Try this:
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
I'd like to point out the Vaex package.
Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.
If you know the bitrate, it's simply bitrate (bits per second) multiplied by number of seconds. Given that HDV is 25 Mbit/s and one hour has 3,600 seconds, non-transcoded it would be:
25 Mbit/s * 3,600 s/hr = 3.125 MB/s * 3,600 s/hr = 11,250 MB/hr ˜ 11 GB/hr
Google's calculator can confirm
The same applies with H.264 footage, although the above might not be as accurate (being variable bitrate and such).
I want to archive approximately 100 hours of such content and want to figure out whether I'm looking at a big hard drive, a multi-drive unit like a Drobo, or an enterprise-level storage system.
First, do not buy an "enterprise-level" storage system (you almost certainly don't need things like hot-swap drives and the same level of support - given the costs)..
I would suggest buying two big drives: One would be your main drive, another in a USB enclosure, and would be connected daily and mirror the primary system (as a backup).
Drives are incredibly cheap, using the above calculation of ~11 GB/hour, that's only 1.1 TB of data (for 100 hours, uncompressed). and you can buy 2 TB drives now.
Drobo, or a machine with a few drives and software RAID is an option, but a single large drive plus backups would be simpler.
Storage is almost a non-issue now, but encode time can still be an issue. Encoding H.264 is very resource-intensive. On a quad-core ~2.5 GHz Xeon, I think I got around 60 fps encoding standard-def (DVD) to H.264 (compared to around 300 fps with MPEG 4). I suppose that's only about 50 hours, but it's something worth considering. Also, assuming the HDV is on tapes, it's a 1:1 capture time, so that's 150 hours of straight processing, never mind things like changing tapes, entering metadata, and general delays (sleep) and errors ("opps, wrong tape").
In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.
component.html
<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio1" value="option1" type="radio"> TRUE
</label>
<label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio2" value="option2" type="radio"> FALSE
</label>
</div>
component.ts file
@Component({
selector: '',
templateUrl: './.component.html',
styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
checked = true;
}
You can't predefine a size of an array in php. A good way to acheive your goal is the following:
// Create a new array.
$array = array();
// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
array_push($array, $some_data);
//or $array[] = $some_data; for single items.
}
Note that it is way faster to use array_fill() to fill an Array :
$array = array_fill(0,$number_of_items, $some_data);
If you want to verify if a value has been set at an index, you should use the following: array_key_exists("key", $array) or isset($array["key"])
See array_key_exists , isset and array_fill
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )
I fetch all items from dynamodb with the following query. It works fine. i create these function generic in zend framework and access these functions over the project.
public function getQuerydata($tablename, $filterKey, $filterValue){
return $this->getQuerydataWithOp($tablename, $filterKey, $filterValue, 'EQ');
}
public function getQuerydataWithOp($tablename, $filterKey, $filterValue, $compOperator){
$result = $this->getClientdb()->query(array(
'TableName' => $tablename,
'IndexName' => $filterKey,
'Select' => 'ALL_ATTRIBUTES',
'KeyConditions' => array(
$filterKey => array(
'AttributeValueList' => array(
array('S' => $filterValue)
),
'ComparisonOperator' => $compOperator
)
)
));
return $result['Items'];
}
//Below i Access these functions and get data.
$accountsimg = $this->getQuerydataWithPrimary('accounts', 'accountID',$msgdata[0]['accountID']['S']);
For Googlers, another way to get a list of users is to use:
Get-WmiObject -Class Win32_UserAccount
Simple :
with open("test.txt") as f:
data = f.readlines()
tail = data[-2:]
print(''.join(tail)
Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/
<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
$a = NULL;
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
unset($a);
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
?>
Per that it seems like "= null" is faster.
PHP 5.4 results:
PHP 5.3 results:
PHP 5.2 results:
PHP 5.1 results:
Things start to look different with PHP 5.0 and 4.4.
5.0:
4.4:
Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.
In my case I needed to put my authorized_keys
file in .openssh
.
This location is specified in /etc/ssh/sshd_config
under the option AuthorizedKeysFile %h/.ssh/authorized_keys
.
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
On the same topic :
Here's my spin on how to get the difference in days between two dates with PHP. Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.
I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" name="form.firstname">
<br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress">
<br/><br/>
<textarea rows="3" cols="25">
Describe your reason for submitting this form ...
</textarea>
<br/>
<input type="radio" ng-model="form.gender" value="female" />Female
<input type="radio" ng-model="form.gender" value="male" />Male
<br/><br/>
<input type="checkbox" ng-model="form.member" value="true"/> Already a member
<input type="checkbox" ng-model="form.member" value="false"/> Not a member
<br/>
<input type="file" ng-model="form.file_profile" id="file_profile">
<br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<input type="submit">
</form>
</div>
Here I'm using lots of angular directives(ng-controller
, ng-model
, ng-submit
) where you were using basic html form submission.
Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission
BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.
For general advice on angular form submission see the cookbook examples
UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission
The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.
Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
The problem is that the execution policy is set on a per user basis. You'll need to run the following command in your application every time you run it to enable it to work:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
There probably is a way to set this for the ASP.NET user as well, but this way means that you're not opening up your whole system, just your application.
(Source)
I know you didn't want to use floats and the question was just theory but in case anyone finds this useful, here's a solution using floats.
Add a class of left to your li
elements that you want to float:
<li class="left"><img src="http://phrogz.net/tmp/alphaball.png">Smells Good</li>
and amend your CSS as follows:
li { text-align:center; float: left; clear: left; padding:0.1em 1em }
.left {float: left; clear: none;}
http://jsfiddle.net/chut319/xJ3pe/
You don't need to specify widths or inline-blocks and works as far back as IE6.
To answer your question you can use ES6 features,
var var=10;
console.log(`var=${var}`);
Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.
<script>
function test()
{
value = document.getElementById("ea_pub_dest").value;
if ( valor == "value_1" )
document.getElementById("ea_pub_dest_nivel").style.display = "block";
}
</script>
Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)
{
"shortcuts":[
{
"command": "completer:invoke-file",
"keys": [
"Ctrl Space"
],
"selector": ".jp-FileEditor .jp-mod-completer-enabled"
},
{
"command": "completer:invoke-file",
"keys": [
"Ctrl Space"
],
"selector": ".jp-FileEditor .jp-mod-completer-enabled"
},
{
"command": "completer:invoke-notebook",
"keys": [
"Ctrl Space"
],
"selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
}
]
}
The answer must depend on the usage of the string. There are many strings that may be "valid base64" according to the syntax suggested by several posters, but that may "correctly" decode, without exception, to junk. Example: the 8char string Portland
is valid Base64. What is the point of stating that this is valid Base64? I guess that at some point you'd want to know that this string should or should not be Base64 decoded.
In my case, I have Oracle connection strings that may be in plain text like:
Data source=mydb/DBNAME;User Id=Roland;Password=.....`
or in base64 like
VXNlciBJZD1sa.....................................==
I just have to check for the presence of a semicolon, because that proves that it is NOT base64, which is of course faster than any above method.
It seems that MediaStore.Images.Media.getBitmap
was deprecated in API 29
. The recommended way is to use ImageDecoder.createSource
which was added in API 28
.
Here's how getting the bitmap would be done:
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
} else {
MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
}
If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.
Just handling the FocusEnter
event doesn't work, because the Click
event comes afterwards, and overrides the selection if you SelectAll()
in the Focus event.
private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
isFirstTimeEntering = true;
}
private void textBox_Click(object sender, EventArgs e)
{
switch (isFirstTimeEntering)
{
case true:
isFirstTimeEntering = false;
break;
case false:
return;
}
textBox.SelectAll();
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}
for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
if createunicode(a.text) in ['<','<']:
links.append(a.attrMap['href'])
else:
continue
It works for me.
Dir.pwd
seems to do the trick.
<activity android:name="[packagename optional].ActivityClassName"></activity>
Simply adding the activity which we want to switch to should be placed in the manifest file
For those using Visual Studio + Git and wanting to keep the file history (works renaming both projects and/or solutions):
Close Visual Studio
In the .gitignore file, duplicate all ignore paths of the project you want to rename with renamed versions of those paths.
Use the Git move command like this:
git mv <old_folder_name> <new_folder_name>
See documentation for additional options: https://git-scm.com/docs/git-mv
In your .sln file: Find the line defining your project and change the folder name in path. The line should look something like:
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "<Project name>", "<path-to-project>\<project>.csproj"
Open Visual Studio, and right click on project → Rename
Afterwards, rename the namespaces.
I read that ReSharper has some options for this. But simple find/replace did the job for me.
Remove old .gitignore paths.
Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw
AssertionErrors
everywhere, and that is obviously not what happens.
The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private
and not calling it from within Example
's code). And so if a call occurs, that assertion has been violated, and so AssertionError
is appropriate.
if you click some button,then change the datatables the displaylenght,you can try this :
$('.something').click( function () {
var oSettings = oTable.fnSettings();
oSettings._iDisplayLength = 50;
oTable.fnDraw();
});
oTable = $('#example').dataTable();
you may use like that
System.out.println(Integer.decode("0x4d2")) // output 1234
//and vice versa
System.out.println(Integer.toHexString(1234); // output is 4d2);
Yeah it is possible with FileReader, I have already done an example of this, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.
Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
reader.open('get', 'test.txt', true);
reader.onreadystatechange = displayContents;
reader.send(null);
}
function displayContents() {
if(reader.readyState==4) {
var el = document.getElementById('main');
el.innerHTML = reader.responseText;
}
}
</script>
</head>
<body>
<div id="container">
<input type="button" value="test.txt" onclick="loadFile()" />
<div id="main">
</div>
</div>
</body>
</html>
var data={
userName: $('#userName').val(),
email: $('#email').val(),
//add other properties similarly
}
and
$.ajax({
type: "POST",
url: "http://rt.ja.com/includes/register.php?submit=1",
data: data
success: function(html)
{
//alert(html);
$('#userError').html(html);
$("#userError").html(userChar);
$("#userError").html(userTaken);
}
});
You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.
Sometimes you want to keep these things contained within your component. Depending on DOM state (the elements you're listening on must exist in DOM when your Vue component is instantiated), you can listen to events on elements outside of your component from within your Vue component. Let's say there is an element outside of your component, and when the user clicks it, you want your component to respond.
In html you have:
<a href="#" id="outsideLink">Launch the component</a>
...
<my-component></my-component>
In your Vue component:
methods() {
doSomething() {
// do something
}
},
created() {
document.getElementById('outsideLink').addEventListener('click', evt =>
{
this.doSomething();
});
}
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
Consider the following query:
$iId = mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
mysql_real_escape_string()
will not protect you against this.
The fact that you use single quotes (' '
) around your variables inside your query is what protects you against this. The following is also an option:
$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";
I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.
(Note that this answer refers to Python 3.x. In Python 2.x you'll get a TypeError
for calling the method on the class itself.)
For example:
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
def rollCall(n): #this is implicitly a class method (see comments below)
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
In this code, the "rollCall" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as "rollCall" is called from the class rather than an instance, the code will work fine. If we try to call "rollCall" from an instance, e.g.:
rex.rollCall(-1)
however, it would cause an exception to be raised because it would send two arguments: itself and -1, and "rollCall" is only defined to accept one argument.
Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.
This is where the decoration comes in: If we precede the "rollCall" method with
@staticmethod
then, by explicitly stating that the method is static, we can even call it from an instance. Now,
rex.rollCall(-1)
would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.
You can verify this by trying the following code with and without the @staticmethod line commented out.
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
@staticmethod
def rollCall(n):
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)
a and b must both be sets of the same type. But nothing prevents you from writing
myfunction(Set<X> a, Set<Y> b)
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
Default Export (export default
)
// MyClass.ts -- using default export
export default class MyClass { /* ... */ }
The main difference is that you can only have one default export per file and you import it like so:
import MyClass from "./MyClass";
You can give it any name you like. For example this works fine:
import MyClassAlias from "./MyClass";
Named Export (export
)
// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }
When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:
import { MyClass } from "./MyClass";
Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.
Or say your file exported multiple classes, then you could import both like so:
import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass
Or you could give either of them a different name in this file:
import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias
Or you could import everything that's exported by using * as
:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here
Which to use?
In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
It also plays very nicely with barrel files (files that use namespace exports—export *
—to export other files). An example of this is shown in the "example" section of this answer.
Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";
. If you disagree with me about doing this, I would love to hear your reasoning.
That said, find what you prefer! You could use one, the other, or both at the same time.
Additional Points
A default export is actually a named export with the name default
, so if the file has a default export then you can also import by doing:
import { default as MyClass } from "./MyClass";
And take note these other ways to import exist:
import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports
Why don't you just use CopyToDataTable
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
This is easily achieved in ES6;
You can convert strings to Arrays with Array.from('string');
Array.from("01")
will console.log
['0', '1']
Which is exactly what you're looking for.
Simply use sudo yum install php-zip
You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.
And what is p->param?
Actually, it isn't clear what do you want to do
I experienced the same problem developing a client-server app using Microsoft Visual Studio 2012.
If you used Visual Studio to develop the app, you must make sure the new (i.e. the computer that the software was not developed on) has the appropriate Microsoft Visual C++ Redistributable Package. By appropriate, you need the right year and bit version (i.e. x86 for 32 bit and x64 for 64 bit) of the Visual C++ Redistributable Package.
The Visual C++ Redistributable Packages install run-time components that are required to run C++ applications built using Visual Studio.
Here is a link to the Visual C++ Redistributable for Visual Studio 2015 .
You can check what versions are installed by going to Control Panel -> Programs -> Programs and Features.
Here's how I got this error and fixed it:
1) I developed a 32 bit application using Visual Studio 2012 on my computer. Let's call my computer ComputerA.
2) I installed the .exe and the related files on a different computer we'll call ComputerB.
3) On ComputerB, I ran the .exe and got the error message.
4) On ComputerB, I looked at the Programs and Features and didn't see Visual C++ 2012 Redistributable (x64).
5) On ComputerB, I googled for Visual C++ 2012 Redistributable and selected and installed the x64 version.
6) On ComputerB, I ran the .exe on ComputerB and did not receive the error message.
Same error, solved by updating Google Nuget support packages
/**
* @expectedException Exception
* @expectedExceptionMessage Amount has to be bigger then 0!
*/
public function testDepositNegative()
{
$this->account->deposit(-7);
}
Be very carefull about "/**"
, notice the double "*". Writing only "**"(asterix) will fail your code.
Also make sure your using last version of phpUnit. In some earlier versions of phpunit @expectedException Exception is not supported. I had 4.0 and it didn't work for me, I had to update to 5.5 https://coderwall.com/p/mklvdw/install-phpunit-with-composer to update with composer.
I got this error when I tried to set a column as unique when there was already duplicate data in the column OR if you try to add a column and set it as unique when there is already data in the table.
I had a table with 5 rows and I tried to add a unique column and it failed because all 5 of those rows would be empty and thus not unique.
I created the column without the unique index set, then populated the data then set it as unique and everything worked.
Another Variation can be... Be sure to close the file afterwards
import sys
file = open('output.txt', 'a')
sys.stdout = file
print("Hello stackoverflow!")
print("I have a question.")
file.close()
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
You must to wrap your following code into a block (Either method or static).
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
Without a block you can only declare variables and more than that assign them a value in single statement.
For method main() will be best choice for now:
public class details {
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or If you want to use static block then...
public class details {
static {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or if you want to build another method then..
public class details {
public static void main(String[] args){
myMethod();
}
private static void myMethod(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
Also worry about exception due to BufferedReader .
resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...
hard-size your DIV relative to your image
position your asp:login control where needed...
I got the same error, what worked for me is:
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
I had this part enabled in my php.ini
extension=php_memcache.dll
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211
After commenting these lines composer was installed in my windows 10
Just call array.ToObject<List<SelectableEnumItem>>()
method. It will return what you need.
Documentation: Convert JSON to a Type
# To support matches from the beginning, not any matches:
items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'
filter(lambda x: x.startswith(prefix), items)
div {
background: #dbdbdb;
-webkit-transition: .5s all;
-webkit-transition-delay: 5s;
-moz-transition: .5s all;
-moz-transition-delay: 5s;
-ms-transition: .5s all;
-ms-transition-delay: 5s;
-o-transition: .5s all;
-o-transition-delay: 5s;
transition: .5s all;
transition-delay: 5s;
}
div:hover {
background:#5AC900;
-webkit-transition-delay: 0s;
-moz-transition-delay: 0s;
-ms-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
}
This will add a transition delay, which will be applicable to almost every browser..
file.lines
with JFile package
var JFile=require('jfile');
var myF=new JFile("./data.txt");
myF.lines // ["first line","second line"] ....
Don't forget before :
npm install jfile --save
you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...
View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);
make sure your css reads:
margin: 0 auto;
Even though you're saying you have the left and right set to auto, you may be placing an error. Of course we wouldn't know though because you did not show us any code.
For anyone encountering this issue with Capistrano: capistrano isn't able to locate the bundler
. The reason might be that you installed bundler under some other gemset
where the Capistrano isn't even looking.
rvm gemset list
rvm use 'my_get_set'
gem install bundler
Then, try again with the deploy task.
You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""
std::bitset
has a .to_string()
method that returns a std::string
holding a text representation in binary, with leading-zero padding.
Choose the width of the bitset as needed for your data, e.g. std::bitset<32>
to get 32-character strings from 32-bit integers.
#include <iostream>
#include <bitset>
int main()
{
std::string binary = std::bitset<8>(128).to_string(); //to binary
std::cout<<binary<<"\n";
unsigned long decimal = std::bitset<8>(binary).to_ulong();
std::cout<<decimal<<"\n";
return 0;
}
EDIT: Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.
pyenv
can be used in Linux/MacOS for python version management. pyenv-win
is the fork of pyenv
which can be used on Windows.
Tested on Mac Catalina
Install pyenv
.
brew install pyenv
Add following to your shell config file:
.bashrc
/.bash_profile
- For Bash.zshrc
- For Zshexport PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
Restart your shell. Start a new shell or run exec "$SHELL"
in your current shell.
Tested on Arch Linux
Install pyenv
on your system.
curl https://pyenv.run | bash
Follow same steps as in Step 2 and 3 of MacOS installation.
Install pyenv-win
on Windows.
In Powershell
pip install pyenv-win --target "$HOME\.pyenv"
In cmd.exe
pip install pyenv-win --target "%USERPROFILE%\.pyenv"
Setup the environment variables using Powershell/Terminal.
[System.Environment]::SetEnvironmentVariable('PYENV',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
[System.Environment]::SetEnvironmentVariable('PYENV_HOME',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
[System.Environment]::SetEnvironmentVariable('path', $HOME + "\.pyenv\pyenv-win\bin;" + $HOME + "\.pyenv\pyenv-win\shims;" + $env:Path,"User")
Close and re-open your terminal. Run pyenv --version
on the terminal.
a. If the return value is the installed version of pyenv, then continue below. b. If you receive a command not found error, ensure the environment variables are properly set via the GUI: This PC ? Properties ? Advanced system settings ? Advanced ? Environment Variables... ? PATH c. If you receive a command not found error and you are using Visual Studio Code or another IDE with a built in terminal, restart it and try again.
Run pyenv rehash
from the home directory.
pyenv versions
Example
$ pyenv versions
* system (set by /home/souser/.pyenv/version)
3.6.9
pyenv install <version-number>
pyenv uninstall <version-number>
pyenv global <version-number> # <version-number> is the name assigned to your python in output of `pyenv versions`
Example
$ python --version
Python 3.9.1
$ pyenv global 3.6.9
$ python --version
Python 3.6.9
Set a python version for a directory and all it's sub-directories
pyenv local <version-number> # <version-number> is the name assigned to your python in output of `pyenv versions`
Example
~/tmp/temp$ python --version
Python 3.9.1
~/tmp/temp$ pyenv local 3.6.9
~/tmp/temp$ python --version
Python 3.6.9
For more details, you can check the Github repos : pyenv and pyenv-win.
I always do this to download the packages:
pip install --download /path/to/download/to_packagename
OR
pip install --download=/path/to/packages/downloaded -r requirements.txt
And when I want to install all of those libraries I just downloaded, I do this:
pip install --no-index --find-links="/path/to/downloaded/dependencies" packagename
OR
pip install --no-index --find-links="/path/to/downloaded/packages" -r requirements.txt
Update
Also, to get all the packages installed on one system, you can export them all to requirement.txt
that will be used to intall them on another system, we do this:
pip freeze > requirement.txt
Then, the requirement.txt
can be used as above for download, or do this to install them from requirement.txt
:
pip install -r requirement.txt
REFERENCE: pip installer
Another easier way to print the whole string is to call values
on the dataframe.
df = pd.DataFrame({'one' : ['one', 'two',
'This is very long string very long string very long string veryvery long string']})
print(df.values)
The Output will be
[['one']
['two']
['This is very long string very long string very long string veryvery long string']]
Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".
Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
Func<int, int, int> funcAdd = (x, y) => x + y;
c=funcAdd.Invoke(a, b);
Console.WriteLine(Convert.ToString(c));
}
}
}
Regular expressions are overkill for this situation. You can use the String.IndexOfAny()
method in combination with Path.GetInvalidPathChars()
and Path.GetInvalidFileNameChars()
.
Also note that both Path.GetInvalidXXX()
methods clone an internal array and return the clone. So if you're going to be doing this a lot (thousands and thousands of times) you can cache a copy of the invalid chars array for reuse.
I know the question was asked 7 years and 9 months ago
but many posted solutions doesn't seem to work, for example using an <iframe>
works only with FireFox
and doesn't work with Chrome
.
Best solution:
The best working solution to open a file download pop-up in JavaScript
is to use a HTML
link element, with no need to append the link element to the document.body
as stated in other answers.
You can use the following function:
function downloadFile(filePath){
var link=document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
In my application, I am using it this way:
downloadFile('report/xls/myCustomReport.xlsx');
Working Demo:
function downloadFile(filePath) {_x000D_
var link = document.createElement('a');_x000D_
link.href = filePath;_x000D_
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);_x000D_
link.click();_x000D_
}_x000D_
_x000D_
downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");
_x000D_
Note:
link.download
attribute so the browser doesn't
open the file in a new tab and fires the download pop-up.Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
You can also use findIndex and pick to achieve the same result:
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
var data = {id: 2, name: 'Person 2 (updated)'};
var index = _.findIndex(arr, _.pick(data, 'id'));
if( index !== -1) {
arr.splice(index, 1, data);
} else {
arr.push(data);
}
This should work
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
mBitmapSampled = BitmapFactory.decodeFile(mCurrentPhotoPath,options);
Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.
In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:
<p:selectOneListbox id="adminEvents" value="#{testBean.selectedEvent}">
... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}
, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.
Not sure if there is an easier way in 2008 version.
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName'
VS 2017 Professional edition- Go to Quick launch type "Class..." select Class designer and install it.
Once installed go to Add New Items search "Class Diagram" and you are ready to go.
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
You have indented part of your code in settings.py:
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'tinymce',
'sorl.thumbnail',
'south',
'django_facebook',
'djcelery',
'devserver',
'main',
Therefore, it is giving you an error.
If you don't care about formatting and you just need some quick date, you can use this:
import time
print(time.ctime())
This query worked for me:)
SELECT * FROM tbl_purchase_receipt
WHERE purchase_date BETWEEN '2008-09-09' AND '2009-09-09'
It simply take two dates and retrieves the values between them.
A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed
In another word change the entire value of that variable (name)
or leave it alone.
Example:
my_string = "Hello world"
my_string[0] = "h"
print my_string
you expected this to work and print hello world but this will throw the following error:
Traceback (most recent call last):
File "test.py", line 4, in <module>
my_string[0] = "h"
TypeError: 'str' object does not support item assignment
The interpreter is saying : i can't change the first character of this string
you will have to change the whole string
in order to make it works:
my_string = "Hello World"
my_string = "hello world"
print my_string #hello world
check this table:
The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].
You have to iterate through that values to get actuall value. Like the following
jQuery provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (linktext, link) {
console.log(linktext);
console.log(link);
});
});
Now just create an Hyperlink using that info.
Bitcode (iOS, watchOS)
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.
Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.
Devs don't have to make changes and submit the app again to support new platforms.
Let's take the example of iPhone 5s when apple introduced x64
chip in it. Although x86
apps were totally compatible with x64
architecture but to fully utilise the x64
platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.
If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64
bit architecture.
Use
position:absolute;
right: 0;
No need for float:right
with absolute positioning
Also, make sure the parent element is set to position:relative;
SYSDATE
is an Oracle only function.
The ANSI standard defines current_date
or current_timestamp
which is supported by Postgres and documented in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
(Btw: Oracle supports CURRENT_TIMESTAMP
as well)
You should pay attention to the difference between current_timestamp
, statement_timestamp()
and clock_timestamp()
(which is explained in the manual, see the above link)
This statement:
select up_time from exam where up_time like sysdate
Does not make any sense at all. Neither in Oracle nor in Postgres. If you want to get rows from "today", you need something like:
select up_time
from exam
where up_time = current_date
Note that in Oracle you would probably want trunc(up_time) = trunc(sysdate)
to get rid of the time part that is always included in Oracle.
What worked for me (on Windows, using git version 1.8.3.msysgit.0):
git submodule init
and git submodule update
After doing all that, everything is in the state I would expect. I imagine other users of the repository will have similar pain when they come to update though - it would be wise to explain these steps in your commit message!
My situation
empty Instance Name in SQL Server Management Studio > select your database engine > Right Mouse Button > Properties (Server Properties) > Link View connection properties > Product > Instance Name is empty
Data Source=.\SQLEXPRESS did not work => use localhost in web.config (see below)
Solution: in web.config
xxxxxx = name of my database without .mdf yyyyyy = name of my database in VS2012 database explorer
You can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost.
Set overflow-y
property to auto
, or remove the property altogether if it is not inherited.
There is a lot of mess going on here - people suggest solutions for non-primitive values, try to implement some sorting algos from the ground, give solutions involving additional libraries, showing off some hacky ones etc. The answer to the original question is 50/50. For those who just want to copy/paste:
// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};
// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++)
arrOfObjects[i] = new Integer(arrOfPrimitives[i]);
// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());
arrOfObjects
is {6,5,4,3,2,1}
now. If you have an array of something other than ints - use the corresponding object instead of Integer
.
This simple one-liner should work in any shell, not just bash:
ls -1q log* | wc -l
ls -1q will give you one line per file, even if they contain whitespace or special characters such as newlines.
The output is piped to wc -l, which counts the number of lines.
Using the SSH URL from GitLab:
Step 1: Generate an SSH Key with default values from GitLab.
GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.
STEP 2: Add the SSH key to your keychain using the command ssh-add -K
.
Open the terminal and paste the above command in it. This will add the key to your keychain.
STEP 3: Restart SourceTree and clone remote repo using URL.
Restarting SourceTree is needed so that SourceTree picks the new key.
STEP 4: Copy the SSH URL provided by GitLab.
STEP 5: Paste the SSH URL into the Source URL field of SourceTree.
These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.
I am assuming that active events in a time period means at least one day of the event falls inside the time period. This is a simple "find overlapping dates" problem and there is a generic solution:
-- [@d1, @d2] is the date range to check against
SELECT * FROM events WHERE @d2 >= start AND end >= @d1
Some tests:
-- list of events
SELECT * FROM events;
+------+------------+------------+
| id | start | end |
+------+------------+------------+
| 1 | 2013-06-14 | 2013-06-14 |
| 2 | 2013-06-15 | 2013-08-21 |
| 3 | 2013-06-22 | 2013-06-25 |
| 4 | 2013-07-01 | 2013-07-10 |
| 5 | 2013-07-30 | 2013-07-31 |
+------+------------+------------+
-- events between [2013-06-01, 2013-06-15]
SELECT * FROM events WHERE '2013-06-15' >= start AND end >= '2013-06-01';
+------+------------+------------+
| id | start | end |
+------+------------+------------+
| 1 | 2013-06-14 | 2013-06-14 |
| 2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+
-- events between [2013-06-16, 2013-06-30]
SELECT * FROM events WHERE '2013-06-30' >= start AND end >= '2013-06-16';
+------+------------+------------+
| id | start | end |
+------+------------+------------+
| 2 | 2013-06-15 | 2013-08-21 |
| 3 | 2013-06-22 | 2013-06-25 |
+------+------------+------------+
-- events between [2013-07-01, 2013-07-01]
SELECT * FROM events WHERE '2013-07-01' >= start AND end >= '2013-07-01';
+------+------------+------------+
| id | start | end |
+------+------------+------------+
| 2 | 2013-06-15 | 2013-08-21 |
| 4 | 2013-07-01 | 2013-07-10 |
+------+------------+------------+
-- events between [2013-07-11, 2013-07-29]
SELECT * FROM events WHERE '2013-07-29' >= start AND end >= '2013-07-11';
+------+------------+------------+
| id | start | end |
+------+------------+------------+
| 2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+
If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).
The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.
You should set JAVA_HOME
based on current Java you are using.
readlink
will print value of a symbolic link for current Java and sed
will adjust it to JRE directory:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
If you want to set up JAVA_HOME to JDK you should go up one folder more:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
To serialize an object, do:
using (StreamWriter myWriter = new StreamWriter(path, false))
{
XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
mySerializer.Serialize(myWriter, objectToSerialize);
}
Also remember that for XmlSerializer to work, you need a parameterless constructor.
You can simply use if(yourElement)
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
console.log("elemA exists");_x000D_
else_x000D_
console.log("elemA does not exist");_x000D_
_x000D_
if(b)_x000D_
console.log("elemB exists");_x000D_
else_x000D_
console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
Try this:
body {
background-image:url(img/background.jpg);
background-repeat: no-repeat;
min-height: 679px;
background-size: cover;
}
(see detailed explanation here)
$text = Get-Content $filePath | Out-String
The IO.File.ReadAllText
didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath
instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)
$text = Get-Content $filePath -Raw
As you’re in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference '
('
hexadecimal):
<input type='text' id='abc' value='hel'lo'>
You Just execute the following commands in your command prompt,
For 32 bit machine,
cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
For 64 bit machine,
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
For brevity, here's an ES2015 sample that doesn't rely on global variables
// controllers/example-controller.js
export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
// something...
}
// controllers/another-controller.js
export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
// functionality...
}
// app.js
import angular from "angular";
import {
ExampleControllerName,
ExampleController
} = "./controllers/example-controller";
import {
AnotherControllerName,
AnotherController
} = "./controllers/another-controller";
angular.module("myApp", [/* deps */])
.controller(ExampleControllerName, ExampleController)
.controller(AnotherControllerName, AnotherController)
I prefer
SELECT
MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
trading_summary t
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime);
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
An another way: your application can open a server socet and wait for an information arrived to it. For example a string with a "magic" word :) and then react to make shutdown: System.exit(). You can send such information to the socke using an external application like telnet.
I usually work with Notepad2, all the text I copy from the web are pasted there and then reused, that allows me to clean it (from format and make modifications).
In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.
Many developers will mistakenly use for
loop or foreach
and leave the SqlCommand
to execute outside the loop, to avoid that make sure that you have like this code sample for example:
public static void Save(List<myClass> listMyClass)
{
using (var Scope = new System.Transactions.TransactionScope())
{
if (listMyClass.Count > 0)
{
for (int i = 0; i < listMyClass.Count; i++)
{
SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);
try
{
myConnection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException sqe)
{
throw new Exception(sqe.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
myConnection.Close();
}
}
}
else
{
throw new Exception("List is empty");
}
Scope.Complete();
}
}
You can use this :
$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);
>>> mask = df['ids'].str.contains('ball')
>>> mask
0 True
1 True
2 False
3 True
Name: ids, dtype: bool
>>> df[mask]
ids vals
0 aball 1
1 bball 2
3 fball 4
A pointer to pointer is, well, a pointer to pointer.
A meaningfull example of someType** is a bidimensional array: you have one array, filled with pointers to other arrays, so when you write
dpointer[5][6]
you access at the array that contains pointers to other arrays in his 5th position, get the pointer (let fpointer his name) and then access the 6th element of the array referenced to that array (so, fpointer[6]).
In my case, I had to open up
Documents\IISExpress\config
folder and rename or delete existing config files. After this step, I ran the application and IISExpress generated new config files and the error was gone.
From the Python glossary:
It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a
__path__
attribute is considered a package.
Python files with a dash in the name, like my-file.py
, cannot be imported with a simple import
statement. Code-wise, import my-file
is the same as import my - file
which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.
If you are installing first time then please try login with username and password as root
The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:
for (int i = 0; i < 60; i++) {
list.add(0);
}
For apache 4.5.3, if you want to move the level for all apache http client logging to Warn, use:
log4j.logger.org.apache=WARN
If you are using the GET request to actually SEND data...
check: http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it: http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
Use an iframe
for the nested form. If they need to share fields, then... it's not really nested.
Follow the code below exactly matched with your case.
ie for
<div class="facetContainerDiv">
<div>
</div>
</div>
2. Create an IList with all the elements inside the second div i.e for,
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
3. Access each check boxes using the index
Please find the code below
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTests
{
class ChechBoxClickWthIndex
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("file:///C:/Users/chery/Desktop/CheckBox.html");
// Create an interface WebElement of the div under div with **class as facetContainerDiv**
IWebElement WebElement = driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
// Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
int RowCount = AllCheckBoxes.Count;
for (int i = 0; i < RowCount; i++)
{
// Check the check boxes based on index
AllCheckBoxes[i].Click();
}
Console.WriteLine(RowCount);
Console.ReadLine();
}
}
}
The following numpy implementation should be approx. 2x the speed of the given answer:
def cartesian2(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
It works like this:
String item = "http://www.youtube.com/embed/";
String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);
try {
wv.loadData(
"<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
+ (w1 - 20)
+ "\" height=\""
+ h1
+ "\" src=\""
+ item
+ "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
"text/html5", "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
private WebChromeClient chromeClient = new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
video.start();
}
}
}
};
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
To push up through a given commit, you can write:
git push <remotename> <commit SHA>:<remotebranchname>
provided <remotebranchname>
already exists on the remote. (If it doesn't, you can use git push <remotename> <commit SHA>:refs/heads/<remotebranchname>
to autocreate it.)
If you want to push a commit without pushing previous commits, you should first use git rebase -i
to re-order the commits.
If you want import some class like :
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
You can add the following line in the build.gradle (Gradle dependencies)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:support-v4:27.1.0'
.
.
.
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
According to this discussion, Promise
has finally been called CompletableFuture
for inclusion in Java 8, and its javadoc explains:
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
An example is also given on the list:
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
Note that the final API is slightly different but allows similar asynchronous execution:
CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
google.load("jquery", "1.7.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
</script>
But even he admits that it just doesn't compare to doing the following when it comes to optimal performance:
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
<script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>
I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT
when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);
This way it completely fills the available space. (You may need to use Tomik's solution too).
To use border radius I have a border radius of 20px in the table, and then put the border radius on the first child of the table header (th) and the last child of the table header.
table {
border-collapse: collapse;
border-radius:20px;
padding: 10px;
}
table th:first-child {
/* border-radius = top left, top right, bottom right, bottom left */
border-radius: 20px 0 0 0; /* curves the top left */
padding-left: 15px;
}
table th:last-child {
border-radius: 0 20px 0 0; /* curves the top right */
}
This however will not work if this is done with table data (td) because it will add a curve onto each table row. This is not a problem if you only have 2 rows in your table but any additional ones will add curves onto the inner rows too. You only want these curves on the outside of the table. So for this, add an id to your last row. Then you can apply the curves to them.
/* curves the first tableData in the last row */
#lastRow td:first-child {
border-radius: 0 0 0 20px; /* bottom left curve */
}
/* curves the last tableData in the last row */
#lastRow td:last-child {
border-radius: 0 0 20px 0; /* bottom right curve */
}
I also needed what you've been searching for and did some research.
I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.
Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.
You miss parenthesis:
var value: string = dataObjects[i].getValue();
var id: number = dataObjects[i].getId();
System.Uri.EscapeUriString()
can be problematic with certain characters, for me it was a number / pound '#' sign in the string.
If that is an issue for you, try:
System.Uri.EscapeDataString() //Works excellent with individual values
Here is a SO question answer that explains the difference:
What's the difference between EscapeUriString and EscapeDataString?
and recommends to use Uri.EscapeDataString()
in any aspect.
You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
I did it like this (temporarily turning on delayed expansion):
...
sqlcmd -b -S %COMPUTERNAME% -E -d %DBNAME% -Q "SELECT label from document WHERE label = '%DOCID%';" -h-1 -o Result.txt
if errorlevel 1 goto INVALID
:: Read SQL result and trim trailing whitespace
SET /P ITEM=<Result.txt
@echo ITEM is %ITEM%.
setlocal enabledelayedexpansion
for /l %%a in (1,1,100) do if "!ITEM:~-1!"==" " set ITEM=!ITEM:~0,-1!
setlocal disabledelayedexpansion
@echo Var ITEM=%ITEM% now has trailing spaces trimmed.
....
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
Another possibility that I encountered was that one of the packages in the repository ended up with a detached HEAD. If none of the answer here helps and you encounter a git status message like this you might have the same problem:
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: path/to/package (new commits)
Going into the path/to/package
folder a git status
should yield the following result:
HEAD detached at 7515f05
And the following command should then fix the issue, where master
should be replaced by your local branch:
git checkout master
And you'll get a message that your local branch will be some amounts of commits behind the remote branch. git pull
and you should be out of the woods!
Currently Angular CLI doesn't support an option to remove the component, you need to do it manually.
A primitive quick fix that works.
If you only use OpenFileDialog
, you can capture the FileName
, SafeFileName
, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...
But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.
If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.
Try this
<input type="text"/>
It will display same in all cross browser like mozilla , chrome and internet explorer.
<style>
input{
border:2px solid #FF0000;
}
</style>
Dont add style inline because its not good practise, use class to add style for your input box.
All way to make a redirect from the client side:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>JavaScript and jQuery example to redirect a page or URL </title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="redirect">_x000D_
<h2>Redirecting to another page</h2>_x000D_
</div>_x000D_
_x000D_
<script src="scripts/jquery-1.6.2.min.js"></script>_x000D_
<script>_x000D_
// JavaScript code to redirect a URL_x000D_
window.location.replace("http://stackoverflow.com");_x000D_
// window.location.replace('http://code.shouttoday.com');_x000D_
_x000D_
// Another way to redirect page using JavaScript_x000D_
_x000D_
// window.location.assign('http://code.shouttoday.com');_x000D_
// window.location.href = 'http://code.shouttoday.com';_x000D_
// document.location.href = '/relativePath';_x000D_
_x000D_
//jQuery code to redirect a page or URL_x000D_
$(document).ready(function(){_x000D_
//var url = "http://code.shouttoday.com";_x000D_
//$(location).attr('href',url);_x000D_
// $(window).attr('location',url)_x000D_
//$(location).prop('href', url)_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I use the following aliases.
[alias]
lol = log --graph --decorate --pretty=oneline --abbrev-commit
lola = log --graph --decorate --pretty=oneline --abbrev-commit --all
It has more info in the color scheme than aliases that I saw above. It also seems to be quite common, so you might have a chance of it existing in other's environment or being able to mention it in conversation without having to explain it.
With screenshots and a full description here: http://blog.kfish.org/2010/04/git-lola.html
Why not just use all Lambda syntax?
database.Stores.Where(s => s.CompanyID == curCompany.ID)
.Select(s => new SelectListItem
{
Value = s.Name,
Text = s.ID
});
This would work fine.
Push-Location $PSScriptRoot
Write-Host CurrentDirectory $CurDir
Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
I had a similar problem in revamping a web site in Dreamweaver. The site structure is based on a complex set of tables, and this video was in one of the main layout cells. I created a nested table just for the video and then added an align=center
attribute to the new table:
<table align=center><tr><td>
<video width=420 height=236 controls="controls" autoplay="autoplay">
<source src="video/video.ogv" type='video/ogg; codecs="theora, vorbis"'/>
<source src="video/video.webm" type='video/webm' >
<source src="video/video.mp4" type='video/mp4'>
<p class="sidebar">If video is not visible, your browser does not support HTML5 video</p>
</video>
</td></tr></table>
df_1.join(df_2)
df_1.merge(df_2)
on
parameter has different meaning in both casesdf_1.merge(df_2, on='column_1')
df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')
I tried this and worked for me.
success: function (response) {
document.getElementById('packageItems').value = response.package_items;
ClassicEditor
.create(document.querySelector('#packageItems'), {
removePlugins: ['dragdrop']
})
.then(function (editor) {
editor.setData(response.package_items);
})
.catch(function (err) {
console.error(err);
});
},
If you have simple dropdown like:
<select name="status" id="status">
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
Then you can use this code for getting value:
$(function(){
$("#status").change(function(){
var status = this.value;
alert(status);
if(status=="1")
$("#icon_class, #background_class").hide();// hide multiple sections
});
});
Just omit the [Required] attribute from the string somefield
property. This will make it create a NULL
able column in the db.
To make int types allow NULLs in the database, they must be declared as nullable ints in the model:
// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }
// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }
SQL Server doesn't have a boolean data type. As @Mikael has indicated, the closest approximation is the bit. But that is a numeric type, not a boolean type. In addition, it only supports 2 values - 0
or 1
(and one non-value, NULL
).
SQL (standard SQL, as well as T-SQL dialect) describes a Three valued logic. The boolean type for SQL should support 3 values - TRUE
, FALSE
and UNKNOWN
(and also, the non-value NULL
). So bit
isn't actually a good match here.
Given that SQL Server has no support for the data type, we should not expect to be able to write literals of that "type".
Here's another solution using a package solely dedicated to working with dates and times in R:
library(tidyverse)
library(lubridate)
(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#> ID Date
#> <int> <chr>
#> 1 1 2004-02-06
#> 2 2 2006-03-14
#> 3 3 2007-07-16
df %>%
mutate(
Date = ymd(Date),
Month_Yr = format_ISO8601(Date, precision = "ym")
)
#> # A tibble: 3 x 3
#> ID Date Month_Yr
#> <int> <date> <chr>
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
Created on 2020-09-01 by the reprex package (v0.3.0)
Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
Passing parameters with history push:
import { useHistory } from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: { detail: 'some_value' }
});
};
};
export default FirstPage;
Accessing the passed parameter using useLocation from 'react-router-dom':
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
As far as i know it wouldn't be possible to change the spark.executor.memory
at run time. If you are running a stand-alone version, with pyspark and graphframes, you can launch the pyspark REPL
by executing the following command:
pyspark --driver-memory 2g --executor-memory 6g --packages graphframes:graphframes:0.7.0-spark2.4-s_2.11
Be sure to change the SPARK_VERSION
environment variable appropriately regarding the latest released version of Spark
If you are on a remote branch(called feature-branch
) cloned from a Golden Repository(golden_repo_name
), then here's the technique to squash your commits into one:
Checkout the golden repo
git checkout golden_repo_name
Create a new branch from it(golden repo) as follows
git checkout -b dev-branch
Squash merge with your local branch that you have already
git merge --squash feature-branch
Commit your changes (this will be the only commit that goes in dev-branch)
git commit -m "My feature complete"
Push the branch to your local repository
git push origin dev-branch
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
Top answers don't point to an even simpler and more flexible solution.
just place a
@TestPropertySource(properties=
{"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.example.FooAutoConfiguration"})
@SpringBootTest
public class MySpringTest {...}
annotation above your test class. This means other tests aren't affected by the current test's special case. If there is a configuration affecting most of your tests, then consider using the spring profile instead as the current top answer suggests.
Thanks to @skirsch for encouraging me to upgrade this from a comment to an answer.
Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'
...and I can’t believe no one’s posted one for Windows 10 yet:
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'
If you know the exact size of the view, just use setLayoutParams()
:
graphView.setLayoutParams(new LayoutParams(width, height));
Or in Kotlin:
graphView.layoutParams = LayoutParams(width, height)
However, if you need a more flexible approach you can override onMeasure()
to measure the view more precisely depending on the space available and layout constraints (wrap_content
, match_parent
, or a fixed size). You can find more details about onMeasure()
in the android docs.
There is no difference between the two, one is just a shorthand for the second.
The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
Source: official documentation.
In my case, my application's default page was index.html which was missing from the default document options. Adding it fixed the 403.14 Forbidden error.
function Animal(type) {
if (type == "cat") {
this.__proto__ = Cat.prototype;
} else if (type == "dog") {
this.__proto__ = Dog.prototype;
} else if (type == "fish") {
this.__proto__ = Fish.prototype;
}
}
Animal.prototype.say = function() {
alert("This animal can't speak!");
}
function Cat() {
// init cat
}
Cat.prototype = new Animal();
Cat.prototype.say = function() {
alert("Meow!");
}
function Dog() {
// init dog
}
Dog.prototype = new Animal();
Dog.prototype.say = function() {
alert("Bark!");
}
function Fish() {
// init fish
}
Fish.prototype = new Animal();
var newAnimal = new Animal("dog");
newAnimal.say();
This isn't guaranteed to work as __proto__
isn't a standard variable, but it works at least in Firefox and Safari.
If you don't understand how it works, read about the prototype chain.
Being a fan of the Joda Time library, here's how you can do it that way using a Joda DateTime
:
import org.joda.time.format.*;
import org.joda.time.*;
...
String dateString = "2009-04-17 10:41:33";
// parse the string
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatter.parseDateTime(dateString);
// add two hours
dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants
System.out.println(dateTime);
If you still need to use java.util.Date
objects before/after this conversion, the Joda DateTime
API provides some easy toDate()
and toCalendar()
methods for easy translation.
The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.
MySQL has started deprecating SQL_CALC_FOUND_ROWS
functionality with version 8.0.17 onwards.
So, it is always preferred to consider executing your query with LIMIT
, and then a second query with COUNT(*)
and without LIMIT
to determine whether there are additional rows.
From docs:
The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated as of MySQL 8.0.17 and will be removed in a future MySQL version.
COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS causes some optimizations to be disabled.
Use these queries instead:
SELECT * FROM tbl_name WHERE id > 100 LIMIT 10; SELECT COUNT(*) WHERE id > 100;
Also, SQL_CALC_FOUND_ROWS
has been observed to having more issues generally, as explained in the MySQL WL# 12615 :
SQL_CALC_FOUND_ROWS has a number of problems. First of all, it's slow. Frequently, it would be cheaper to run the query with LIMIT and then a separate SELECT COUNT() for the same query, since COUNT() can make use of optimizations that can't be done when searching for the entire result set (e.g. filesort can be skipped for COUNT(*), whereas with CALC_FOUND_ROWS, we must disable some filesort optimizations to guarantee the right result)
More importantly, it has very unclear semantics in a number of situations. In particular, when a query has multiple query blocks (e.g. with UNION), there's simply no way to calculate the number of “would-have-been” rows at the same time as producing a valid query. As the iterator executor is progressing towards these kinds of queries, it is genuinely difficult to try to retain the same semantics. Furthermore, if there are multiple LIMITs in the query (e.g. for derived tables), it's not necessarily clear to which of them SQL_CALC_FOUND_ROWS should refer to. Thus, such nontrivial queries will necessarily get different semantics in the iterator executor compared to what they had before.
Finally, most of the use cases where SQL_CALC_FOUND_ROWS would seem useful should simply be solved by other mechanisms than LIMIT/OFFSET. E.g., a phone book should be paginated by letter (both in terms of UX and in terms of index use), not by record number. Discussions are increasingly infinite-scroll ordered by date (again allowing index use), not by paginated by post number. And so on.
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
If the datepicker is in a row of a grid, try something like
editoptions : {
dataInit : function (e) {
$(e).datepicker({
onSelect : function (ev) {
// here your code
}
});
}
}
Old question, but this is what I typically do to make things a bit more readable:
Func<int, string, Tuple<int, string>> tc = Tuple.Create;
var tupleList = new List<Tuple<int, string>>
{
tc( 1, "cow" ),
tc( 5, "chickens" ),
tc( 1, "airplane" )
};
If you don't want your new column to be of type IDENTITY
(auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of type INT NULL
and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.
UPDATE MyTable
SET MyTable.MyNewColumn = AutoTable.AutoNum
FROM
(
SELECT MyPrimaryKey,
ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum
FROM MyTable
) AutoTable
WHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey
This works in SQL Sever 2005 and later, i.e. versions that support ROW_NUMBER()
Hi this is odd way but try it once
XMLDocument.LoadXML(xmlstring)
I try with your code and same XML without adding any XML declaration it works for me
XmlDocument doc = new XmlDocument();
doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
XmlNodeList nodes = doc.GetElementsByTagName("Product");
XmlNode node = null;
foreach (XmlNode n in nodes)
{
Console.WriteLine("HI");
}
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
I know that this is about matplotlib
, but using pandas
and seaborn
can save you a lot of time:
df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()
Use this in your code:
String.valueOf(x);
You can set the System.out print stream via setOut() (and for in
and err
). Can you redirect this to a print stream that records to a string, and then inspect that ? That would appear to be the simplest mechanism.
(I would advocate, at some stage, convert the app to some logging framework - but I suspect you already are aware of this!)
Just wanted to point out that the accepted answer has a couple of limitations (which I discovered when I tried to use it)
It is thus not suitable (without adaptation) for use in a repeated-call setting (eg a ComponentResizedListener
, or a custom/modified LayoutManager
).
The listed code effectively assumes a starting size of 10 pt but refers to the current font size and is thus suitable for calling once (to set the size of the font when the label is created). It would work better in a multi-call environment if it did int newFontSize = (int) (widthRatio * 10);
rather than int newFontSize = (int)(labelFont.getSize() * widthRatio);
Because it uses new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse))
to generate the new font, there is no support for Bolding, Italic or Color etc from the original font in the updated font. It would be more flexible if it made use of labelFont.deriveFont
instead.
The solution does not provide support for HTML label Text. (I know that was probably not ever an intended outcome of the answer code offered, but as I had an HTML-text JLabel
on my JPanel
I formally discovered the limitation. The FontMetrics.stringWidth()
calculates the text length as inclusive of the width of the html tags - ie as simply more text)
I recommend looking at the answer to this SO question where trashgod's answer points to a number of different answers (including this one) to an almost identical question. On that page I will provide an additional answer that speeds up one of the other answers by a factor of 30-100.
Project is not a statement. It is the capability of the select statement. Select statement has three capabilities. They are selection,projection,join. Selection-it retrieves the rows that are satisfied by the given query. Projection-it chooses the columns that are satisfied by the given query. Join-it joins the two or more tables
As others have said, the only correct answer is no, the type has been erased.
If the list has a non-zero number of elements, you could investigate the type of the first element ( using it's getClass method, for instance ). That won't tell you the generic type of the list, but it would be reasonable to assume that the generic type was some superclass of the types in the list.
I wouldn't advocate the approach, but in a bind it might be useful.
JpaRepository
extends PagingAndSortingRepository
which in turn extends CrudRepository
.
Their main functions are:
CrudRepository
mainly provides CRUD functions.PagingAndSortingRepository
provides methods to do pagination and sorting records.JpaRepository
provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.Because of the inheritance mentioned above, JpaRepository
will have all the functions of CrudRepository
and PagingAndSortingRepository
. So if you don't need the repository to have the functions provided by JpaRepository
and PagingAndSortingRepository
, use CrudRepository
.
There are only a few style attributes that can be applied to an <option>
element.
This is because this type of element is an example of a "replaced element". They are OS-dependent and are not part of the HTML/browser. It cannot be styled via CSS.
There are replacement plug-ins/libraries that look like a <select>
but are actually composed of regular HTML elements that CAN be styled.
If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,
git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin
Please remove
.git\index.lock
File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.
git reset --hard HEAD
git reset --hard origin
Hope that helps!!!
In combination with lists, dicts and sets, there are also another interesting python objects, OrderedDicts.
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
OrderedDicts could be useful when you need to preserve the order of the keys, for example working with documents: It's common to need the vector representation of all terms in a document. So using OrderedDicts you can efficiently verify if a term has been read before, add terms, extract terms, and after all the manipulations you can extract the ordered vector representation of them.
@Override
protected void onResume() {
super.onResume();
boolean installed = false;
while (!installed) {
installed = appInstalledOrNot (APPPACKAGE);
if (installed) {
Toast.makeText(this, "App installed", Toast.LENGTH_SHORT).show ();
}
}
}
private boolean appInstalledOrNot (String uri) {
PackageManager pm = getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>
function openPopUp()
{
$('#divId').css('display','block');
$('#divId').dialog();
}
this works for me, sudo apt-get install libx11-dev
I faced issues in redirecting to a different page in an angular app as well
You can add the $window
as Ewald has suggested in his answer, or if you don't want to add the $window
, just add an timeout and it will work!
setTimeout(function () {
window.location.href = "http://whereeveryouwant.com";
}, 500);
You can use the exit keyword. Here is an example from one of my batch files:
start myProgram.exe param1
exit
You should really go with the array of alerts suggestions, but otherwise adding to the object you mentioned would look like this:
alerts[3]={"app":"goodbyeworld","message":"cya"};
But since you shouldn't use literal numbers as names quote everything and go with
alerts['3']={"app":"goodbyeworld","message":"cya"};
or you can make it an array of objects.
Accessing it looks like
alerts['1'].app
=> "helloworld"
Do this:
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
Context initialContext = new InitialContext(props);
Also add this to the libraries of the project:
C:\installs\glassfish\glassfish-4.1\glassfish\lib\gf-client.jar
adjust path accordingly
I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.
This should give you a hint what goes wrong.
If you use
$( document ).ready({ })
or
$(function() { });
more than once, the click function will trigger as many times as it is used.
Well I struggled with this issue for a couple of weeks.
The easiest, most compliant and non hacky way to do this is to probably use a provider JavaScript API which does not make browser based calls and can handle Cross Origin requests.
E.g. Facebook JavaScript API and Google JS API.
In case your API provider is not current and does not support Cross Origin Resource Origin '*' header in its response and does not have a JS api (Yes I am talking about you Yahoo ),you are struck with one of three options-
Using jsonp in your requests which adds a callback function to your URL where you can handle your response. Caveat this will change the request URL so your API server must be equipped to handle the ?callback= at the end of the URL.
Send the request to your API server which is controller by you and is either in the same domain as the client or has Cross Origin Resource Sharing enabled from where you can proxy the request to the 3rd party API server.
Probably most useful in cases where you are making OAuth requests and need to handle user interaction Haha! window.open('url',"newwindowname",'_blank', 'toolbar=0,location=0,menubar=0')
I hope you got your answer regarding which is default constructor. But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object.
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Please refer below link for more details.
All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak
, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak
) and the table that you are writing to (dbo.foo
) have the exact same column names.
This is what worked for me using a hybrid of a bunch of different answers:
USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
([rown0]
,[row1]
,[row2]
,[row3]
,...
,[rown])
SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO
This version of my answer is helpful if you have primary and foreign keys.
Just Try to do like this....
SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();
// Add this code
if(userCache != null)
{
userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
userListComboBox.DisplayMember = "Key";
userListComboBox.ValueMember = "Value";
}
In plt.colorbar(z1_plot,cax=ax1)
, use ax=
instead of cax=
, i.e. plt.colorbar(z1_plot,ax=ax1)
Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:
obj.__dict__.update(your_dict)
obj.save()
Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.
ConcurrentLinkedQueue means no locks are taken (i.e. no synchronized(this) or Lock.lock calls). It will use a CAS - Compare and Swap operation during modifications to see if the head/tail node is still the same as when it started. If so, the operation succeeds. If the head/tail node is different, it will spin around and try again.
LinkedBlockingQueue will take a lock before any modification. So your offer calls would block until they get the lock. You can use the offer overload that takes a TimeUnit to say you are only willing to wait X amount of time before abandoning the add (usually good for message type queues where the message is stale after X number of milliseconds).
Fairness means that the Lock implementation will keep the threads ordered. Meaning if Thread A enters and then Thread B enters, Thread A will get the lock first. With no fairness, it is undefined really what happens. It will most likely be the next thread that gets scheduled.
As for which one to use, it depends. I tend to use ConcurrentLinkedQueue because the time it takes my producers to get work to put onto the queue is diverse. I don't have a lot of producers producing at the exact same moment. But the consumer side is more complicated because poll won't go into a nice sleep state. You have to handle that yourself.
Something like this would work for reading:
String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try
{
input = new BufferedReader(new FileReader(filename));
String line = null;
while (( line = input.readLine()) != null)
{
String[] data = line.split(",");
csvData.add(Arrays.toList(data));
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if(input != null)
{
input.close();
}
}
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
EDITED MARCH 2019 now with programmatic pin color,
PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS
no longer relies on deprecated Charts API
var pinColor = "#FFFFFF";
var pinLabel = "A";
// Pick your pin (hole or no hole)
var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
var labelOriginHole = new google.maps.Point(12,15);
var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
var labelOriginFilled = new google.maps.Point(12,9);
var markerImage = { // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
path: pinSVGFilled,
anchor: new google.maps.Point(12,17),
fillOpacity: 1,
fillColor: pinColor,
strokeWeight: 2,
strokeColor: "white",
scale: 2,
labelOrigin: labelOriginFilled
};
var label = {
text: pinLabel,
color: "white",
fontSize: "12px",
}; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
this.marker = new google.maps.Marker({
map: map.MapObject,
//OPTIONAL: label: label,
position: this.geographicCoordinates,
icon: markerImage,
//OPTIONAL: animation: google.maps.Animation.DROP,
});
IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])
Edit: Note that join wants an iterable (e.g. a list) as its single argument.