You can use
if errorlevel 1 echo Unsuccessful
in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.
Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.
Parameters starting with -
or --
are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.
See also the documentation:
In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):
parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required named arguments:
-i INPUT, --input INPUT
Input file name
There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.
Demo site: https://brendandahl.github.io/trapeze-reader/demos/
Github page: https://github.com/brendandahl/trapeze-reader
Disclaimer: I'm the author.
If you really want to create an array rather than a list use either
String[] names = ["lucas", "Fred", "Mary"]
or
def names = ["lucas", "Fred", "Mary"].toArray()
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="fname" id="fname"/>
<input type="submit" name="click" value="button" />
</form>
<script>
$(document).ready(function(){
$(function(){
$("#myForm").submit(function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
dataType: "json",
contentType: "application/json",
data : $('#myForm').serialize(),
success: function(data){
alert(data);
},
error: function(xhr, desc, err){
console.log(err);
}
});
});
});
});
</script>
</body>
</html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");
Here is the official documentation on replace_all.
Download it from here:
http://www.iis.net/downloads/microsoft/url-rewrite
or if you already have Web Platform Installer on your machine you can install it from there.
If you are already doing databinding:
<asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" />
Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
The standard library arrays are useful for binary I/O, such as translating a list of ints to a string to write to, say, a wave file. That said, as many have already noted, if you're going to do any real work then you should consider using NumPy.
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
try to use
<?php require_once($_SERVER['DOCUMENT_ROOT'].'/web/a.php'); ?>
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
math.fabs()
converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.
In addition to floats, abs()
also works with integers and complex numbers. Its return type depends on the type of its argument.
In [7]: type(abs(-2))
Out[7]: int
In [8]: type(abs(-2.0))
Out[8]: float
In [9]: type(abs(3+4j))
Out[9]: float
In [10]: type(math.fabs(-2))
Out[10]: float
In [11]: type(math.fabs(-2.0))
Out[11]: float
In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))
TypeError: can't convert complex to float
These days IMHO the best short, sane & valid way for an empty img src is like this:
<img src="data:," alt>
or
<img src="data:," alt="Alternative Text">
The second example displays "Alternative Text" (plus broken-image-icon in Chrome and IE).
"data:,"
is a valid URI. An empty media-type defaults to text/plain
. So it represents an empty text file and is equivalent to "data:text/plain,"
alt
. You can omit =""
, it's implicit per HTML spec.
The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"
So you could take a substring starting at the colon with something like this:
String selector = divA.toString().substring(s.indexOf(":") + 2);
With this, you could find your element inside your other element with this:
WebElement input = driver.findElement( By.xpath( selector + "//input" ) );
Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.
Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.
You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:
CREATE TABLE #tmp(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(1000);
SET @sql = N'BULK INSERT #tmp ...' + @variables;
EXEC master.sys.sp_executesql @sql;
SELECT * FROM #tmp;
This makes it tougher to maintain (readability) but gets by the scoping issue:
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
BULK INSERT #tmp ...' + @variables + ';
SELECT * FROM #tmp;';
EXEC master.sys.sp_executesql @sql;
EDIT 2011-01-12
In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:
CREATE TABLE #outer(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SET NOCOUNT ON;
CREATE TABLE #inner(a INT, b INT, c INT);
BULK INSERT #inner ...' + @variables + ';
SELECT * FROM #inner;';
INSERT #outer EXEC master.sys.sp_executesql @sql;
Your model should implement an interface IValidatableObject
. Put your validation code in Validate
method:
public class MyModel : IValidatableObject
{
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Title == null)
yield return new ValidationResult("*", new [] { nameof(Title) });
if (Description == null)
yield return new ValidationResult("*", new [] { nameof(Description) });
}
}
Please notice: this is a server-side validation. It doesn't work on client-side. You validation will be performed only after form submission.
Just telling you about one other possibility: I like using friend definitions for that:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}
The function will be automatically targeted into the surrounding namespace Math
(even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>
.
if you want to not use jQuery, you can use below code:
document.getElementById("mySelect").selectedIndex = "2";
cmd
Tunnel all your internet traffic through a socks proxy:
netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"
View the current proxy settings:
netsh winhttp show proxy
Clear all proxy settings:
netsh winhttp reset proxy
you must change php_admin_value max_execution_time
in your Alias config (\XAMPP\alias\phpmyadmin.conf)
answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded
This happens either, some files are missing in the "Compile Sources" section, or duplicate entries are found for some file(s). In my case, I had duplicate entries for two files, I deleted one entry for each of the files, that solved my problem. Hope this helps.
In PyCharm the parameters are added in the Script Parameters
as you did but, they are enclosed in double quotes ""
and without specifying the Interpreter flags like -s
. Those flags are specified in the Interpreter options
box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0]
holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
In controller:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
Just for those who want to send a nested JSON object with form-data as content type.
I want to send nested custom_field in below
{ "description": "Details about the issue...", "subject": "Support Needed...", "type": "Others", "email": "[email protected]", "priority": 1, "status": 2, **"custom_fields" : { "cf_type_of_issue" : "Complaint" }**, "cc_emails": ["[email protected]","[email protected]"] }
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
Short string similar to examples from OP question
The fastest solution on all browsers is / /g
(regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join
solution. Change
to \s
or add +
or i
to regexp slows down processing.
For string about ~3 milion character results are:
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
I had this error today and discovered it was an incorrectly-formatted year...
select * from es_timeexpense where parsedate > to_date('12/3/2018', 'MM/dd/yyy')
Notice the year has only three 'y's. It should have 4.
Double-check your format.
So far best solution that I've made:
function convertHtmlToJQueryObject(html){
var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
return $(htmlDOMObject.documentElement);
}
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];
I had the problem with not working curl on win8 wamp3 php5.6. Reinstalling wamp (x64 version as I had x64 in system info) made it work fine.
Try This Code :
button.setVisibility(View.INVISIBLE);
There's no such keyword in C++. List of C++ keywords can be found in section 2.11/1 of C++ language standard. restrict
is a keyword in C99 version of C language and not in C++.
Adding yet another solution: HashMap
is pretty much the first class I ported from Java to JavaScript. You could say there is a lot of overhead, but the implementation is almost 100% equal to Java's implementation and includes all interfaces and subclasses.
The project can be found here: https://github.com/Airblader/jsava I'll also attach the (current) source code for the HashMap class, but as stated it also depends on the super class, etc. The OOP framework used is qooxdoo.
Please note that this code is already out-dated and refer to the GitHub project for the current work. As of writing this, there is also an ArrayList
implementation.
qx.Class.define( 'jsava.util.HashMap', {
extend: jsava.util.AbstractMap,
implement: [jsava.util.Map, jsava.io.Serializable, jsava.lang.Cloneable],
construct: function () {
var args = Array.prototype.slice.call( arguments ),
initialCapacity = this.self( arguments ).DEFAULT_INITIAL_CAPACITY,
loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;
switch( args.length ) {
case 1:
if( qx.Class.implementsInterface( args[0], jsava.util.Map ) ) {
initialCapacity = Math.max( ((args[0].size() / this.self( arguments ).DEFAULT_LOAD_FACTOR) | 0) + 1,
this.self( arguments ).DEFAULT_INITIAL_CAPACITY );
loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;
} else {
initialCapacity = args[0];
}
break;
case 2:
initialCapacity = args[0];
loadFactor = args[1];
break;
}
if( initialCapacity < 0 ) {
throw new jsava.lang.IllegalArgumentException( 'Illegal initial capacity: ' + initialCapacity );
}
if( initialCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {
initialCapacity = this.self( arguments ).MAXIMUM_CAPACITY;
}
if( loadFactor <= 0 || isNaN( loadFactor ) ) {
throw new jsava.lang.IllegalArgumentException( 'Illegal load factor: ' + loadFactor );
}
var capacity = 1;
while( capacity < initialCapacity ) {
capacity <<= 1;
}
this._loadFactor = loadFactor;
this._threshold = (capacity * loadFactor) | 0;
this._table = jsava.JsavaUtils.emptyArrayOfGivenSize( capacity, null );
this._init();
},
statics: {
serialVersionUID: 1,
DEFAULT_INITIAL_CAPACITY: 16,
MAXIMUM_CAPACITY: 1 << 30,
DEFAULT_LOAD_FACTOR: 0.75,
_hash: function (hash) {
hash ^= (hash >>> 20) ^ (hash >>> 12);
return hash ^ (hash >>> 7) ^ (hash >>> 4);
},
_indexFor: function (hashCode, length) {
return hashCode & (length - 1);
},
Entry: qx.Class.define( 'jsava.util.HashMap.Entry', {
extend: jsava.lang.Object,
implement: [jsava.util.Map.Entry],
construct: function (hash, key, value, nextEntry) {
this._value = value;
this._next = nextEntry;
this._key = key;
this._hash = hash;
},
members: {
_key: null,
_value: null,
/** @type jsava.util.HashMap.Entry */
_next: null,
/** @type Number */
_hash: 0,
getKey: function () {
return this._key;
},
getValue: function () {
return this._value;
},
setValue: function (newValue) {
var oldValue = this._value;
this._value = newValue;
return oldValue;
},
equals: function (obj) {
if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.HashMap.Entry ) ) {
return false;
}
/** @type jsava.util.HashMap.Entry */
var entry = obj,
key1 = this.getKey(),
key2 = entry.getKey();
if( key1 === key2 || (key1 !== null && key1.equals( key2 )) ) {
var value1 = this.getValue(),
value2 = entry.getValue();
if( value1 === value2 || (value1 !== null && value1.equals( value2 )) ) {
return true;
}
}
return false;
},
hashCode: function () {
return (this._key === null ? 0 : this._key.hashCode()) ^
(this._value === null ? 0 : this._value.hashCode());
},
toString: function () {
return this.getKey() + '=' + this.getValue();
},
/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
_recordAccess: function (map) {
},
/**
* This method is invoked whenever the entry is
* removed from the table.
*/
_recordRemoval: function (map) {
}
}
} )
},
members: {
/** @type jsava.util.HashMap.Entry[] */
_table: null,
/** @type Number */
_size: 0,
/** @type Number */
_threshold: 0,
/** @type Number */
_loadFactor: 0,
/** @type Number */
_modCount: 0,
/** @implements jsava.util.Set */
__entrySet: null,
/**
* Initialization hook for subclasses. This method is called
* in all constructors and pseudo-constructors (clone, readObject)
* after HashMap has been initialized but before any entries have
* been inserted. (In the absence of this method, readObject would
* require explicit knowledge of subclasses.)
*/
_init: function () {
},
size: function () {
return this._size;
},
isEmpty: function () {
return this._size === 0;
},
get: function (key) {
if( key === null ) {
return this.__getForNullKey();
}
var hash = this.self( arguments )._hash( key.hashCode() );
for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];
entry !== null; entry = entry._next ) {
/** @type jsava.lang.Object */
var k;
if( entry._hash === hash && ((k = entry._key) === key || key.equals( k )) ) {
return entry._value;
}
}
return null;
},
__getForNullKey: function () {
for( var entry = this._table[0]; entry !== null; entry = entry._next ) {
if( entry._key === null ) {
return entry._value;
}
}
return null;
},
containsKey: function (key) {
return this._getEntry( key ) !== null;
},
_getEntry: function (key) {
var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() );
for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];
entry !== null; entry = entry._next ) {
/** @type jsava.lang.Object */
var k;
if( entry._hash === hash
&& ( ( k = entry._key ) === key || ( key !== null && key.equals( k ) ) ) ) {
return entry;
}
}
return null;
},
put: function (key, value) {
if( key === null ) {
return this.__putForNullKey( value );
}
var hash = this.self( arguments )._hash( key.hashCode() ),
i = this.self( arguments )._indexFor( hash, this._table.length );
for( var entry = this._table[i]; entry !== null; entry = entry._next ) {
/** @type jsava.lang.Object */
var k;
if( entry._hash === hash && ( (k = entry._key) === key || key.equals( k ) ) ) {
var oldValue = entry._value;
entry._value = value;
entry._recordAccess( this );
return oldValue;
}
}
this._modCount++;
this._addEntry( hash, key, value, i );
return null;
},
__putForNullKey: function (value) {
for( var entry = this._table[0]; entry !== null; entry = entry._next ) {
if( entry._key === null ) {
var oldValue = entry._value;
entry._value = value;
entry._recordAccess( this );
return oldValue;
}
}
this._modCount++;
this._addEntry( 0, null, value, 0 );
return null;
},
__putForCreate: function (key, value) {
var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
i = this.self( arguments )._indexFor( hash, this._table.length );
for( var entry = this._table[i]; entry !== null; entry = entry._next ) {
/** @type jsava.lang.Object */
var k;
if( entry._hash === hash
&& ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {
entry._value = value;
return;
}
}
this._createEntry( hash, key, value, i );
},
__putAllForCreate: function (map) {
var iterator = map.entrySet().iterator();
while( iterator.hasNext() ) {
var entry = iterator.next();
this.__putForCreate( entry.getKey(), entry.getValue() );
}
},
_resize: function (newCapacity) {
var oldTable = this._table,
oldCapacity = oldTable.length;
if( oldCapacity === this.self( arguments ).MAXIMUM_CAPACITY ) {
this._threshold = Number.MAX_VALUE;
return;
}
var newTable = jsava.JsavaUtils.emptyArrayOfGivenSize( newCapacity, null );
this._transfer( newTable );
this._table = newTable;
this._threshold = (newCapacity * this._loadFactor) | 0;
},
_transfer: function (newTable) {
var src = this._table,
newCapacity = newTable.length;
for( var j = 0; j < src.length; j++ ) {
var entry = src[j];
if( entry !== null ) {
src[j] = null;
do {
var next = entry._next,
i = this.self( arguments )._indexFor( entry._hash, newCapacity );
entry._next = newTable[i];
newTable[i] = entry;
entry = next;
} while( entry !== null );
}
}
},
putAll: function (map) {
var numKeyToBeAdded = map.size();
if( numKeyToBeAdded === 0 ) {
return;
}
if( numKeyToBeAdded > this._threshold ) {
var targetCapacity = (numKeyToBeAdded / this._loadFactor + 1) | 0;
if( targetCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {
targetCapacity = this.self( arguments ).MAXIMUM_CAPACITY;
}
var newCapacity = this._table.length;
while( newCapacity < targetCapacity ) {
newCapacity <<= 1;
}
if( newCapacity > this._table.length ) {
this._resize( newCapacity );
}
}
var iterator = map.entrySet().iterator();
while( iterator.hasNext() ) {
var entry = iterator.next();
this.put( entry.getKey(), entry.getValue() );
}
},
remove: function (key) {
var entry = this._removeEntryForKey( key );
return entry === null ? null : entry._value;
},
_removeEntryForKey: function (key) {
var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
i = this.self( arguments )._indexFor( hash, this._table.length ),
prev = this._table[i],
entry = prev;
while( entry !== null ) {
var next = entry._next,
/** @type jsava.lang.Object */
k;
if( entry._hash === hash
&& ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {
this._modCount++;
this._size--;
if( prev === entry ) {
this._table[i] = next;
} else {
prev._next = next;
}
entry._recordRemoval( this );
return entry;
}
prev = entry;
entry = next;
}
return entry;
},
_removeMapping: function (obj) {
if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {
return null;
}
/** @implements jsava.util.Map.Entry */
var entry = obj,
key = entry.getKey(),
hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),
i = this.self( arguments )._indexFor( hash, this._table.length ),
prev = this._table[i],
e = prev;
while( e !== null ) {
var next = e._next;
if( e._hash === hash && e.equals( entry ) ) {
this._modCount++;
this._size--;
if( prev === e ) {
this._table[i] = next;
} else {
prev._next = next;
}
e._recordRemoval( this );
return e;
}
prev = e;
e = next;
}
return e;
},
clear: function () {
this._modCount++;
var table = this._table;
for( var i = 0; i < table.length; i++ ) {
table[i] = null;
}
this._size = 0;
},
containsValue: function (value) {
if( value === null ) {
return this.__containsNullValue();
}
var table = this._table;
for( var i = 0; i < table.length; i++ ) {
for( var entry = table[i]; entry !== null; entry = entry._next ) {
if( value.equals( entry._value ) ) {
return true;
}
}
}
return false;
},
__containsNullValue: function () {
var table = this._table;
for( var i = 0; i < table.length; i++ ) {
for( var entry = table[i]; entry !== null; entry = entry._next ) {
if( entry._value === null ) {
return true;
}
}
}
return false;
},
clone: function () {
/** @type jsava.util.HashMap */
var result = null;
try {
result = this.base( arguments );
} catch( e ) {
if( !qx.Class.isSubClassOf( e.constructor, jsava.lang.CloneNotSupportedException ) ) {
throw e;
}
}
result._table = jsava.JsavaUtils.emptyArrayOfGivenSize( this._table.length, null );
result.__entrySet = null;
result._modCount = 0;
result._size = 0;
result._init();
result.__putAllForCreate( this );
return result;
},
_addEntry: function (hash, key, value, bucketIndex) {
var entry = this._table[bucketIndex];
this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );
if( this._size++ >= this._threshold ) {
this._resize( 2 * this._table.length );
}
},
_createEntry: function (hash, key, value, bucketIndex) {
var entry = this._table[bucketIndex];
this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );
this._size++;
},
keySet: function () {
var keySet = this._keySet;
return keySet !== null ? keySet : ( this._keySet = new this.KeySet( this ) );
},
values: function () {
var values = this._values;
return values !== null ? values : ( this._values = new this.Values( this ) );
},
entrySet: function () {
return this.__entrySet0();
},
__entrySet0: function () {
var entrySet = this.__entrySet;
return entrySet !== null ? entrySet : ( this.__entrySet = new this.EntrySet( this ) );
},
/** @private */
HashIterator: qx.Class.define( 'jsava.util.HashMap.HashIterator', {
extend: jsava.lang.Object,
implement: [jsava.util.Iterator],
type: 'abstract',
/** @protected */
construct: function (thisHashMap) {
this.__thisHashMap = thisHashMap;
this._expectedModCount = this.__thisHashMap._modCount;
if( this.__thisHashMap._size > 0 ) {
var table = this.__thisHashMap._table;
while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {
// do nothing
}
}
},
members: {
__thisHashMap: null,
/** @type jsava.util.HashMap.Entry */
_next: null,
/** @type Number */
_expectedModCount: 0,
/** @type Number */
_index: 0,
/** @type jsava.util.HashMap.Entry */
_current: null,
hasNext: function () {
return this._next !== null;
},
_nextEntry: function () {
if( this.__thisHashMap._modCount !== this._expectedModCount ) {
throw new jsava.lang.ConcurrentModificationException();
}
var entry = this._next;
if( entry === null ) {
throw new jsava.lang.NoSuchElementException();
}
if( (this._next = entry._next) === null ) {
var table = this.__thisHashMap._table;
while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {
// do nothing
}
}
this._current = entry;
return entry;
},
remove: function () {
if( this._current === null ) {
throw new jsava.lang.IllegalStateException();
}
if( this.__thisHashMap._modCount !== this._expectedModCount ) {
throw new jsava.lang.ConcurrentModificationException();
}
var key = this._current._key;
this._current = null;
this.__thisHashMap._removeEntryForKey( key );
this._expectedModCount = this.__thisHashMap._modCount;
}
}
} ),
_newKeyIterator: function () {
return new this.KeyIterator( this );
},
_newValueIterator: function () {
return new this.ValueIterator( this );
},
_newEntryIterator: function () {
return new this.EntryIterator( this );
},
/** @private */
ValueIterator: qx.Class.define( 'jsava.util.HashMap.ValueIterator', {
extend: jsava.util.HashMap.HashIterator,
construct: function (thisHashMap) {
this.base( arguments, thisHashMap );
},
members: {
next: function () {
return this._nextEntry()._value;
}
}
} ),
/** @private */
KeyIterator: qx.Class.define( 'jsava.util.HashMap.KeyIterator', {
extend: jsava.util.HashMap.HashIterator,
construct: function (thisHashMap) {
this.base( arguments, thisHashMap );
},
members: {
next: function () {
return this._nextEntry().getKey();
}
}
} ),
/** @private */
EntryIterator: qx.Class.define( 'jsava.util.HashMap.EntryIterator', {
extend: jsava.util.HashMap.HashIterator,
construct: function (thisHashMap) {
this.base( arguments, thisHashMap );
},
members: {
next: function () {
return this._nextEntry();
}
}
} ),
/** @private */
KeySet: qx.Class.define( 'jsava.util.HashMap.KeySet', {
extend: jsava.util.AbstractSet,
construct: function (thisHashMap) {
this.base( arguments );
this.__thisHashMap = thisHashMap;
},
members: {
__thisHashMap: null,
iterator: function () {
return this.__thisHashMap._newKeyIterator();
},
size: function () {
return this.__thisHashMap._size;
},
contains: function (obj) {
return this.__thisHashMap.containsKey( obj );
},
remove: function (obj) {
return this.__thisHashMap._removeEntryForKey( obj ) !== null;
},
clear: function () {
this.__thisHashMap.clear();
}
}
} ),
/** @private */
Values: qx.Class.define( 'jsava.util.HashMap.Values', {
extend: jsava.util.AbstractCollection,
construct: function (thisHashMap) {
this.base( arguments );
this.__thisHashMap = thisHashMap;
},
members: {
__thisHashMap: null,
iterator: function () {
return this.__thisHashMap._newValueIterator();
},
size: function () {
return this.__thisHashMap._size;
},
contains: function (obj) {
return this.__thisHashMap.containsValue( obj );
},
clear: function () {
this.__thisHashMap.clear();
}
}
} ),
/** @private */
EntrySet: qx.Class.define( 'jsava.util.HashMap.EntrySet', {
extend: jsava.util.AbstractSet,
construct: function (thisHashMap) {
this.base( arguments );
this.__thisHashMap = thisHashMap;
},
members: {
__thisHashMap: null,
iterator: function () {
return this.__thisHashMap._newEntryIterator();
},
size: function () {
return this.__thisHashMap._size;
},
contains: function (obj) {
if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {
return false;
}
/** @implements jsava.util.Map.Entry */
var entry = obj,
candidate = this.__thisHashMap._getEntry( entry.getKey() );
return candidate !== null && candidate.equals( entry );
},
remove: function (obj) {
return this.__thisHashMap._removeMapping( obj ) !== null;
},
clear: function () {
this.__thisHashMap.clear();
}
}
} )
}
} );
>> man -k mysqldump [enter in the terminal]
you will find the below explanation
--no-create-info, -t
Do not write CREATE TABLE statements that re-create each dumped table. Note This option does not not exclude statements creating log file groups or tablespaces from mysqldump output; however, you can use the --no-tablespaces option for this purpose.
--no-data, -d
Do not write any table row information (that is, do not dump table contents). This is useful if you want to dump only the CREATE TABLE statement for the table (for example, to create an empty copy of the table by loading the dump file).
# To export to file (data only)
mysqldump -t -u [user] -p[pass] -t mydb > mydb_data.sql
# To export to file (structure only)
mysqldump -d -u [user] -p[pass] -d mydb > mydb_structure.sql
Finally this worked for me
private String buildBasicAuthorizationString(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
All previous answers are correct, you have three options for what you are asking
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}
You can simply check whether the element length is undefined or not just by using
var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
//get the length here if the element is not undefined
elementLength = theHref.length
// do stuff
} else {
// do other stuff
}
A better way to do a break line is using span with CSS style parameter white-space: nowrap;
span.nobreak {
white-space: nowrap;
}
or
span.nobreak {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Example directly in your HTML
<span style='overflow:hidden; white-space: nowrap;'> YOUR EXTENSIVE TEXT THAT YOU CAN´T BREAK LINE ....</span>
You're looking for keydown/press/up
$("#inputID").keydown(function(event) {
alert(event.keyCode);
});
or using bind $("#inputID").bind('onkeydown', ...
I had a similar problem. Just to help out someone with the same issue:
My error was the user file attribute for the files in /var/www. After changing them back to the user "www-data", the problem was gone.
Why not keep it simple?!
GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()
giving you,
print(GB)
abc xyz
2013 6 80 250
8 40 -5
2014 1 25 15
2 60 80
and then you can plot like asked using,
GB.plot('abc','xyz',kind='scatter')
This is how I solved it:
Integer.toHexString(System.identityHashCode(object));
The @overload
decorator was added with type hints (PEP 484).
While this doesn't change the behaviour of Python, it does make it easier to understand what is going on, and for mypy to detect errors.
See: Type hints and PEP 484
I would simply use,
np.asarray(input, dtype=np.float)[0]
input
is an ndarray
of the right dtype, there is no overhead, since np.asarray
does nothing in this case.input
is a list
, np.asarray
makes sure the output is of the right type.I had the same exception in JPA 2 using eclipse link. I had an @embedded class with one to one relationship with an entity. By mistake ,in the embedded class, i had also the annotation @Table("TRADER"). When the DB was created by the JPA from the entities it also created a table TRADER (which was a wrong as the Trader entity was embedded to the main entity) and the existence of that table was causing the above exception every time i was trying to persist my entity. After deleting the TRADER table the exception disappered.
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
The idea behind reporting progress with the background worker is through sending a 'percent completed' event. You are yourself responsible for determining somehow 'how much' work has been completed. Unfortunately this is often the most difficult part.
In your case, the bulk of the work is database-related. There is to my knowledge no way to get progress information from the DB directly. What you can try to do however, is split up the work dynamically. E.g., if you need to read a lot of data, a naive way to implement this could be.
Divide the actual reading in smaller chunks, reporting progress every time one chunk is completed:
for (int i = 0; i < count; i++)
{
bgWorker.ReportProgress((100 * i) / count);
// ... (read data for step i)
}
I don't want to include the Support library just for getColor, so I'm using something like
public static int getColorWrapper(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
I guess the code should work just fine, and the deprecated getColor
cannot disappear from API < 23.
And this is what I'm using in Kotlin:
/**
* Returns a color associated with a particular resource ID.
*
* Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
*/
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);
We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.
Our solution was to use the replacer
param of JSON.stringify()
, e.g.:
function jsonFriendlyErrorReplacer(key, value) {_x000D_
if (value instanceof Error) {_x000D_
return {_x000D_
// Pull all enumerable properties, supporting properties on custom Errors_x000D_
...value,_x000D_
// Explicitly pull Error's non-enumerable properties_x000D_
name: value.name,_x000D_
message: value.message,_x000D_
stack: value.stack,_x000D_
}_x000D_
}_x000D_
_x000D_
return value_x000D_
}_x000D_
_x000D_
let obj = {_x000D_
error: new Error('nested error message')_x000D_
}_x000D_
_x000D_
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))_x000D_
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))
_x000D_
you can use getChildFragmentManager()
function.
example:
Parent fragment :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.parent_fragment, container,
false);
}
//child fragment
FragmentManager childFragMan = getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
ChildFragment fragB = new ChildFragment ();
childFragTrans.add(R.id.FRAGMENT_PLACEHOLDER, fragB);
childFragTrans.addToBackStack("B");
childFragTrans.commit();
return rootView;
}
Parent layout (parent_fragment.xml
):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<FrameLayout
android:id="@+id/FRAGMENT_PLACEHOLDER"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Child Fragment:
public class ChildFragment extends Fragment implements View.OnClickListener{
View v ;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.child_fragment, container, false);
v = rootView;
return rootView;
}
@Override
public void onClick(View view) {
}
}
You are missing 'json' dataType in the $.post()
method:
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
.done(function(data){
alert(data);
}, "json");
//-^^^^^^-------here
Updates:
try with this:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
I like to add these functions in the head.
window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};
Now log won't break IE I can enable it or disable it in one place I can log inline
$(".classname").log(); //show an array of all elements with classname class
If you don't have ReSharper installed and still want to use the shortcut Shift
+Alt
+L
to move focus to the current file in Solution Explorer in Visual Studio 2013 then please follow these steps:
In the Show commands containing box type "solutionexplorer" and then in the list below look for the SyncWithActiveDocument command:
Click in textbox under "Press short keys" label and press: Shift
+Alt
+L
and click the Assign button and you are done:
To verify open any file in Visual Studio and press the shortcut keys Shift
+Alt
+L
and you'll see the file in the solution explorer. Enjoy!
the problem occurs because of the name of column is in camel case internally it wraps it in " "(double quotes) to solve this, at the time of inserting values in table use single quotes ('')
e.g. insert into schema_name.table_name values(' ',' ',' ');
If you also want to name the constraint, use this:
ALTER TABLE myTable
ADD CONSTRAINT constraintName
UNIQUE (columnName);
You need to use the CONCAT()
function in MySQL for string concatenation:
UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;
All of the above - for whatever reason I was doing some big refactor and starting to get this. I renamed the package my interface was in and that cleared it. Hope that helps.
webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();
The above line works fine. Please remove the space after href.
Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.
Please understand the use case before using this solution:
trim does not work while doing select query
This works
select replace(name , ' ','') from test;
While this doesn't
select trim(name) from test;
There are several things wrong with your script.
Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).
It's good practice to surround your variable references with curly braces, too. Your code might look like:
#!/bin/sh
command="/bin/date -u" #...Example Only
safeRunCommand() {
cmnd="$@" #...insure whitespace passed and preserved
$cmnd
ERROR_CODE=$? #...so we have it for the command we want
if [ ${ERROR_CODE} != 0 ]; then
printf "Error when executing command: '${command}'\n"
exit ${ERROR_CODE} #...consider 'return()' here
fi
}
safeRunCommand $command
command="cp"
safeRunCommand $command
I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.
Try Eric Meyer's reset.css.
The rest of the sentence is:
where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.
This basically means that the following XML element
<foo>hello
wor
ld</foo>
could be represented like this in a denormalized node:
Element foo
Text node: ""
Text node: "Hello "
Text node: "wor"
Text node: "ld"
When normalized, the node will look like this
Element foo
Text node: "Hello world"
And the same goes for attributes: <foo bar="Hello world"/>
, comments, etc.
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
A functional approach.
var kvToParam = R.mapObjIndexed((val, key) => {_x000D_
return '&' + key + '=' + encodeURIComponent(val);_x000D_
});_x000D_
_x000D_
var objToParams = R.compose(_x000D_
R.replace(/^&/, '?'),_x000D_
R.join(''),_x000D_
R.values,_x000D_
kvToParam_x000D_
);_x000D_
_x000D_
var o = {_x000D_
username: 'sloughfeg9',_x000D_
password: 'traveller'_x000D_
};_x000D_
_x000D_
console.log(objToParams(o));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
_x000D_
$?
is the exit status of a command, such that you can daisy-chain a series of commands.
Example
command1 && command2 && command3
command2
will run if command1's
$?
yields a success (0)
and command3
will execute if $?
of command2
will yield a success
I close them, but they always come back
When you say "they always come back" do you mean "next time you restart Visual Studio" or "immediately"?
One quirk of Visual Studio (at least VS2005) is that settings aren't saved until you exit. That means that if VS crashes at all while you are using it, any layout changes you made will be lost. The way around this is to always gracefully exit when you have set up everything like you want it to be.
Not sure if this will help your particular situation though.
Run these codes in thread or AsyncTask. In order to avoid duplicated callings of same _url(one time for getContentLength(), one time of openStream()), use IOUtils.toByteArray of Apache.
void downloadFile(String _url, String _name) {
try {
URL u = new URL(_url);
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = IOUtils.toByteArray(stream);
FileOutputStream fos = mContext.openFileOutput(_name, Context.MODE_PRIVATE);
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
You can try the same with replacewith()
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').replaceWith(linkText);
// cancel the default action of the link by returning false
return false;
});
The .replaceWith()
method removes content from the DOM and inserts new content in its place with a single call.
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
If you use Python3, you can use ipaddress
module http://docs.python.org/py3k/library/ipaddress.html. Example:
>>> import ipaddress
>>> ipv6 = "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
>>> ipv4 = "192.168.2.10"
>>> ipv4invalid = "266.255.9.10"
>>> str = "Tay Tay"
>>> ipaddress.ip_address(ipv6)
IPv6Address('2001:db8:a0b:12f0::1')
>>> ipaddress.ip_address(ipv4)
IPv4Address('192.168.2.10')
>>> ipaddress.ip_address(ipv4invalid)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: '266.255.9.10' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address(str)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: 'Tay Tay' does not appear to be an IPv4 or IPv6 address
My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->
Try,
string[] files = new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();
Above line may throw UnauthorizedAccessException. To handle this check out below link
If you're looking at using this for relative timing (for example for games or animation) I'd rather use CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
Which is the recommended way; NSDate
draws from the networked synch-clock and will occasionally hiccup when re-synching it against the network.
It returns the current absolute time, in seconds.
If you want only the decimal part (often used when syncing animations),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT
under the hood).
If one of them is faster, it's going to be DISTINCT
. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY
is not taking advantage of any group members, just their keys. DISTINCT
makes this explicit, so you can get away with a slightly dumber optimizer.
When in doubt, test!
Maybe try this
Select cust.*
From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null
Following the answer from DruidKuma and jumping_monkey
You can also include optional and make your code a bit nicer and cleaner:
public static MyService getService(String type) {
return Optional.ofNullable(myServiceCache.get(type))
.orElseThrow(() -> new RuntimeException("Unknown service type: " + type));
}
Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.
Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J
In a nutshell: You cannot access child scopes from a parent scope.
Your solutions:
$emit
sends events upwards to parents until the root scope and $broadcast
dispatches events downwards. This might help you to keep things semantically correct.Assume a dataframe with 19 rows
index=range(0,19)
index
columns=['A']
test = pd.DataFrame(index=index, columns=columns)
Keeping Column A as a constant
test['A']=10
Keeping column b as a variable given by a loop
for x in range(0,19):
test.loc[[x], 'b'] = pd.Series([x], index = [x])
You can replace the first x in pd.Series([x], index = [x])
with any value
Enter the number and create an Arraylist
, and the while loop will record all the digits into the Arraylist
. Then we can take out the size of array, which will be the length of the integer value you entered.
ArrayList<Integer> a=new ArrayList<>();
while(number > 0)
{
remainder = num % 10;
a.add(remainder);
number = number / 10;
}
int m=a.size();
In a more functional programming style, you could use array_reduce
$groupedById = array_reduce($data, function (array $accumulator, array $element) {
$accumulator[$element['id']][] = $element;
return $accumulator;
}, []);
I ran into the same issue, this was an exercise as part of a tutorial on lynda.com if I'm not wrong. The mistake I made was not selecting the runtime as Python 3.6 which is an option in the lamda function console.
For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:
sudo apt-get install -y python-setuptools
For python3:
sudo apt-get install -y python3-setuptools
After that, install your package again normally, using
sudo python setup.py install
That's all.
OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.
async public static void LengthyOperation(Control control, Action action)
{
try
{
control.Enabled = false;
Application.UseWaitCursor = true;
Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
Log.Info("Task Start");
doWork.Start();
Log.Info("Before Await");
await doWork;
Log.Info("After await");
}
finally
{
Log.Info("Finally");
Application.UseWaitCursor = false;
control.Enabled = true;
}
Here's the code form the main form
private void btnSleep_Click(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
Log.Info("Launching lengthy operation...");
CursorWait.LengthyOperation(control, () => DummyAction());
Log.Info("...Lengthy operation launched.");
}
}
private void DummyAction()
{
try
{
var _log = NLog.LogManager.GetLogger("TmpLogger");
_log.Info("Action - Sleep");
TimeSpan sleep = new TimeSpan(0, 0, 16);
Thread.Sleep(sleep);
_log.Info("Action - Wakeup");
}
finally
{
}
}
I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)
Here's the main log, which shows things happening in the order we expect:
16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally
Have you considered lsof
(list open files)?
The Oracle and OpenJDK JVMs are the same and have the same GC features (as of the latest versions 10+). Prior to Oracle managing the OpenJDK JVM there were concrete differences that made that old Openjdk JVM almost unusable in many environments. The JVMs are now the same.
The JDKs which include the JVM as part of the Kit, differ by licensing, release and maintenance schedule, and the software libraries included in the JDK. Crucial differences to me also mean things that would make code not run if not present. Not only licensing.
diff --brief -r openjdk oraclejdk
Crucially the following files are missing in addition to a bunch of others on the linux JDK (So if you 'claimed' that code didn't work on OpenJDK and did so on OracleJDK while you were using javafx then you were correct):
Only in jdk-10.0.1/bin: javapackager
Only in jdk-10.0.1/bin: javaws
Only in jdk-10.0.1/bin: jcontrol
Only in jdk-10.0.1/bin: jmc
Only in jdk-10.0.1/bin: jweblauncher
Only in jdk-10.0.1/lib: ant-javafx.jar
Only in jdk-10.0.1/lib: deploy
Only in jdk-10.0.1/lib: deploy.jar
Only in jdk-10.0.1/lib: desktop
Only in jdk-10.0.1/lib: fontconfig.bfc
Only in jdk-10.0.1/lib: fontconfig.properties.src
Only in jdk-10.0.1/lib: fontconfig.RedHat.6.bfc
Only in jdk-10.0.1/lib: fontconfig.RedHat.6.properties.src
Only in jdk-10.0.1/lib: fontconfig.SuSE.11.bfc
Only in jdk-10.0.1/lib: fontconfig.SuSE.11.properties.src
Only in jdk-10.0.1/lib: fonts
Only in jdk-10.0.1/lib: javafx.properties
Only in jdk-10.0.1/lib: javafx-swt.jar
Only in jdk-10.0.1/lib: java.jnlp.jar
Only in jdk-10.0.1/lib: javaws.jar
Only in jdk-10.0.1/lib: jdk.deploy.jar
Only in jdk-10.0.1/lib: jdk.javaws.jar
Only in jdk-10.0.1/lib: jdk.plugin.jar
Only in jdk-10.0.1/lib: jfr
Only in jdk-10.0.1/lib: libavplugin-53.so
Only in jdk-10.0.1/lib: libavplugin-54.so
Only in jdk-10.0.1/lib: libavplugin-55.so
Only in jdk-10.0.1/lib: libavplugin-56.so
Only in jdk-10.0.1/lib: libavplugin-57.so
Only in jdk-10.0.1/lib: libavplugin-ffmpeg-56.so
Only in jdk-10.0.1/lib: libavplugin-ffmpeg-57.so
Only in jdk-10.0.1/lib: libbci.so
Only in jdk-10.0.1/lib: libcmm.so
Only in jdk-10.0.1/lib: libdecora_sse.so
Only in jdk-10.0.1/lib: libdeploy.so
Only in jdk-10.0.1/lib: libfxplugins.so
Only in jdk-10.0.1/lib: libglassgtk2.so
Only in jdk-10.0.1/lib: libglassgtk3.so
Only in jdk-10.0.1/lib: libglass.so
Only in jdk-10.0.1/lib: libgstreamer-lite.so
Only in jdk-10.0.1/lib: libjavafx_font_freetype.so
Only in jdk-10.0.1/lib: libjavafx_font_pango.so
Only in jdk-10.0.1/lib: libjavafx_font.so
Only in jdk-10.0.1/lib: libjavafx_iio.so
Only in jdk-10.0.1/lib: libjfxmedia.so
Only in jdk-10.0.1/lib: libjfxwebkit.so
Only in jdk-10.0.1/lib: libnpjp2.so
Only in jdk-10.0.1/lib: libprism_common.so
Only in jdk-10.0.1/lib: libprism_es2.so
Only in jdk-10.0.1/lib: libprism_sw.so
Only in jdk-10.0.1/lib: librm.so
Only in jdk-10.0.1/lib: libt2k.so
Only in jdk-10.0.1/lib: locale
Only in jdk-10.0.1/lib: missioncontrol
Only in jdk-10.0.1/lib: oblique-fonts
Only in jdk-10.0.1/lib: plugin.jar
Only in jdk-10.0.1/lib: plugin-legacy.jar
Only in jdk-10.0.1/lib/security: blacklist
Only in jdk-10.0.1/lib/security: public_suffix_list.dat
Only in jdk-10.0.1/lib/security: trusted.libraries
Only in openjdk-10.0.1: man`
I'm assuming that your container element is probably position:relative;
. This is will mean that the dialog box will be positioned accordingly to the container, not the page.
Can you change the markup to this?
<html>
<body>
<!-- Need to place this div at the top right of the page-->
<div class="ajax-message">
<div class="row">
<div class="span9">
<div class="alert">
<a class="close icon icon-remove"></a>
<div class="message-content">
Some message goes here
</div>
</div>
</div>
</div>
</div>
<div class="container">
<!-- Page contents starts here. These are dynamic-->
<div class="row">
<div class="span12 inner-col">
<h2>Documents</h2>
</div>
</div>
</div>
</body>
</html>
With the dialog box outside the main container then you can use absolute positioning relative to the page.
I realize you're wanting to accomplish this with CSS, but just a reminder in case it's a small, simple image - you can always pop it open in Notepad++ and change the path/whateverelement's fill:
<path style="fill:#010002;" d="M394.854,205.444c9.218-15.461,19.102-30.181,14.258-49.527
...
C412.843,226.163,402.511,211.451,394.854,205.444z"/>
It could save a ton of ugly script. Sorry if it's off-base, but sometimes the simple solutions can be overlooked.
...even swapping multiple svg images might be smaller in size than some of the code snippets for this question.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Use pipe()
and write to the appropriate file descriptor.
https://docs.python.org/library/os.html#file-descriptor-operations
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY
each time you need it - there's no need to create a new object each time.
I figured out that this behaves like a mousedown event:
button:active:hover {}
With hooks:
import { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { history as historyShape } from 'react-router-prop-types'
const DebugHistory = ({ history }) => {
useEffect(() => {
console.log('> Router', history.action, history.location])
}, [history.location.key])
return null
}
DebugHistory.propTypes = { history: historyShape }
export default withRouter(DebugHistory)
Import and render as <DebugHistory>
component
If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.
To trigger an event after ng-repeat has rendered try this directive:
var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
Complete example in angular: http://jsfiddle.net/ADukg/6880/
I got the directive from here: Use AngularJS just for routing purposes
What about providing a custom N-Factor authentication mechanism?
Before combining available methods, let's assume we can perform the following:
1) Hard-code inside the Java program
2) Store in a .properties file
3) Ask user to type password from command line
4) Ask user to type password from a form
5) Ask user to load a password-file from command line or a form
6) Provide the password through network
7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)
1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.
2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.
3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd
.
This doesn't require the password to be stored and will stay in memory. However, history
commands and OS logs, may be your worst enemy here.
To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.
One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.
4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.
5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.
6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.
I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.
We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.
Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.
We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.
It is terrible, but you can try to use
select
SUBSTRING(Table1.Col1,0,PATINDEX('%|%=',Table1.Col1)) as myString
from
Table1
This code is probably not 100% right though. need to be adjusted
Before doing anything else, confirm if your backup is Full or Differential. If you're trying to create a new database out of a differential backup, no matter what you do you will encounter the error.
ssh-keygen -y
ssh-keygen -y
will prompt you for the passphrase (if there is one).
If you input the correct passphrase, it will show you the associated public key.
If you input the wrong passphrase, it will display load failed
.
If the key has no passphrase, it will not prompt you for a passphrase and will immediately show you the associated public key.
e.g.,
Create a new public/private key pair, with or without a passphrase:
$ ssh-keygen -f /tmp/my_key
...
Now see if you can access the key pair:
$ ssh-keygen -y -f /tmp/my_key
Create a new public/private key pair, with or without a passphrase:
$ ssh-keygen -f /tmp/my_key
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /tmp/my_key.
Your public key has been saved in /tmp/my_key.pub.
The key fingerprint is:
de:24:1b:64:06:43:ca:76:ba:81:e5:f2:59:3b:81:fe [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
| .+ |
| . . o |
| = . + |
| = + + |
| o = o S . |
| + = + * |
| = o o . |
| . . |
| E |
+-----------------+
Attempt to access the key pair by inputting the correct passphrase.
Note that the public key will be shown and the exit status ($?
) will be 0
to indicate success:
$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBJhVYDYxXOvcQw0iJTPY64anbwSyzI58hht6xCGJ2gzGUJDIsr1NDQsclka6s0J9TNhUEBBzKvh9nTAYibXwwhIqBwJ6UwWIfA3HY13WS161CUpuKv2A/PrfK0wLFBDBlwP6WjwJNfi4NwxA21GUS/Vcm/SuMwaFid9bM2Ap4wZIahx2fxyJhmHugGUFF9qYI4yRJchaVj7TxEmquCXgVf4RVWnOSs9/MTH8YvH+wHP4WmUzsDI+uaF1SpCyQ1DpazzPWAQPgZv9R8ihOrItLXC1W6TPJkt1CLr/YFpz6vapdola8cRw6g/jTYms00Yxf2hn0/o8ORpQ9qBpcAjJN
$ echo $?
0
Attempt to access the key pair by inputting an incorrect passphrase.
Note that the "load failed" error message will be displayed (message may differ depending on OS) and the exit status ($?
) will be 1
to indicate an error:
$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
load failed
$ echo $?
1
Attempt to access a key pair that has no passphrase. Note that there is no prompt for the passphrase, the public key will be displayed, and the exit status ($?
) will be 0
to indicate success:
$ ssh-keygen -y -f /tmp/my_key_with_no_passphrase
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLinxx9T4HE6Brw2CvFacvFrYcOSoQUmwL4Cld4enpg8vEiN8DB2ygrhFtKVo0qMAiGWyqz9gXweXhdmAIsVXqhOJIQvD8FqddA/SMgqM++2M7GxgH68N+0V+ih7EUqf8Hb2PIeubhkQJQGzB3FjYkvRLZqE/oC1Q5nL4B1L1zDQYPSnQKneaRNG/NGIaoVwsy6gcCZeqKHywsXBOHLF4F5nf/JKqfS6ojStvzajf0eyQcUMDVhdxTN/hIfEN/HdYbOxHtwDoerv+9f6h2OUxZny1vRNivZxTa+9Qzcet4tkZWibgLmqRyFeTcWh+nOJn7K3puFB2kKoJ10q31Tq19
$ echo $?
0
Note that the order of arguments is important. -y
must come before -f input_keyfile
, else you will get the error Too many arguments.
.
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject)
;
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
git push --tags production
This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.
There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.
(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.
Use LinearLayout.LayoutParams
instead of MarginLayoutParams
. Here's the documentation.
I've had various problems (see below) installing upgraded SSL modules, even inside a virtualenv, on top of older OS-provided Python versions, so I now use pyenv
.
pyenv makes it very easy to install new Python versions and supports virtualenvs. Getting started is much easier than the recipes for virtualenv listed in other answers:
brew install pyenv
and on Linux, use pyenv-installerThis works very well to insulate the "new Python" version and virtualenv from system Python. Because you can easily use a more recent Python (post 2.7.9), the SSL modules are already upgraded, and of course like any modern virtualenv setup you are insulated from the system Python modules.
A couple of nice tutorials:
pyenv global 3.6.1
(global to current user) or pyenv local 2.7.13
(local to current directory).The pyenv-virtualenv
plugin is now built in - type pyenv commands | grep virtualenv
to check. I wouldn't use the pyenv-virtualenvwrapper plugin to start with - see how you get on with pyenv-virtualenv which is more integrated into pyenv, as this covers most of what virtualenvwrapper does.
pyenv
is modelled on rbenv
(a good tool for Ruby version switching) and its only dependency is bash.
pyvenv
- that is a virtualenv equivalent that's part of recent Python 3 versions, and doesn't handle Python version switchingTwo warnings about pyenv:
dash
, which is /bin/sh
on Ubuntu or Debian.bash --login
using a terminal), which is not always easy to achieve with automation tools such as Ansible.Hence pyenv is best for interactive use, and less good for scripting servers.
One reason to use pyenv
was that there were often problems with upgrading Python SSL modules when using older system-provided Python versions. This may be less of a problem now that current Linux distributions support Python 3.x.
0.0.0.0/0
for all IPv4 addresses
::0/0
for all IPv6 addresses
all
to match any IP address
samehost
to match any of the server's own IP addresses
samenet
to match any address in any subnet that the server is directly connected to.
e.g.
host all all 0.0.0.0/0 md5
I just added position:absolute and that solved my problem.
Go to the repository folder. Delete relevant submodules from .gitmodules. Select show hidden files. Go to .git folder, delete the submodules from module folder and config.
As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:
#content {
display: table;
}
#pageFooter {
display: table-footer-group;
}
#pageFooter:after {
counter-increment: page;
content: counter(page);
}
And the HTML code is:
<div id="content">
<div id="pageFooter">Page </div>
multi-page content here...
</div>
This way you can customize your page number by editing parametrs to #pageFooter. My example:
#pageFooter:after {
counter-increment: page;
content:"Page " counter(page);
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
-moz-border-radius: 5px;
-moz-box-shadow: 0px 0px 4px #222;
background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
}
This trick worked for me fine. Hope it will help you.
if there are multiple java processes and you wish to kill them with one command try the below command
kill -9 $(ps -ef | pgrep -f "java")
replace "java" with any process string identifier , to kill anything else.
Another way:
md5=$(md5sum ${my_iso_file} | sed '/ .*//' )
This might be another option. The trick is in the wrapper
function that returns another function which is passed in to pool.map
. The code below reads an input array and for each (unique) element in it, returns how many times (ie counts) that element appears in the array, For example if the input is
np.eye(3) = [ [1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
then zero appears 6 times and one 3 times
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def extract_counts(label_array):
labels = np.unique(label_array)
out = extract_counts_helper([label_array], labels)
return out
def extract_counts_helper(args, labels):
n = max(1, cpu_count() - 1)
pool = ThreadPool(n)
results = {}
pool.map(wrapper(args, results), labels)
pool.close()
pool.join()
return results
def wrapper(argsin, results):
def inner_fun(label):
label_array = argsin[0]
counts = get_label_counts(label_array, label)
results[label] = counts
return inner_fun
def get_label_counts(label_array, label):
return sum(label_array.flatten() == label)
if __name__ == "__main__":
img = np.ones([2,2])
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.eye(3)
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.random.randint(5, size=(3, 3))
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
You should get:
input array:
[[1. 1.]
[1. 1.]]
label counts: {1.0: 4}
========
input array:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
label counts: {0.0: 6, 1.0: 3}
========
input array:
[[4 4 0]
[2 4 3]
[2 3 1]]
label counts: {0: 1, 1: 1, 2: 2, 3: 2, 4: 3}
========
Kotlin code
val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(requireActivity().currentFocus?.windowToken, 0)
Alex Robinson and bmju provided valuable information to understand cross-origin issues. I wanted to add that you may need to make an explicit OPTIONS call in your client code before making the desired GET/POST (e.g. against a CORS OAuth service endpoint). Your browser/library may not automatically handle the OPTIONS request. Gruber, this is one of the possible answers to your question.
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum
is already built in!
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
SELECT MIN(A.maxsal) secondhigh
FROM (
SELECT TOP 2 MAX(EmployeeBasic) maxsal
FROM M_Salary
GROUP BY EmployeeBasic
ORDER BY EmployeeBasic DESC
) A
If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph
smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()
where timeseries
is your set of data passed you can alter windowsize
for more smoothining.
Try out with mImageCaptureUri.getPath();
By Below Way :
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Get your Image Path
String Path=mImageCaptureUri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.
I ran into this trying to revive an accidentally deleted Docker Container (oraclelinux's MySQL) from a luckily-not-removed docker volume that had the DB data in physical files.
So, all I wanted to do was to turn the data from physical files into a .sql
importable file to recreate the container with the DB and the data.
I tried biolin's solution, but ran into some [InnoDB] Multiple files found for the same tablespace ID
errors, after restart. I realized that doing open hurt surgery on certain folders/files there is quite trickey.
The solution that worked for me was temporarily changing the datadir=
in my.cnf
to the available folder and restarting the MySQL server. It did the job perfectly!
You can copy an iterator to a new list like this:
Iterator<String> iter = list.iterator();
List<String> copy = new ArrayList<String>();
while (iter.hasNext())
copy.add(iter.next());
That's assuming that the list contains strings. There really isn't a faster way to recreate a list from an iterator, you're stuck with traversing it by hand and copying each element to a new list of the appropriate type.
EDIT :
Here's a generic method for copying an iterator to a new list in a type-safe way:
public static <T> List<T> copyIterator(Iterator<T> iter) {
List<T> copy = new ArrayList<T>();
while (iter.hasNext())
copy.add(iter.next());
return copy;
}
Use it like this:
List<String> list = Arrays.asList("1", "2", "3");
Iterator<String> iter = list.iterator();
List<String> copy = copyIterator(iter);
System.out.println(copy);
> [1, 2, 3]
Use either of these depending how you want backslashes in the shell variables handled (avar
is an awk variable, svar
is a shell variable):
awk -v avar="$svar" '... avar ...' file
awk 'BEGIN{avar=ARGV[1];ARGV[1]=""}... avar ...' "$svar" file
See http://cfajohnson.com/shell/cus-faq-2.html#Q24 for details and other options. The first method above is almost always your best option and has the most obvious semantics.
For anyone who is still having issues after trying all the answers on this page, the following (finally) worked:
sudo apt-get install libgmp3-dev
gem install pg
This was after doing everything else mentioned on this page.
postgresql 9.5.8
Ubuntu 16.10
In visual studio 2019, select your properties like this:
Then press Ctrl+r
Then press Ctrl+e
A dialog will appear showing you the preview of the changes that are going to be done to your code. If everything looks good (which it mostly will), press OK
.
A simple loop would suffice:
lines = []
with open('test.txt', 'r') as f:
for line in f.readlines():
l,name = line.strip().split(',')
lines.append((l,name))
print lines
And the ed
answer:
printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html
To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.
public class HelloWorld extends TimerTask{
public void run() {
System.out.println("Hello World");
}
}
public class PrintHelloWorld {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new HelloWorld(), 0, 5000);
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("InterruptedException Exception" + e.getMessage());
}
}
}
}
infinite loop is created ad scheduler task is configured.
For normal form you can do
class MyModelForm(forms.ModelForm):
slug = forms.CharField(widget=forms.HiddenInput())
If you have model form you can do the following
class MyModelForm(forms.ModelForm):
class Meta:
model = TagStatus
fields = ('slug', 'ext')
widgets = {'slug': forms.HiddenInput()}
You can also override __init__
method
class Myform(forms.Form):
def __init__(self, *args, **kwargs):
super(Myform, self).__init__(*args, **kwargs)
self.fields['slug'].widget = forms.HiddenInput()
html, body {
min-height: 100%;
}
Will do the trick.
By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.
You might also want to read http://css-tricks.com/perfect-full-page-background-image/
There are some great ways do achieve a very good and scalable full background image.
Python 3.x Update
From Eli Bendersky answer:
Python 3 removed dict.iteritems use dict.items instead. See Python wiki: https://wiki.python.org/moin/Python3.0
from collections import defaultdict
dd = defaultdict(list)
for d in (d1, d2):
for key, value in d.items():
dd[key].append(value)
I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.
index.html (or .php)
/resources
/css
/fonts
/images
/js
/controllers
/directives
/filters
/services
/partials (views)
I find that good for single apps. I haven't really had a project yet where I'd need multiple.
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
fieldNameElement.textContent = "New text";
I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.
after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.
Results of testing with the utility Split wrote (link is in his answer):
device: (crash amount/total amount/percentage of total)
Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)
C.f. Ethereal -> WireShark
Simply install adb with brew
brew cask install android-platform-tools
Check if adb is installed
adb devices
It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:
String str = "ABC";
if (str.Contains('A'))
{
//...
}
if (str.Contains("AB"))
{
//...
}
It's also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments
object into array in a way that makes the function optimizable under V8 JavaScript engine:
function doesntLeakArguments() {
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}
This method is used in favor of var args = [].slice.call(arguments);
. The author also shows how a build step can help reduce the verbosity.
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
I know this question was old, but I wanted a solution that doesn't involve libraries outside those included JRE6 (i.e. Apache Commons is not acceptable), and I came up with a simple solution using the built-in java.io.StreamTokenizer
:
import java.io.*;
// ...
String literal = "\"Has \\\"\\\\\\\t\\\" & isn\\\'t \\\r\\\n on 1 line.\"";
StreamTokenizer parser = new StreamTokenizer(new StringReader(literal));
String result;
try {
parser.nextToken();
if (parser.ttype == '"') {
result = parser.sval;
}
else {
result = "ERROR!";
}
}
catch (IOException e) {
result = e.toString();
}
System.out.println(result);
Output:
Has "\ " & isn't
on 1 line.
For Ubuntu, please install the below things:
sudo apt-get update && sudo apt-get install build-essential
#use return convertView;
Code:
public View getView(final int position, View convertView, ViewGroup parent) {
//convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) convertView.findViewById(R.id.name);
Button rm_btn = (Button) convertView.findViewById(R.id.rm_btn);
Model m = modelList.get(position);
tv.setText(m.getName());
// click listener for remove button ??????????
rm_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modelList.remove(position);
notifyDataSetChanged();
}
});
}
///#use return convertView;
return convertView;
}
Well, you want to split, right?
String animals = "dog, cat, bear, elephant, giraffe";
String[] animalsArray = animals.split(",");
If you want to additionally get rid of whitespaces around items:
String[] animalsArray = animals.split("\\s*,\\s*");
Octave is basically an open source version of MATLAB. It was written to be just that. MATLAB has a very nice GUI which makes it a bit easier to use but the next stable release of OCTAVE will also have a GUI, which I have tested in the unstable release, and looks fantastic. Octave is much more buggy because it was developed and maintained by a group of volunteers, where the development of MATLAB is funded by millions of dollars by industry. I'm still a student and am using a student version of MATLAB, but I am thinking of going over to Octave once the stable version with the GUI is released.
MATLAB is probably a lot more powerful than Octave, and the algorithms run faster, but for most applications, Octave is more than adequate and is, in my opinion' an amazing tool that is completely free, where Octave is completely free.
I would say use MATLAB while you can use the academic version, but the switch to Octave should be seamless as they use the exact same syntax.
Lastly, there is the issue of SIMULINK. If you want to do simulation or control system design (there are probably a million other uses) SIMULINK is fantastic and comes with MATLAB. I don't think any other comes close to this, although Scilab is apparently a 'good' open source alternative, I haven't tried it.
Peace.
Intent i = new Intent(this,Here is your first activity.Class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code.
Add headers in your application class like this :
class Application : Application() {
override fun onCreate() {
super.onCreate()
retrofitClient = RetrofitClient.instance
//api url
.setBaseUrl("https://reqres.in/")
//you can set multiple urls
// .setUrl("example","http://ngrok.io/api/")
//set timeouts
.setConnectionTimeout(4)
.setReadingTimeout(15)
//enable cache
.enableCaching(this)
//add Headers
.addHeader("Content-Type", "application/json")
.addHeader("client", "android")
.addHeader("language", Locale.getDefault().language)
.addHeader("os", android.os.Build.VERSION.RELEASE)
}
companion object {
lateinit var retrofitClient: RetrofitClient
}
}
And then make your call:
retrofitClient.Get<GetResponseModel>()
//set path
.setPath("api/users/2")
//set url params Key-Value or HashMap
.setUrlParams("KEY","Value")
// you can add header here
.addHeaders("key","value")
.setResponseHandler(GetResponseModel::class.java,
object : ResponseHandler<GetResponseModel>() {
override fun onSuccess(response: Response<GetResponseModel>) {
super.onSuccess(response)
//handle response
}
}).run(this)
For more information see the documentation
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
My favorite human friendly command for this is:
reset
Tested on xterm and VT100. It also helps after an abnormal program termination. Keeps the command buffer, so up-arrow will cycle through previous commands.
May also want to use "documentElement":
var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseEDIT: Kanbanize is a commercial product and offers a 30 day free trial.
Disclosing: I am a co-founder of http://kanbanize.com/
Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.
Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.
Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.
I hope that helps.
Use forward slashes. See explanation here
For Files - svn revert filename
For Folders - svn revert -R folder
find triggers on table:
select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%TableName%'
and you can find store procedure which has reference of table:
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%yourtablename%'
For those looking for a quick wget install on Mac, check out Quentin Stafford-Fraser's precompiled binary here, which has been around for over a decade:
https://statusq.org/archives/2008/07/30/1954/
MD5 for 2008 wget.zip: 24a35d499704eecedd09e0dd52175582
MD5 for 2005 wget.zip: c7b48ec3ff929d9bd28ddb87e1a76ffb
No make/install/port/brew/curl junk. Just download, install, and run. Works with Mac OS X 10.3-10.12+.
Allows getting any URL on your system, not just a current one.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
If running a linux server, make sure that your IPTABLES configuration is correct.
Execute sudo iptables -L -n
, you will recieve a listing of your open ports. If there is not an Iptables Rule to open the port serving the fcgi script you will receive a 502 error. The Iptables Rule which opens the correct port must be listed before any rule which categorically rejects all packets (i.e. a rule of the form "REJECT ALL -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
or similar)
On my configuration, to properly open the port, I had to execute this command (assume my fcgi server is running at port 4567):
sudo iptables -I INPUT 1 -p tcp --dport 4567 -j ACCEPT
WARNING: This will open port 4567 to the whole world.
So it might be better to do something like this:
sudo iptables-save >> backup.iptables
sudo iptables -D INPUT 1 #Delete the previously entered rule
sudo iptables -I INPUT 1 -p tcp --dport 8080 -s localhost -j ACCEPT # Add new rule
Doing this removed the 502 error for me.
Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.
As a beginner you should probably not attempt to solve such a non-trivial problem.
I had this exact same problem with Xampp portable on Windows 10 Home. I went through all the suggestions and none worked. I did get it working with Windows Firewall Settings and an error on my part.
My pen drive was labelled Drive E on my laptop and Drive F on my Desktop. Once I corrected that using disk partition and changed the drive letter to E for my desktop to windows asked for access for the firewall and everything clicked.
The steps to correct the drive letter were: 1. Hit the windows key and type Partition, "create and format harddisks partitions" should be at the top, hit enter 2. Find the drive you are looking for at the top panel and click on it. 3. Right click on it and select change drive letter and path, click okay 4. Now try to start xampp control panel and start Apache and Mysql 5. if you get the windows firewall click allow.
I can't say this will work but it did for me and is what I added to this discussion. I also think it might have been just the firewall did not allow the oither drive letter.
You probably have one .OBJ or .LIB file that's targeted for x64 (that's the module machine type) while you're linking for x86 (that's the target machine type).
Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.
In my case, with GitHub Desktop for Windows (as of June 2, 2016) & Android Studio 2.1:
This folder ->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\
Contained a BATCH file called something like 'post-install.bat'. Run this file to create a folder 'cmd' with 'git.exe' inside.
This path-->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\cmd\git.exe
would be the location of 'git.exe' after running the post-install script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
When I first saw %1$s
and %2$d
in the accepted answer, it made no sense. Here is a little more explanation.
They are called format specifiers. In the xml string they are in the form of
%[parameter_index$][format_type]
1$
, 2$
, and 3$
. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones:
s
stringd
decimal integerf
floating point numberWe will create the following formatted string where the gray parts are inserted programmatically.
My sister
Mary
is12
years old.
string.xml
<string name="my_xml_string">My sister %1$s is %2$d years old.</string>
MyActivity.java
String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);
getString
because I was in an Activity. You can use context.getResources().getString(...)
if it is not available.String.format()
will also format a String.1$
and 2$
terms don't need to be used in that order. That is, 2$
can come before 1$
. This is useful when internationalizing an app for languages that use a different word order.%1$s
multiple times in the xml if you want to repeat it.%%
to get the actual %
character.There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines()
, eg) for use.
An update to Adam's answer considering tryp's answer too. Don't have to instantiate a String in the loop.
public static URI appendUri(String uri, Map<String, String> parameters) throws URISyntaxException {
URI oldUri = new URI(uri);
StringBuilder queries = new StringBuilder();
for(Map.Entry<String, String> query: parameters.entrySet()) {
queries.append( "&" + query.getKey()+"="+query.getValue());
}
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = queries.substring(1);
} else {
newQuery += queries.toString();
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
Maybe it's funny, but this works for me:
string.Join("",List1) != string.Join("", List2)
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
This looks more to me like what you probably want.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());
function getReplacementString(str){
return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you.
This seems a little strange to only have 3 of the url characters so I would recommend this if possible.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());
function getReplacementString(str){
return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
which would rip out the http:// or https:// and print up to 10 charaters of www.example.com
After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.
To build the production code the first thing you have to create is production configuration with optimization packages like,
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
Then in the package.json file you can configure the build procedure with this production configuration
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
now you have to run the following command to initiate the build
npm run build
As per my production build configuration webpack will build the source to ./dist
directory.
Now your UI code will be available in ./dist/
directory. Configure your server to serve these files as static assets. Done!
Java 8 style, using the java.time classes:
// Monday, February 29 is a leap day in 2016 (otherwise, February only has 28 days)
LocalDate start = LocalDate.parse("2016-02-28"),
end = LocalDate.parse("2016-03-02");
// 4 days between (end is inclusive in this example)
Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1)
.forEach(System.out::println);
Output:
2016-02-28
2016-02-29
2016-03-01
2016-03-02
Alternative:
LocalDate next = start.minusDays(1);
while ((next = next.plusDays(1)).isBefore(end.plusDays(1))) {
System.out.println(next);
}
Java 9 added the datesUntil() method:
start.datesUntil(end.plusDays(1)).forEach(System.out::println);
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))
The compiler may well optimize the second form into the first form, but it doesn't have to.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Output from gcc 4.4:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
I hate to be the guy who says, "you're just doing it wrong" (I always hate that guy ;) but...
Does it have to be repeatably generated for the unique machine? Could you just assign the identifier or do a public/private key? Maybe if you could generate and store the value, you could access it from both OS installs on the same disk?
You've probably explored these options and they doesn't work for you, but if not, it's something to consider.
If it's not a matter of user trust, you could just use MAC addresses.
Instead of doing this:
$(document).ready(function() { });
You should be doing this:
jQuery(document).ready(function($) {
// your code goes here
});
This is because WordPress may use $ for something other than jQuery, in the future, or now, and so you need to load jQuery in a way that the $ can be used only in a jQuery document ready callback.
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message)
Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.
Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:
!ipython nbconvert <notebook name>.ipynb --to html
EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html
now.
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)
public static byte[] numToBytes(int num){
if(num == 0){
return new byte[]{};
}else if(num < 256){
return new byte[]{ (byte)(num) };
}else if(num < 65536){
return new byte[]{ (byte)(num >>> 8),(byte)num };
}else if(num < 16777216){
return new byte[]{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
}else{ // up to 2,147,483,647
return new byte[]{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
}
}
Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "@" symbol in a much more convenient way:
NSString *myString = @"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
This is because the path of image is wrong or the name of image you write is incorrect .
how to check? first try to print the image using print(img) if it prints 'None' that means you have given wrong image path correct that path and try again.
children
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = ({name}) => <div>Hello {name}</div>;
const WrappedApp = ({name}) => (
<Wrapper>
<App name={name}/>
</Wrapper>
);
render(<WrappedApp name="toto"/>,node);
This is also known as transclusion
in Angular.
children
is a special prop in React and will contain what is inside your component's tags (here <App name={name}/>
is inside Wrapper
, so it is the children
Note that you don't necessarily need to use children
, which is unique for a component, and you can use normal props too if you want, or mix props and children:
const AppLayout = ({header,footer,children}) => (
<div className="app">
<div className="header">{header}</div>
<div className="body">{children}</div>
<div className="footer">{footer}</div>
</div>
);
const appElement = (
<AppLayout
header={<div>header</div>}
footer={<div>footer</div>}
>
<div>body</div>
</AppLayout>
);
render(appElement,node);
This is simple and fine for many usecases, and I'd recommend this for most consumer apps.
It is possible to pass render functions to a component, this pattern is generally called render prop
, and the children
prop is often used to provide that callback.
This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.
Counter example:
const Counter = () => (
<State initial={0}>
{(val, set) => (
<div onClick={() => set(val + 1)}>
clicked {val} times
</div>
)}
</State>
);
You can get even more fancy and even provide an object
<Promise promise={somePromise}>
{{
loading: () => <div>...</div>,
success: (data) => <div>{data.something}</div>,
error: (e) => <div>{e.message}</div>,
}}
</Promise>
Note you don't necessarily need to use children
, it is a matter of taste/API.
<Promise
promise={somePromise}
renderLoading={() => <div>...</div>}
renderSuccess={(data) => <div>{data.something}</div>}
renderError={(e) => <div>{e.message}</div>}
/>
As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.
const wrapHOC = (WrappedComponent) => {
class Wrapper extends React.PureComponent {
render() {
return (
<div>
<div>header</div>
<div><WrappedComponent {...this.props}/></div>
<div>footer</div>
</div>
);
}
}
return Wrapper;
}
const App = ({name}) => <div>Hello {name}</div>;
const WrappedApp = wrapHOC(App);
render(<WrappedApp name="toto"/>,node);
An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.
Using an Higher-Order Component can be more performant than using children
or render props
, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate
.
Here we are using PureComponent
. When re-rendering the app, if the WrappedApp
name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children
based solution above, even if the wrapper is PureComponent
, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children
element over time.
Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.
Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.
Redux used at first a runtime wrapper <Connect>
and switched later to an HOC connect(options)(Comp)
for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate
). This is the perfect illustration of what I wanted to highlight in this answer.
Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query>
render-prop component, and the graphql
HOC using it.
Personally, I use both, but when in doubt I prefer HOCs because:
compose(hoc1,hoc2)(Comp)
) compared to render propsI don't hesitate to use/create HOC versions of my favorite tools:
Context.Consumer
compSubscribe
graphql
HOC of Apollo instead of Query
render propIn my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.
On Chrome and Firefox 32+, navigator.languages contains an array of locales in order of user preference, and is more accurate than navigator.language, however to make it backwards-compatible (Tested Chrome / IE / Firefox / Safari), then use this:
function getLang()
{
if (navigator.languages != undefined)
return navigator.languages[0];
else
return navigator.language;
}
These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)
a) Part on the developers' website:
Sign in into: https://developer.apple.com/
Member Center
Certificates, Identifiers & Profiles
Certificates>All
Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.
b) XCode part:
After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.
Every time the randint() method is called inside the for loop a different seed is set and a sequence is generated according to the time. But as for loop runs fast in your computer in a small time the seed is almost same and a very similar sequence is generated to the past one due to the time. So setting the seed outside the randint() method is enough.
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
var r = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
func main() {
fmt.Println(randomString(10))
}
func randomString(l int) string {
var result bytes.Buffer
var temp string
for i := 0; i < l; {
if string(randInt(65, 90)) != temp {
temp = string(randInt(65, 90))
result.WriteString(temp)
i++
}
}
return result.String()
}
func randInt(min int, max int) int {
return min + r.Intn(max-min)
}
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
Check the official jQuery FAQ page :
How do I test whether an element has perticular class or not
have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?
<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
<span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>
For both speed and memory purposes, when building a large data frame via some complex series of steps, I'll periodically flush it (the in-progress data set being built) to disk, appending to anything that came before, and then restart it. This way the intermediate steps are only working on smallish data frames (which is good as, e.g., rbind slows down considerably with larger objects). The entire data set can be read back in at the end of the process, when all the intermediate objects have been removed.
dfinal <- NULL
first <- TRUE
tempfile <- "dfinal_temp.csv"
for( i in bigloop ) {
if( !i %% 10000 ) {
print( i, "; flushing to disk..." )
write.table( dfinal, file=tempfile, append=!first, col.names=first )
first <- FALSE
dfinal <- NULL # nuke it
}
# ... complex operations here that add data to 'dfinal' data frame
}
print( "Loop done; flushing to disk and re-reading entire data set..." )
write.table( dfinal, file=tempfile, append=TRUE, col.names=FALSE )
dfinal <- read.table( tempfile )
A simple way is to set line-height
to the height of the element.