No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.
HTML5 spec
http://www.w3.org/TR/html5/forms.html#attr-input-checked :
The disabled content attribute is a boolean attribute.
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion
The following are valid, equivalent and true:
<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />
The following are invalid:
<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
The absence of the attribute is the only valid syntax for false:
<input type="checkbox" />
Recommendation
If you care about writing valid XHTML, use checked="checked"
, since <input checked>
is invalid and other alternatives are less readable. Else, just use <input checked>
as it is shorter.
Use set
if you don't care about items order or repetition. Use list comprehensions if you do:
>>> def diff(first, second):
second = set(second)
return [item for item in first if item not in second]
>>> diff(A, B)
[1, 3, 4]
>>> diff(B, A)
[5]
>>>
Type 1: If
statement style
{props.hasImage &&
<MyImage />
}
Type 2: If else
statement style
{props.hasImage ?
<MyImage /> :
<OtherElement/>
}
To adjust the size of one figure:
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(15, 15))
To change the default settings, and therefore all your plots:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [15, 15]
Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.
If you want lines instead of line ranges, you can do it with perl: eg. if you want to get line 1, 3 and 5 from a file, say /etc/passwd:
perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd
Use these tools for generating a C# class, and then use this code to serialize your object:
var json = new JavaScriptSerializer().Serialize(obj);
You can also use indexValue attribute for passing multiple parameters via object:
var someData = "hello";
jQuery.ajax({
url: "http://maps.google.com/maps/api/js?v=3",
indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
dataType: "script"
}).done(function() {
console.log(this.indexValue.param1);
console.log(this.indexValue.param2);
console.log(this.indexValue.param3);
});
Just to play with it, question is strong entity type and answer is weak. Question is always there, but an answer requires a question to exist.
Example: Don't ask 'Why?' if Your Dad's a Chemistry Professor
Content-type
You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.
More about that content-type here: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
Data
The data is correct as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.
You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.
JSON
It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.
Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.
So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:
$.ajax({
type: 'POST',
url: '/Services/GetPatient',
data: { 'patientID' : 1 },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading PatientID=' + id);
}
});
When you use find, you have two basic options: filter results out after find has completed searching or use some built in option that will prevent find from considering those files and dirs matching some given pattern.
If you use the former approach on a high number of files and dirs. You will be using a lot of CPU and RAM just to pass the result on to a second process which will in turn filter out results by using a lot of resources as well.
If you use the -not keyword which is a find argument, you will be preventing any path matching the string on the -name or -regex argument behind from being considered, which will be much more efficient.
find . -not -regex ".*/foo/.*" -regex ".*"
Then, any path that is not filtered out by -not will be captured by the subsequent -regex arguments.
Here's an answer to a 2-year old question in case it helps anyone else with the same problem.
Based upon the information you've provided, a permissions issue on the file (or files) would be one cause of the same 500 Internal Server Error.
To check whether this is the problem (if you can't get more detailed information on the error), navigate to the directory in Terminal and run the following command:
ls -la
If you see limited permissions - e.g. -rw-------@
against your file, then that's your problem.
The solution then is to run chmod 644
on the problem file(s) or chmod 755
on the directories. See this answer - How do I set chmod for a folder and all of its subfolders and files? - for a detailed explanation of how to change permissions.
By way of background, I had precisely the same problem as you did on some files that I had copied over from another Mac via Google Drive, which transfer had stripped most of the permissions from the files.
The screenshot below illustrates. The index.php file with the -rw-------@
permissions generates a 500 Internal Server Error, while the index_finstuff.php (precisely the same content!) with -rw-r--r--@
permissions is fine. Changing the permissions on the index.php immediately resolves the problem.
In other words, your PHP code and the server may both be fine. However, the limited read permissions on the file may be forbidding the server from displaying the content, causing the 500 Internal Server Error message to be displayed instead.
If you can use lodash, there is a function, which does exactly that:
_.get(object, path, [defaultValue])
var val = _.get(obj, "a.b");
you can use rjust string method of python syntax: string.rjust(length, fillchar) fillchar is optional
and for your Question you acn write like this
'0b'+ '1'.rjust(8,'0)
so it wil be '0b00000001'
echo '<p class="paragraph'.$i.'"></p>'
should do the trick.
The problem here is that a compliant implementation does not need to put your classes in a compile .cpp file. If the compiler can optimize out the existence of a class, so long as the program behaves the same way without it, then it can be omitted from the output executable.
C has a standardized binary interface. Therefore you'll be able to know that your functions are exported. But C++ has no such standard behind it.
Your code is working fine using bootatrap v3.3.7, but you can use
word-break: break-word
if it's not working at your end.
which would then look like this -
<html>_x000D_
_x000D_
<head>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="row" style="box-shadow: 0 0 30px black;">_x000D_
<div class="col-6 col-sm-6 col-lg-4">_x000D_
<h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
$6900</h3>_x000D_
<p>_x000D_
<small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
excellent ,comes with warranty if you're ...</small>_x000D_
</p>_x000D_
<p>_x000D_
<a class="btn btn-default" href="/search/1355/detail/" role="button">View details »</a>_x000D_
<button type="button" class="btn bookmark" id="1355">_x000D_
<span class="_x000D_
glyphicon glyphicon-star-empty "></span>_x000D_
</button>_x000D_
</p>_x000D_
</div>_x000D_
<!--/span-->_x000D_
<div class="col-6 col-sm-6 col-lg-4">_x000D_
<h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
<p>_x000D_
<small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
great, cd player, 4 cylinder engen, ...</small>_x000D_
</p>_x000D_
<p>_x000D_
<a class="btn btn-default" href="/search/1356/detail/" role="button">View details »</a>_x000D_
<button type="button" class="btn bookmark" id="1356">_x000D_
<span class="_x000D_
glyphicon glyphicon-star-empty "></span>_x000D_
</button>_x000D_
</p>_x000D_
_x000D_
</div>_x000D_
<!--/span-->_x000D_
<div class="col-6 col-sm-6 col-lg-4">_x000D_
<h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
<p>_x000D_
<small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
nice,has_x000D_
cd player, power windows ...</small>_x000D_
</p>_x000D_
<p>_x000D_
<a class="btn btn-default" href="/search/1357/detail/" role="button">View details »</a>_x000D_
<button type="button" class="btn bookmark" id="1357">_x000D_
<span class="_x000D_
glyphicon glyphicon-star-empty "></span>_x000D_
</button>_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
First create your own error page in HTML and put it in your assets folder, Let's call it myerrorpage.html Then with onReceivedError:
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
});
Yes, you can safely pass an array as a parameter.
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
If your rotation angles are fairly uniform, you can use CSS:
<img id="image_canv" src="/image.png" class="rotate90">
CSS:
.rotate90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:
<img id="image_canv" src="/image.png" data-rotate="90">
Sample jQuery:
$('img').each(function() {
var deg = $(this).data('rotate') || 0;
var rotate = 'rotate(' + deg + 'deg)';
$(this).css({
'-webkit-transform': rotate,
'-moz-transform': rotate,
'-o-transform': rotate,
'-ms-transform': rotate,
'transform': rotate
});
});
Demo:
Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.
Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span>
for instance:
<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>
Then:
$('.replaceme').html('Whatever <b>HTML</b> you want here.');
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
Export like export default HelloWorld;
and import, such as import React from 'react'
are part of the ES6 modules system.
A module is a self contained unit that can expose assets to other modules using export
, and acquire assets from other modules using import
.
In your code:
import React from 'react'; // get the React object from the react module
class HelloWorld extends React.Component {
render() {
return <p>Hello, world!</p>;
}
}
export default HelloWorld; // expose the HelloWorld component to other modules
In ES6 there are two kinds of exports:
Named exports - for example export function func() {}
is a named export with the name of func
. Named modules can be imported using import { exportName } from 'module';.
In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';
. There can be multiple named exports in one module.
Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'
. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.
A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';
.
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $
represents the jQuery Function, and is actually a shorthand alias for jQuery
. (Unlike in most languages, the $
symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
Simple way like this (one line)
$('#startDateText').val(startDate).datepicker("update");
If you also want to preserve the original file name, try with:
wget --content-disposition --trust-server-names -i list_of_urls.txt
Have a look at JavaScript substring()
method.
You could use assign
, but using assign
(or get
) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.
with a list:
A <- lapply (1 : 10, function (x) d + rnorm (3))
with a matrix:
A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
If you already have pods which are recreated, think to delete all deployments first
kubectl delete -n *NAMESPACE deployment *DEPLOYMENT
Just replace the NAMSPACE and the DEPLOYMENT to corresponding ones, you can get all deployments information by the following command
kubectl get deployments --all-namespaces
When you type x = 0
that is creating a new int
variable (name) and assigning a zero to it.
When you type x[age1]
that is trying to access the age1
'th entry, as if x
were an array.
Found it here: http://awesomesql.wordpress.com/2010/02/08/script-to-drop-all-connections-to-a-database/
DECLARE @dbname NVARCHAR(128)
SET @dbname = 'DB name here'
-- db to drop connections
DECLARE @processid INT
SELECT @processid = MIN(spid)
FROM master.dbo.sysprocesses
WHERE dbid = DB_ID(@dbname)
WHILE @processid IS NOT NULL
BEGIN
EXEC ('KILL ' + @processid)
SELECT @processid = MIN(spid)
FROM master.dbo.sysprocesses
WHERE dbid = DB_ID(@dbname)
END
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.
// this function just get the public url of zip file.
let url = await getStorageUrl(path)
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
console.log('zip download status ', res.status)
//load contents into jszip and create an object
jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
const zipObj = zip
$.each(zip.files, function (index, zipEntry) {
console.log('filename', zipEntry.name)
})
})
Now using the zipObj you can access the files and create a src url for it.
var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)
I was looking for the same issue, and imho the pretty solution is :
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
and using that to parse the string to boolean as suggested above.
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
A bit late to answer the question. But,
If it's a MySQL database
should $doctrine_record_object->id
work if AUTO_INCREMENT
is defined in database and in your table definition.
It got simplified with newer version of rxjs .
import {map} from 'rxjs/operators';
import {Observable,of, from } from 'rxjs';
Instead of chaining we need to pipe . For example
Old syntax :
source.map().switchMap().subscribe()
New Syntax:
source.pipe(map(), switchMap()).subscribe()
Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:
do
-> tap
,
catch
-> catchError
switch
-> switchAll
finally
-> finalize
I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.
import { Rx } from 'rxjs/Rx'
;This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.
public cache = new Rx.BehaviorSubject('');
Or you can import individual operators .
This will Optimize your app to use only those files :
import { _______ } from 'rxjs/_________';
This syntax usually used for main Object like Rx
itself or Observable
etc.,
Keywords which can be imported with this syntax
Observable, Observer, BehaviorSubject, Subject, ReplaySubject
import 'rxjs/add/observable/__________';
Update for Angular 5
With Angular 5, which uses rxjs 5.5.2+
import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';
These are usually accompanied with Observable directly. For example
Observable.from()
Observable.of()
Other such keywords which can be imported using this syntax:
concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of,
range, throw, timer, using, zip
import 'rxjs/add/operator/_________';
Update for Angular 5
With Angular 5, which uses rxjs 5.5.2+
import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';
These usually come in the stream after the Observable is created. Like flatMap
in this code snippet:
Observable.of([1,2,3,4])
.flatMap(arr => Observable.from(arr));
Other such keywords using this syntax:
audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay,
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck,
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take,
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip
FlatMap:
flatMap
is alias to mergeMap
so we need to import mergeMap
to use flatMap
.
Note for /add
imports :
We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.
To force redirect on https protocol, you can also add this directive in .htaccess on root folder
RewriteEngine on
RewriteCond %{REQUEST_SCHEME} =http
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
Just using max-width: 0
in the display: table-cell
element worked for me:
.table {_x000D_
display: table;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.table-cell {_x000D_
display: table-cell;_x000D_
max-width: 0px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-cell">short</div>_x000D_
<div class="table-cell">loooooong</div>_x000D_
<div class="table-cell">Veeeeeeery loooooong</div>_x000D_
</div>
_x000D_
I've had good luck with the SWF::File library on CPAN, and particularly the dumpswf.plx tool that comes with that distribution. It generates Perl code that, when run, regenerates your SWF.
Personally I would avoid iframes and go with an embed tag to create the view in the mouseover box.
<embed src="http://www.btf-internet.com" width="600" height="400" />
I wanted to try/catch a warning, but at the same time keep the usual warning/error logging (e.g. in /var/log/apache2/error.log
); for which the handler has to return false
. However, since the "throw new..." statement basically interrupts the execution, one then has to do the "wrap in function" trick, also discussed in:
Is there a static way to throw exception in php
Or, in brief:
function throwErrorException($errstr = null,$code = null, $errno = null, $errfile = null, $errline = null) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
return false && throwErrorException($errstr, 0, $errno, $errfile, $errline);
# error_log("AAA"); # will never run after throw
/* Do execute PHP internal error handler */
# return false; # will never run after throw
}
...
set_error_handler('warning_handler', E_WARNING);
...
try {
mkdir($path, 0777, true);
} catch (Exception $e) {
echo $e->getMessage();
// ...
}
EDIT: after closer inspection, it turns out it doesn't work: the "return false && throwErrorException ...
" will, basically, not throw the exception, and just log in the error log; removing the "false &&
" part, as in "return throwErrorException ...
", will make the exception throwing work, but will then not log in the error_log... I'd still keep this posted, though, as I haven't seen this behavior documented elsewhere.
I was able to achieve the effect with the following code
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:left="0dp" android:right="-5dp" android:top="-5dp" android:bottom="-5dp">
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#123456" />
</shape>
</item>
</layer-list>
You can adjust to your needs for border position by changing the direction of displacement
Have you tried this:
Taken from the site:
pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled
I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:
1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:
...
Dim oFile As Object ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False
2) I went back and looked for all of the .range in the code and made sure it was the full construct..
Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value
or (not 100% sure if this is correct syntax, but this is the 'effort' i made)
ActiveSheet.Range("A1").Select
The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
if(x)
println "x value: ${x}"
For python 3, just write below codes to ignore all warnings.
from warnings import filterwarnings
filterwarnings("ignore")
Define the Entity
class in Hibernate.cfg.xml
<mapping class="com.supernt.Department"/>
While creating the sessionFactory
object Load the Configuration file Like
SessionFactory factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
Just happened to me when trying to send_keys to a search input box - that has autoupdate depending on what you type in. As mentioned by Eero, this can happen if your element does some Ajax updated while you are typing in your text inside the input element. The solution is to send one character at a time and search again for the input element. (Ex. in ruby shown below)
def send_keys_eachchar(webdriver, elem_locator, text_to_send)
text_to_send.each_char do |char|
input_elem = webdriver.find_element(elem_locator)
input_elem.send_keys(char)
end
end
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt
Now, Next add this downloaded files into your project:
Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93
You're thinking it wrong.
What you are trying to do:
If stdin exists use it, else check whether the user supplied a filename.
What you should be doing instead:
If the user supplies a filename, then use the filename. Else use stdin.
You cannot know the total length of an incoming stream unless you read it all and keep it buffered. You just cannot seek backwards into pipes. This is a limitation of how pipes work. Pipes are not suitable for all tasks and sometimes intermediate files are required.
this gives you the Xact;
System.Data.SqlClient.SqlConnectionStringBuilder connBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
connBuilder.ConnectionString = connectionString;
string server = connBuilder.DataSource; //-> this gives you the Server name.
string database = connBuilder.InitialCatalog; //-> this gives you the Db name.
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
canvas.toDataURL()
will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>
, whereas the blue-bordered image is a copy in a <img>
, filled with the <canvas>
's data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
_x000D_
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
_x000D_
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
_x000D_
See also:
They will be initialized to false
by default. In Java arrays are created on heap and every element of the array is given a default value depending on its type. For boolean
data type the default value is false
.
Works great, minimal setup and no third parties.
According to Chrome's documentation:
Here's the updated workflow:What happens when you blackbox a script?
Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.
jquery\..*\.js
(glob pattern/human translation: jquery.*.js
)|
, like so: jquery\..*\.js|include\.postload\.js
(which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/
You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:
It's an excellent tool to have:
Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:
- Which elements have events attached to them
- The type of events attached to an element
- The code that will be run with the event is triggered
- The source file and line number for where the attached function was defined (Webkit browsers and Opera only)
You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.
In this instance, I want to know what exactly goes on when I click the button.
Open Dev Tools -> Sources tab, and on the right find Event
Listener Breakpoints
:
Expand Mouse
and select click
With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:
and searching #envio
or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.
Be aware sometimes there's not only an img
but lots of elements stacked, and you may not know which one triggers the code.
If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
If the radiobutton-checked event occurs before the content of the window is loaded fully, i.e. the ellipse is loaded fully, such an exception will be thrown. So check if the UI of the window is loaded (probably by Window_ContentRendered event, etc.).
Open Modules Tab (Press Ctrl+Shift+Alt+S). I had two modules under one project. I've solved the problem after removing the second redundant module (see screenshot).
Spinner
<Spinner
android:id="@+id/To_Units"
style="@style/spinner_style" />
style.xml
<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">10dp</item>
<item name="android:paddingLeft">8dp</item>
<item name="android:paddingRight">20dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
<item name="android:popupBackground">#DFFFFFFF</item>
</style>
gradient_spinner.xml (in drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><layer-list>
<item><shape>
<gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />
<stroke android:width="1dp" android:color="#000000" />
<corners android:radius="4dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape></item>
<item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
</item>
</layer-list></item>
</selector>
@drawable/spinner_arrow
is your bottom right corner image
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.
In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.
http://www.prasannatech.net/2009/07/introduction-python-generators.html
Yes, you can use the shorthand syntax for if
statements.
rate = lambda(t): (200 * exp(-t)) if t > 200 else (400 * exp(-t))
Note that you don't use explicit return
statements inlambda
s either.
In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.
I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.
Here you go:
USE information_schema;
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'X'
AND REFERENCED_COLUMN_NAME = 'X_id';
If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'X'
AND REFERENCED_COLUMN_NAME = 'X_id'
AND TABLE_SCHEMA = 'your_database_name';
You have to open and close your class with { ... }
like:
public class mod_MyMod extends BaseMod
{
public String Version()
{
return "1.2_02";
}
public void AddRecipes(CraftingManager recipes)
{
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt });
}
}
You need not specify receiver. You can use adb instead.
adb shell am broadcast -a com.whereismywifeserver.intent.TEST
--es sms_body "test from adb"
For more arguments such as integer extras, see the documentation.
The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.
Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:
https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en
Or you can get it for free, the author has posted a free version on xda-developers:
http://forum.xda-developers.com/showthread.php?t=1687590
Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure
on the device, and finally kill the adb server on your computer:
% adb kill-server
And then restart the server and it should already be root.
Inspired by Solomon's answer, but to stick with the question, which is related to histogram, a clean solution is:
sns.distplot(bar)
sns.distplot(foo)
plt.show()
Make sure to plot the taller one first, otherwise you would need to set plt.ylim(0,0.45) so that the taller histogram is not chopped off.
ATTENTION! ATTENTION! Imperfect answer ahead. To get the "latest memo" on the state of packaging in the Python universe, read this fairly detailed essay.
I have just ran into this problem when trying to build/install ansible. The problem seems to be that distutils really doesn't support install_requires. Setuptools should monkey-patch distutils on-the-fly, but it doesn't, probably because the last release of setuptools is 0.6c11 from 2009, whereas distutils is a core Python project.
So even after manually installing the setuptools-0.6c11-py2.7.egg running setup.py only picks up distutils dist.py, and not the one from site-packages/setuptools/.
Also the setuptools documentation hints to using ez_setup and not distutils.
However, setuptools is itself provided by distribute nowadays, and that flavor of setup() supports install_requires.
You cloud also simply override the width of the Column...
<div class="col-md-1" style="width: 12.499999995%"></div>
Since col-md-1
is of width 8.33333333%; simply multiply 8.33333333 * 1.5 and set it as your width.
in bootstrap 4
, you will have to override flex and max-width property too:
<div class="col-md-1" style="width: 12.499999995%;
flex: 0 0 12.499%;max-width: 12.499%;"></div>
Use:
if (-f $filePath)
{
# code
}
-e
returns true even if the file is a directory. -f
will only return true if it's an actual file
Normally, you do this with generics, for example:
MapEntToObj<T>(IQueryable<T> query) {...}
The compiler should then infer the T
when you call MapEntToObj(query)
. Not quite sure what you want to do inside the method, so I can't tell whether this is useful... the problem is that inside MapEntToObj
you still can't name the T
- you can either:
T
T
to do thingsbut other than that, it is quite hard to manipulate anonymous types - not least because they are immutable ;-p
Another trick (when extracting data) is to also pass a selector - i.e. something like:
Foo<TSource, TValue>(IEnumerable<TSource> source,
Func<TSource,string> name) {
foreach(TSource item in source) Console.WriteLine(name(item));
}
...
Foo(query, x=>x.Title);
All the metadata about the columns in Oracle Database is accessible using one of the following views.
user_tab_cols; -- For all tables owned by the user
all_tab_cols ; -- For all tables accessible to the user
dba_tab_cols; -- For all tables in the Database.
So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..
DECLARE
v_column_exists number := 0;
BEGIN
Select count(*) into v_column_exists
from user_tab_cols
where upper(column_name) = 'ADD_TMS'
and upper(table_name) = 'EMP';
--and owner = 'SCOTT --*might be required if you are using all/dba views
if (v_column_exists = 0) then
execute immediate 'alter table emp add (ADD_TMS date)';
end if;
end;
/
If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..
If you have file1.sql
alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;
And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.
We can use arrayUnion({})
method to achive this.
Try this:
collectionRef.doc(ID).update({
sharedWith: admin.firestore.FieldValue.arrayUnion({
who: "[email protected]",
when: new Date()
})
});
Documentation can find here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
You can use List<T>.RemoveAt
method:
rows.RemoveAt(rows.Count -1);
Passing data to view is simple as passing object to method. Take a look at Controller.View Method
protected internal ViewResult View(
Object model
)
Something like this
//controller
List<MyObject> list = new List<MyObject>();
return View(list);
//view
@model List<MyObject>
// and property Model is type of List<MyObject>
@foreach(var item in Model)
{
<span>@item.Name</span>
}
There are 3 main possibilities to execute a function:
var callback = function(x, y) {
// "this" may be different depending how you call the function
alert(this);
};
The method you choose depends whether:
Docs for Function.call, Function.apply
You could also use the __getitem__
method combined with map
like the following:
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
The best way to do it without any headache is to use the
\tablefootnote
command from the tablefootnote
package. Add the following to your preamble:
\usepackage{tablefootnote}
It just works without the need of additional tricks.
If you use Virtual Box you can connect Mac OSX (and I think Linux) to your virtual windows machine using one line of code --> I suggest stopping the box before running this in terminal.
VBoxManage modifyvm "YOUR VM NAME" --natdnshostresolver1 on
I will note that this is from the Dinghy docs, which I am running, but its a virtual box command so it shouldn't actually care what you use as long as its Virtual Box
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
I figured out the Xcode Command Line Tools part from the error message, but after running Xcode and getting the prompt to install the additional tools it did claim to install them, but still I got the same error after opening a new terminal.
So I did the xcode-select --install
manually and after that it worked for me.
The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.
Well IMEX=1 did not work for me. Neither did Reynier Booysen's suggestion. (I don't know if it makes a difference but I'm using SQL Server 2008r2). A good explanation of some workarounds and also some explanations of why IMEX=1 is limited to the first eight rows of each spreadsheet can be found at http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/78b87712-8ffe-4c72-914b-f1c031ba6c75
Hope this helps
Look in the documentation for sprintf for your platform. Its usually %f or %e. The only place you will find a definite answer is the documentation... if its undocumented all you can do then is contact the supplier.
What platform is it? Someone might already know where the docs are... :)
Using double
to store large integers is dubious; the largest integer that can be stored reliably in double
is much smaller than DBL_MAX
. You should use long long
, and if that's not enough, you need your own arbitrary-precision code or an existing library.
Using the time.h library, try something like this:
long start_time, end_time, elapsed;
start_time = clock();
// Do something
end_time = clock();
elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;
In my case, it was that the app had defaulted to a Wearable target device.
I removed the reference to Wearable in my Manifest, and the problem was solved.
<uses-library android:name="com.google.android.wearable" android:required="true" />
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
Im putting this in an answer because it's too long for a comment:
If you need the VM to be aware when the CheckBox
is changed, you should really bind the CheckBox
to the VM, and not a static value:
public class ViewModel
{
private bool _caseSensitive;
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
_caseSensitive = value;
NotifyPropertyChange(() => CaseSensitive);
Settings.Default.bSearchCaseSensitive = value;
}
}
}
XAML:
<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>
_id
field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id
it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.
Additional info: http://www.mongodb.org/display/DOCS/BSON
Hope it helps.
Android OnItemClickLIstener conflicts with the OnClickListener of items of row of listview in Adapter. You just have to make sure your code is well managed and properly written with standards.
Check the answer in the link given below:
To solve this for several columns of a dataframe:
In [5]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6],'c'
...: :[3,3,3,4,4,4]})
In [6]: df
Out[6]:
a b c
0 A 1 3
1 A 2 3
2 B 5 3
3 B 5 4
4 B 4 4
5 C 6 4
In [7]: df.groupby('a').agg(lambda x: list(x))
Out[7]:
b c
a
A [1, 2] [3, 3]
B [5, 5, 4] [3, 4, 4]
C [6] [4]
This answer was inspired from Anamika Modi's answer. Thank you!
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
For a specific column, there is an alternative with sapply
DF <- data.frame(A = letters[1:5],
B = letters[6:10],
C = c(2, 5, NA, 8, NA))
DF_NEW <- sapply(seq(1, nrow(DF)),
function(i) ifelse(is.na(DF[i,3]) ==
TRUE,
0,
DF[i,3]))
DF[,3] <- DF_NEW
DF
Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.
More info here:
I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.
The term "bootstrapping" usually applies to a situation where a system depends on itself to start, sort of a chicken and egg problem.
For instance:
In that case, bootstrapping refers to a way of breaking the circular dependency, usually with the help of an external entity, e.g.
etc.
Learn about isset
which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.
// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
$http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}
Then from the interceptor in the request method before return the config object
// if header['Content-type'] is a POST then add data
'request': function (config) {
if (
angular.isDefined(config.headers['Content-Type'])
&& !angular.isDefined(config.data)
) {
config.data = '';
}
return config;
}
Another potential "solution" is to use the window
object. It avoids the reference error problem when in a browser.
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}
In the step 5 of Phil, "Resources" is no longer available in the new version of the Chrome. You need to click the page icon just beside the Ajax page listed in the bottom pane with the columns of Name, Method, Status, ...
Then it will show you more panels where you will find the error messages.
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
The best way to decide questions like this to benchmark them:
use strict;
use warnings;
use Benchmark qw(:all);
our @input_array = (0..1000);
my $a = sub {
my @array = @{[ @input_array ]};
my $index = 0;
foreach my $element (@array) {
die unless $index == $element;
$index++;
}
};
my $b = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (defined(my $element = shift @array)) {
die unless $index == $element;
$index++;
}
};
my $c = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (scalar(@array) !=0) {
my $element = shift(@array);
die unless $index == $element;
$index++;
}
};
my $d = sub {
my @array = @{[ @input_array ]};
foreach my $index (0.. $#array) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $e = sub {
my @array = @{[ @input_array ]};
for (my $index = 0; $index <= $#array; $index++) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $f = sub {
my @array = @{[ @input_array ]};
while (my ($index, $element) = each @array) {
die unless $index == $element;
}
};
my $count;
timethese($count, {
'1' => $a,
'2' => $b,
'3' => $c,
'4' => $d,
'5' => $e,
'6' => $f,
});
And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi
I get:
Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
1: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 12560.13/s (n=39690)
2: 3 wallclock secs ( 3.18 usr + 0.00 sys = 3.18 CPU) @ 7828.30/s (n=24894)
3: 3 wallclock secs ( 3.23 usr + 0.00 sys = 3.23 CPU) @ 6763.47/s (n=21846)
4: 4 wallclock secs ( 3.15 usr + 0.00 sys = 3.15 CPU) @ 9596.83/s (n=30230)
5: 4 wallclock secs ( 3.20 usr + 0.00 sys = 3.20 CPU) @ 6826.88/s (n=21846)
6: 3 wallclock secs ( 3.12 usr + 0.00 sys = 3.12 CPU) @ 5653.53/s (n=17639)
So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.
@ikegami also points out that there are quite a few differences in these implimentations other than speed.
try {
File img = new File("somefile.png");
BufferedImage image = ImageIO.read(img );
System.out.println(image);
} catch (IOException e) {
e.printStackTrace();
}
Example output for my image file:
BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24
numComponents = 3 color
space = java.awt.color.ICC_ColorSpace@50a649
transparency = 1
has alpha = false
isAlphaPre = false
ByteInterleavedRaster:
width = 800
height = 600
#numDataElements 3
dataOff[0] = 2
You can run System.out.println(object); on just about any object and get some information about it.
I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.
If outputting to a webpage in HTML, particularly text in <textarea>
, <pre>
or <code>
you probably always want to use \n
and not PHP_EOL
.
The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).
I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r
's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.
As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.
I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.
If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"
<DataGrid IsReadOnly="True" CanUserAddRows="False" />
Further more you can set IsReadOnly on individual columns to disable editing.
Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
/* Scrollable Content Height */
.scrollContent {
height:100px;
overflow-x:hidden;
overflow-y:auto;
}
.scrollContent tr {
height: auto;
white-space: nowrap;
}
/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
padding-right: 20px;
}
/* Fixed Header Height */
.fixedHeader tr {
position: relative;
height: auto;
}
/* Put border around entire table */
div.TableContainer {
border: 1px solid #7DA87D;
}
/* Table Header formatting */
.headerFormat {
background-color: white;
color: #FFFFFF;
margin: 3px;
padding: 1px;
white-space: nowrap;
font-family: Helvetica;
font-size: 16px;
text-decoration: none;
font-weight: bold;
}
.headerFormat tr td {
border: 1px solid #000000;
background-color: #7DA87D;
}
/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
color: #000000;
margin: 3px;
padding: 1px;
border: 0px none;
font-family: Helvetica;
font-size: 12px;
}
/* Use to set different color for alternating rows */
.alternateRow {
background-color: #E0F1E0;
}
/* Styles used for SORTING */
.point {
cursor:pointer;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
.total {
background-color: #FED362;
color: #000000;
white-space: nowrap;
font-size: 12px;
text-decoration: none;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */
/* ======================================================
Generic Table Sort
Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.
Assumptions:
* The first row of the table contains column titles that are "clicked"
to sort the table
* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist
* The img tag is in each column of the the title row to represent the
sort graphic.
* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
have alternating colors for each row and a highlight the sorted
column. Something like the <style> definition below, but with the
background colors set to whatever you want.
<style>
tr.alternateRow {
background-color: #E0F1E0;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
</style>
====================================================== */
function sortTable(td_element,ignoreLastLines) {
// If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
// was not passed then make it 0
ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;
var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];
// Get the image used in the first row of the current column
var sortColImage = td_element.getElementsByTagName('img')[0];
// If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
// be a descending sort else it will be ascending - get new sort image icon and set sort order flag
var sortAscending = false;
var newSortColImage = "";
if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
newSortColImage = sortImages[0];
sortAscending = false;
} else {
newSortColImage = sortImages[1];
sortAscending = true;
}
// Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
// (will replace with newSortColImage when sort completes)
sortColImage.setAttribute('src',sortImages[3]);
// Find which column was clicked by getting it's column position
var indexCol = td_element.cellIndex;
// Get the table element from the td element that was passed as a parameter to this function
var table_element = td_element.parentNode;
while (table_element.nodeName != "TABLE") {
table_element = table_element.parentNode;
}
// Get all "tr" elements from the table and assign then to the Array "tr_elements"
var tr_elements = table_element.getElementsByTagName('tr');
// Get all the images used in the first row then set them to 'none.gif'
// (element 2 or sortImages array) except for the current column (all ready been changed)
var allImg = tr_elements[0].getElementsByTagName('img');
for(var i=0;i<allImg.length;i++){
if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
}
// Some explantion of the basic concept of the following code before we
// actually start. Essentially we are going to copy the current columns information
// into an array to be sorted. We'll sort the column array then go back and use the information
// we saved about the original row positions to re-order the entire table.
// We are never really sorting more than a columns worth of data, which should keep the sorting fast.
// Create a new array for holding row information
var clonedRows = new Array()
// Create a new array to store just the selected column values, not the whole row
var originalCol = new Array();
// Now loop through all the data row elements
// NOTE: Starting at row 1 because row 0 contains the column titles
for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {
// "Clone" the tr element i.e. save a copy all of its attributes and values
clonedRows[i]=tr_elements[i].cloneNode(true);
// Text value of the selected column on this row
var valueCol = getTextValue(tr_elements[i].cells[indexCol]);
// Format text value for sorting depending on its type, ie Date, Currency, number, etc..
valueCol = FormatForType(valueCol);
// Assign the column value AND the row number it was originally on in the table
originalCol[i]=[valueCol,tr_elements[i].rowIndex];
}
// Get rid of element "0" from this array. A value was never assigned to it because the first row
// in the table just contained the column titles, which we did not bother to assign.
originalCol.shift();
// Sort the column array returning the value of a sort into a new array
sortCol = originalCol.sort(sortCompare);
// If it was supposed to be an Ascending sort then reverse the order
if (sortAscending) { sortCol.reverse(); }
// Now take the values from the sorted column array and use that information to re-arrange
// the order of the tr_elements in the table
for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {
var old_row = sortCol[i-1][1];
var new_row = i;
tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
}
// Format the table, making the rows alternating colors and highlight the sorted column
makePretty(table_element,indexCol,ignoreLastLines);
// Assign correct sort image icon to current column title
sortColImage.setAttribute('src',newSortColImage);
}
// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
// Since the elements of this array are actually arrays themselves, just sort
// on the first element which contiains the value, not the second which contains
// the original row position
if ( currValue[0] == nextValue[0] ) return 0;
if ( currValue[0] < nextValue[0] ) return -1;
if ( currValue[0] > nextValue[0] ) return 1;
}
//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------
// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
document.ELEMENT_NODE = 1;
document.TEXT_NODE = 3;
}
function getTextValue(el) {
var i;
var s;
// Find and concatenate the values of all text nodes contained within the
// element.
s = "";
for (i = 0; i < el.childNodes.length; i++)
if (el.childNodes[i].nodeType == document.TEXT_NODE)
s += el.childNodes[i].nodeValue;
else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
el.childNodes[i].tagName == "BR")
s += " ";
else
// Use recursion to get text within sub-elements.
s += getTextValue(el.childNodes[i]);
return normalizeString(s);
}
// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
s = s.replace(whtSpMult, " "); // Collapse any multiple whites space.
s = s.replace(whtSpEnds, ""); // Remove leading or trailing white space.
return s;
}
// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
var sortValue = itm.toLowerCase();
// If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {
// Convert date to YYYYMMDD format for sort comparison purposes
// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
var yr = -1;
if (itm.length == 10) {
sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
} else if (itm.length == 9) {
sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
} else {
yr = itm.substr(6,2);
if (parseInt(yr) < 50) {
yr = '20'+yr;
} else {
yr = '19'+yr;
}
sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
}
}
// If the item matches a Percent patten (contains a percent sign)
if (itm.match(/%/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
sortValue = parseFloat(sortValue);
}
// If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
itm = "-" + itm.substr(1,itm.length - 2);
}
// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
if (itm.match(/^[£$]|(^-)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
// If the item matches a numeric pattern
if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
// sortValue = sortValue.replace(/,/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
return sortValue;
}
//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------
// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";
// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");
function makePretty(tblEl, col, ignoreLastLines) {
var i, j;
var rowEl, cellEl;
// Set style classes on each row to alternate their appearance.
for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className.replace(rowTest, "");
if (i % 2 != 0)
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 0; j < tblEl.rows[i].cells.length; j++) {
cellEl = rowEl.cells[j];
cellEl.className = cellEl.className.replace(colTest, "");
if (j == col)
cellEl.className += " " + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}
}
// END Generic Table sort.
// =================================================
// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
document.getElementById('TableContainer').scrollTop = 0;
}
//]]>
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
<thead class="fixedHeader headerFormat">
<tr>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
</tr>
</thead>
<tbody class="scrollContent bodyFormat" style="height:200px;">
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">99%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">23423%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">32%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">1%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">99%</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100%</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">59%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">534.23%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">42%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">2%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">(-10.42%)</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">-$19,923.19</td>
<td align="right">100</td>
<td align="right">(-10.01%)</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">-10.20%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="total">
<td><strong>TOTAL</strong>:</td>
<td align="right"><strong>999999</strong></td>
<td align="right"><strong>9999999</strong></td>
<td align="right"><strong>99</strong></td>
<td > </td>
<td align="right"> </td>
</tr>
</tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>
I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).
This is another technique. It uses a Grid with a SharedSizeGroup.
Note: the Grid.IsSharedScope=true on the ListView.
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="40">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
Only 1 emulator or device may be open at a time. Make sure you don't have multiple emulators running.
For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library.
The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages
directory).
Make sure to read: http://docs.python.org/using/cmdline.html#environment-variables
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.
Or this really short version, returns true if the browsers is Internet Explorer:
function isIe() {
return window.navigator.userAgent.indexOf("MSIE ") > 0
|| !!navigator.userAgent.match(/Trident.*rv\:11\./);
}
The problems with calling Thread.Sleep
are explained quite succinctly here:
Thread.Sleep
has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.
Thread.Sleep(n)
means block the current thread for at least the number of timeslices (or thread quantums) that can occur withinn
milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more thann
milliseconds. The likelihood that your thread will re-awaken exactly aftern
milliseconds is about as impossible as impossible can be. So,Thread.Sleep
is pointless for timing.Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.
The preferred solution: WaitHandles
The most-made-mistake is using Thread.Sleep
with a while-construct (demo and answer, nice blog-entry)
EDIT:
I would like to enhance my answer:
We have 2 different use-cases:
We are waiting because we know a specific timespan when we should continue (use
Thread.Sleep
,System.Threading.Timer
or alikes)We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!
My answer mainly covers use-case 2
I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.
Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.
However this answer is simple, infact very simple and yea many have mentioned it that simply put the id of image into the following link https://drive.google.com/uc?export=view&id={fileId}
But however easy that is, I made a script to run in the console. Feed in an array of complete sharable links from google drive and get them converted into the above link. Then they can be simply used as static addresses.
array = ['https://drive.google.com/open?id=0B8kNn6zsgGEtUE5FaGNtcEthNWc','https://drive.google.com/open?id=0B8kNn6zsgGEtM2traVppYkhsV2s','https://drive.google.com/open?id=0B8kNn6zsgGEtNHgzT2x0MThJUlE']_x000D_
_x000D_
function separateDriveImageId(arr) {_x000D_
for (n=0;n<arr.length;n++){_x000D_
_x000D_
str = arr[n]_x000D_
_x000D_
for(i=0;i<str.length;i++){_x000D_
if( str.charAt(i)== '=' ){_x000D_
var num = i+1;_x000D_
var extrctdStrng = str.substr(num)_x000D_
_x000D_
}_x000D_
}_x000D_
console.log('https://drive.google.com/uc?export=view&id='+extrctdStrng)_x000D_
window.open('https://drive.google.com/uc?export=view&id='+extrctdStrng,'_blank')_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
separateDriveImageId(array)
_x000D_
You could use the System.Net.Mail.MailMessage class of the .NET framework.
You can find the MSDN documentation here.
Here is a simple example (code snippet):
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
...
try
{
SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");
// set smtp-client with basicAuthentication
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new
System.Net.NetworkCredential("username", "password");
mySmtpClient.Credentials = basicAuthenticationInfo;
// add from,to mailaddresses
MailAddress from = new MailAddress("[email protected]", "TestFromName");
MailAddress to = new MailAddress("[email protected]", "TestToName");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// add ReplyTo
MailAddress replyTo = new MailAddress("[email protected]");
myMail.ReplyToList.Add(replyTo);
// set subject and encoding
myMail.Subject = "Test message";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
}
catch (SmtpException ex)
{
throw new ApplicationException
("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
Try this:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
in your code should be,
@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})
I have had co-workers that have used Burp ("an interactive HTTP/S proxy server for attacking and testing web applications") for this. You also may be able to use Fiddler ("a HTTP Debugging Proxy").
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
If you want to restrict your search only to files you should consider to use -type f
in your search
try to use also -iname
for case-insensitive search
Example:
find /path -iname 'yourstring*' -type f
You could also perform some operations on results without pipe sign or xargs
Example:
Search for files and show their size in MB
find /path -iname 'yourstring*' -type f -exec du -sm {} \;
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the Fragment Manager
to create a Fragment Transaction
.
Within each Fragment Transaction you can specify in and out animations that will be used for show and hide respectively (or both when replace is used).
The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
DetailsFragment newFragment = DetailsFragment.newInstance();
ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");
// Start the animated transition.
ft.commit();
To achieve the same thing with hiding or showing a fragment you'd simply call ft.show
or ft.hide
, passing in the Fragment you wish to show or hide respectively.
For reference, the XML animation definitions would use the objectAnimator
tag. An example of slide_in_left might look something like this:
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="x"
android:valueType="floatType"
android:valueFrom="-1280"
android:valueTo="0"
android:duration="500"/>
</set>
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
you can also introspect all HTTP traffic running over your tunnels using ngrok
, then you can expose using ngrok http --host-header=rewrite 4200
Follow the below steps. I also encountered the same problem.
run command npm install npm-install
as shown in the image:
Here we go.. npm start...wao
Here is a function to do it and seems reasonably fast.
endv<-function(vec,val)
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}
USAGE:
test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)
BENCHMARK:
test replications elapsed relative
1 expression(tail(x, 5)) 100000 5.24 6.469
2 expression(x[seq.int(to = length(x), length.out = 5)]) 100000 0.98 1.210
3 expression(x[length(x) - (4:0)]) 100000 0.81 1.000
4 expression(endv(x, 5)) 100000 1.37 1.691
It's a little on the cumbersome side, but I believe this should work (without the extra join). This assumes that you can choose a character that will never appear in the field in question, to act as a separator.
You can do it without nesting the select, but I find this a little cleaner that having four references to SYS_CONNECT_BY_PATH.
select id,
parent_id,
case
when lvl <> 1
then substr(name_path,
instr(name_path,'|',1,lvl-1)+1,
instr(name_path,'|',1,lvl)
-instr(name_path,'|',1,lvl-1)-1)
end as name
from (
SELECT id, parent_id, sys_connect_by_path(name,'|') as name_path, level as lvl
FROM tbl
START WITH id = 1
CONNECT BY PRIOR id = parent_id)
It's necessary to mention that returning copy or view depends on kind of indexing.
The pandas documentation says:
Returning a view versus a copy
The rules about when a view on the data is returned are entirely dependent on NumPy. Whenever an array of labels or a boolean vector are involved in the indexing operation, the result will be a copy. With single label / scalar indexing and slicing, e.g. df.ix[3:6] or df.ix[:, 'A'], a view will be returned.
In the cell you want your result to appear, use the following formula:
=COUNTIF(A1:A200,"<>")
That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.
I think this might be helpful:
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Yet another approach: use rbind
on out
:
before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
out <- strsplit(as.character(before$type),'_and_')
do.call(rbind, out)
[,1] [,2]
[1,] "foo" "bar"
[2,] "foo" "bar_2"
[3,] "foo" "bar"
[4,] "foo" "bar_2"
And to combine:
data.frame(before$attr, do.call(rbind, out))
I've already encountered this error and this is the best solution I've found:
In your root folder (probably called public_html)please add this code to your .htaccess file...
REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999
#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
In your wp-admin folder please add this code to your .htaccess file...
#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
pip3 install BeautifulSoup4
Try this. It works for me. The reason is well explained here..
You can see a difference between the two contexts when you launch your app directly from the home screen vs when your app is launched from another app via share intent.
Here a practical example of what "non-standard back stack behaviors", mentioned by @CommonSenseCode, means:
Suppose that you have two apps that communicate with each other, App1 and App2.
Launch App2:MainActivity from launcher. Then from MainActivity launch App2:SecondaryActivity. There, either using activity context or application context, both activities live in the same task and this is ok (given that you use all standard launch modes and intent flags). You can go back to MainActivity with a back press and in the recent apps you have only one task.
Suppose now that you are in App1 and launch App2:MainActivity with a share intent (ACTION_SEND or ACTION_SEND_MULTIPLE). Then from there try to launch App2:SecondaryActivity (always with all standard launch modes and intent flags). What happens is:
if you launch App2:SecondaryActivity with application context on Android < 10 you cannot launch all the activities in the same task. I have tried with android 7 and 8 and the SecondaryActivity is always launched in a new task (I guess is because App2:SecondaryActivity is launched with the App2 application context but you're coming from App1 and you didn't launch the App2 application directly. Maybe under the hood android recognize that and use FLAG_ACTIVITY_NEW_TASK). This can be good or bad depending on your needs, for my application was bad.
On Android 10 the app crashes with the message
"Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?".
So to make it work on Android 10 you have to use FALG_ACTIVITY_NEW_TASK and you cannot run all activities in the same task.
As you can see the behavior is different between android versions, weird.
if you launch App2:SecondaryActivity with activity context all goes well and you can run all the activities in the same task resulting in a linear backstack navigation.
I hope I have added some useful information
For me this works perfect
insert into oehr.employees select * from employees where employee_id=99
I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.
One good approach will be to use the answer @Parodo specified
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
In package json:
{
"name": "abc",
"version": "0.0.1",
"description": "my server",
"scripts": {
"start": "nodemon my_file.js"
},
"devDependencies": {
"nodemon": "~1.3.8",
},
"dependencies": {
}
}
Then from the terminal you can use npm start
Nodemon installation: https://www.npmjs.com/package/nodemon
Lets give an example that would explain the difference between hashtable and dictionary.
Here is a method that implements hashtable
public void MethodHashTable()
{
Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add('A', 300); // char
objHashTable.Add("4", 400); // string
lblDisplay1.Text = objHashTable[1].ToString();
lblDisplay2.Text = objHashTable[2.99].ToString();
lblDisplay3.Text = objHashTable['A'].ToString();
lblDisplay4.Text = objHashTable["4"].ToString();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}
The following is for dictionary
public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error
foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}
If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test
rather than the default unittest
module.
Consider these two examples, which do the same thing:
Example 1 (unittest):
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
Example 2 (pytest):
def test_starting_out():
assert 1 == 1
Assuming that both files are named test_unittesting.py
, how do we run the tests?
Example 1 (unittest):
cd /path/to/dir/
python test_unittesting.py
Example 2 (pytest):
cd /path/to/dir/
py.test
If your project budged allows you to have enough RAM memory on your environment - answer is Redis. Especially taking in account new Redis 3.2 with cluster functionality.
A secure random API was just added to dart:math
new Random.secure()
dart:math
Random
added asecure
constructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.
which delegates to window.crypto.getRandomValues()
in the browser and to the OS (like urandom
on the server)
I found the same error, and it took two days to identify what the error was.
The error was simply because I was trying to use: android:background
Rather than: app:srcCompat
in an SVG file.
In your case, I believe this is it
<ImageView
android:scaleType="fitXY"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/tour_11" <-- the error is here !
/>
I recommend using it this way
add this to your build.gradle app
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
and
<androidx.appcompat.widget.AppCompatImageView <-- use **AppCompatImageView** not **ImageView**
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/tour_11"
/>
I hope this helps.
If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:
ActiveCell.DisplayFormat.Interior.Color
This also seems to work just fine on regular cells.
For me, The problem was solved after I close Visual Studio and Open it again
You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).
Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.
When you create tcp connection using
TcpClient c; c = new TcpClient(remote_ip, remote_port);
Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.
If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.
Please note that jmap
should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.
One of the answers above mentions handling different pixel density but suggests computing the swipe parameters by hand. It is worth noting that you can actually obtain scaled, reasonable values from the system using ViewConfiguration
class:
final ViewConfiguration vc = ViewConfiguration.get(getContext());
final int swipeMinDistance = vc.getScaledPagingTouchSlop();
final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity();
final int swipeMaxOffPath = vc.getScaledTouchSlop();
// (there is also vc.getScaledMaximumFlingVelocity() one could check against)
I noticed that using these values causes the "feel" of fling to be more consistent between the application and rest of system.
Most of the above answers seem to require GNU commands/extensions:
$ head -n -2 myfile.txt
-2: Badly formed number
For a slightly more portible solution:
perl -ne 'push(@fifo,$_);print shift(@fifo) if @fifo > 10;'
OR
perl -ne 'push(@buf,$_);END{print @buf[0 ... $#buf-10]}'
OR
awk '{buf[NR-1]=$0;}END{ for ( i=0; i < (NR-10); i++){ print buf[i];} }'
Where "10" is "n".
There is no any method getCurrentItem() in viewpager.i already checked the API
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
Let me suggest you an easier approach,
Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;
Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.
Copy these two files into a text editor. Checkout master. Paste the files. Commit.
That simple.
pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.
Also I tried other solution, but some of the code executed after redirect.
public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
{
ResponseRedirect(iResponse, iUrl, HttpContext.Current);
}
public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
{
iResponse.Redirect(iUrl, false);
iContext.ApplicationInstance.CompleteRequest();
iResponse.BufferOutput = true;
iResponse.Flush();
iResponse.Close();
}
So if need to prevent code execution after redirect
try
{
//other code
Response.Redirect("")
// code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
//Logging
}
This should get you there every single time.
background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);
The first screenshot in your question is not a public widget. The support SearchView (android.support.v7.widget.SearchView
) mimics Android 5.0 Lollipop's SearchView (android.widget.SearchView
). Your second screenshot is used by other material designed apps like Google Play.
The SearchView in your first screenshot is used in Drive, YouTube and other closed source Google Apps. Fortunately, it is also used in the Android 5.0 Dialer. You can try to backport the view, but it uses some 5.0 APIs.
The classes which you will want to look at are:
SearchEditTextLayout, AnimUtils, and DialtactsActivity to understand how to use the View. You will also need resources from ContactsCommon.
Best of luck.
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
I think you are intended to contain ALL YOUR LOGIC under your if
statement. Basically:
' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
' you want to say
' If i = 4 CONTINUE but VBScript has no continue
If i <> 4 Then ' just invert the logic
WSH.Echo( i )
End If
Next
This can make the code a bit longer, but some people don't like break
or continue
anyway.
Different SQL, same principle. Only insert if the clause in where not exists fails
INSERT INTO FX_USDJPY
(PriceDate,
PriceOpen,
PriceLow,
PriceHigh,
PriceClose,
TradingVolume,
TimeFrame)
SELECT '2014-12-26 22:00',
120.369000000000,
118.864000000000,
120.742000000000,
120.494000000000,
86513,
'W'
WHERE NOT EXISTS
(SELECT 1
FROM FX_USDJPY
WHERE PriceDate = '2014-12-26 22:00'
AND TimeFrame = 'W')
I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file
~/.bash_profile
and append those lines
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
Use JSON Simple,
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
You can do something like this,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
You can try something like Routes.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
render() {
return (
<div>
<Route exact path="/" component={FrontPage} />
<Route exact path="/home" component={Homepage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/admin" component={Backend} />
<Route exact path="/admin/home" component={Dashboard} />
<Route exact path="/users" component={UserPage} />
</div>
)
}
}
export default Routes
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';
class App extends Component {
render() {
return (
<div className="App">
<Router>
<Routes/>
</Router>
</div>
);
}
}
export default App;
I think you can achieve the same from here also.
This answers a different question:
If trying to figure out if an OBJECT (not class) has a property,
OBJECT.GetType().GetProperty("PROPERTY") != null
returns true if (but not only if) the property exists.
In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
helped me here.
Edit: Nowadays, it's probably smart to use the nameof
operator instead of the stringified property name.
The Margin
property returns a Thickness
structure, of which Left
is a property. What the statement does is copying the structure value from the Margin
property and setting the Left
property value on the copy. You get an error because the value that you set will not be stored back into the Margin
property.
(Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...)
To set the property you would need to get the Thickness
structure from the Margin
property, set the value and store it back:
Thickness m = MyControl.Margin;
m.Left = 10;
MyControl.Margin = m;
If you are going to set all the margins, just create a Thickness
structure and set them all at once:
MyControl.Margin = new Thickness(10, 10, 10, 10);
'Pass by reference' (by using pointers) has been in C from the beginning. Why do you think it's not?
Yes, gcc can also compile assembly source code. Alternatively, you can invoke as
, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)
In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.
If both operands mismatch, a compile time error is thrown.
The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:
if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }
source: java programming lang 4th ed
just this as img tag is a content element
img {
content:url(http://example.com/image.png);
}
Here's a basic implementation of a line segment in C#, with corresponding intersection detection code. It requires a 2D vector/point struct called Vector2f
, though you can replace this with any other type that has X/Y properties. You could also replace float
with double
if that suits your needs better.
This code is used in my .NET physics library, Boing.
public struct LineSegment2f
{
public Vector2f From { get; }
public Vector2f To { get; }
public LineSegment2f(Vector2f @from, Vector2f to)
{
From = @from;
To = to;
}
public Vector2f Delta => new Vector2f(To.X - From.X, To.Y - From.Y);
/// <summary>
/// Attempt to intersect two line segments.
/// </summary>
/// <remarks>
/// Even if the line segments do not intersect, <paramref name="t"/> and <paramref name="u"/> will be set.
/// If the lines are parallel, <paramref name="t"/> and <paramref name="u"/> are set to <see cref="float.NaN"/>.
/// </remarks>
/// <param name="other">The line to attempt intersection of this line with.</param>
/// <param name="intersectionPoint">The point of intersection if within the line segments, or empty..</param>
/// <param name="t">The distance along this line at which intersection would occur, or NaN if lines are collinear/parallel.</param>
/// <param name="u">The distance along the other line at which intersection would occur, or NaN if lines are collinear/parallel.</param>
/// <returns><c>true</c> if the line segments intersect, otherwise <c>false</c>.</returns>
public bool TryIntersect(LineSegment2f other, out Vector2f intersectionPoint, out float t, out float u)
{
var p = From;
var q = other.From;
var r = Delta;
var s = other.Delta;
// t = (q - p) × s / (r × s)
// u = (q - p) × r / (r × s)
var denom = Fake2DCross(r, s);
if (denom == 0)
{
// lines are collinear or parallel
t = float.NaN;
u = float.NaN;
intersectionPoint = default(Vector2f);
return false;
}
var tNumer = Fake2DCross(q - p, s);
var uNumer = Fake2DCross(q - p, r);
t = tNumer / denom;
u = uNumer / denom;
if (t < 0 || t > 1 || u < 0 || u > 1)
{
// line segments do not intersect within their ranges
intersectionPoint = default(Vector2f);
return false;
}
intersectionPoint = p + r * t;
return true;
}
private static float Fake2DCross(Vector2f a, Vector2f b)
{
return a.X * b.Y - a.Y * b.X;
}
}
For me the problem was fixed by creating a folder
pip
, with a file: pip.ini
in
C:\Users\<username>\AppData\Roaming\
e.g:
C:\Users\<username>\AppData\Roaming\pip\pip.ini
Inside it I wrote:
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
I restarted python, and then pip permanently trusted these sites, and used them to download packages from.
If you can't find the AppData Folder on windows, write %appdata%
in file explorer and it should appear.
input[type='text'],textarea {font-size:1em;}
var clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var element = document.getElementById('element-id');
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
element.dispatchEvent
is supported in all major browsers. The example above is based on an sample simulateClick()
function on MDN.
Most likely the socket is held by some process. Use netstat -o
to find which one.
Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.
The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.
There are ways around this behavior by only using Linq queries with the .NoTracking()
extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.
date.setTime( date.getTime() + days * 86400000 );
See answer here: How to control web page caching, across all browsers?
The list is just examples of different techniques, it's not for direct insertion. If copied, the second would overwrite the first and the fourth would overwrite the third because of the http-equiv declarations AND fail with the W3C validator. At most, one could have one of each http-equiv declarations; pragma, cache-control and expires. These are completely outdated when using modern up to date browsers. After IE9 anyway. Chrome and Firefox specifically does not work with these as you would expect, if at all.
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
Caching headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query
It depends on which version of PHP your MAMP is using. You can find it out on: /Applications/MAMP/conf/apache/httpd.conf
looking for the configured php5_module
.
After that, as someone said before, you have to go to the bin
folder. There you'll find a conf
folder with a php.ini
inside.
example: /Applications/MAMP/bin/php/php5.4.10/conf
Leo
Use the following code:
if(isset($_SERVER['HTTPS']) == 'on')
{
$self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
<script type='text/javascript'>
window.location.href = 'http://<?php echo $self ?>';
</script>"
<?php
exit();
}
?>