If you are using TortoiseSVN client then you can follow the below steps
Right-click in the source directory and then click on SVN Relocate
After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
set the wrapper to height 100%
.vwrapper {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 100%;
}
and set the 3rd row to flex-grow
#row3 {
background-color: green;
flex: 1 1 auto;
display: flex;
}
This is how I would do it.
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54',
'0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>
Use sort() method to sort the list as below:
List list = new ArrayList();
//add elements to the list
Comparator comparator = new SomeComparator();
Collections.sort(list, comparator);
For reference see the link: http://tutorials.jenkov.com/java-collections/sorting.html
Not the most readable solution, but you can mix the result from a value-of with plain text:
<a>
<xsl:attribute name="href">
Text<xsl:value-of select="/*/properties/property[@name='report']/@value"/>Text
</xsl:attribute>
</a>
Just style a normal button however you want, using your favorite CSS.
Then call a simple JS function to create and link a hidden input element to your styled button. Don't add browser-specific CSS to do the hiding part.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
button {
width : 160px;
height : 30px;
font-size : 13px;
border : none;
text-align : center;
background-color : #444;
color : #6f0;
}
button:active {
background-color : #779;
}
</style>
<button id="upload">Styled upload button!</button>
<script>
function Upload_On_Click(id, handler) {
var hidden_input = null;
document.getElementById(id).onclick = function() {hidden_input.click();}
function setup_hidden_input() {
hidden_input && hidden_input.parentNode.removeChild(hidden_input);
hidden_input = document.createElement("input");
hidden_input.setAttribute("type", "file");
hidden_input.style.visibility = "hidden";
document.querySelector("body").appendChild(hidden_input);
hidden_input.onchange = function() {
handler(hidden_input.files[0]);
setup_hidden_input();
};
}
setup_hidden_input();
}
Upload_On_Click("upload", function(file) {
console.log("GOT FILE: " + file.name);
});
</script>
Notice how the above code re-links it after every time the user chooses a file. This is important because "onchange" is only called if the user changes the filename. But you probably want to get the file every time the user provides it.
For more details, research DropZone and gmail uploads.
Here is just another option you couold apply for ASP NET MVC.
Normally you shoud use BaseController
class for each Controller
class.
So inside of it's constructor method do following.
public class BaseController : Controller
{
public BaseController()
{
// get the previous url and store it with view model
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
}
}
And now in ANY view you can do like
<button class="btn btn-success mr-auto" onclick=" window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>
Enjoy!
These are equivalent.
#pragma omp parallel
spawns a group of threads, while #pragma omp for
divides loop iterations between the spawned threads. You can do both things at once with the fused #pragma omp parallel for
directive.
To over load a function simply do pass parameter as null by default,
class ParentClass
{
function mymethod($arg1 = null, $arg2 = null, $arg3 = null)
{
if( $arg1 == null && $arg2 == null && $arg3 == null ){
return 'function has got zero parameters <br />';
}
else
{
$str = '';
if( $arg1 != null )
$str .= "arg1 = ".$arg1." <br />";
if( $arg2 != null )
$str .= "arg2 = ".$arg2." <br />";
if( $arg3 != null )
$str .= "arg3 = ".$arg3." <br />";
return $str;
}
}
}
// and call it in order given below ...
$obj = new ParentClass;
echo '<br />$obj->mymethod()<br />';
echo $obj->mymethod();
echo '<br />$obj->mymethod(null,"test") <br />';
echo $obj->mymethod(null,'test');
echo '<br /> $obj->mymethod("test","test","test")<br />';
echo $obj->mymethod('test','test','test');
Within Jquery.UI, just update the _checkOffset function, so that viewHeight is added to offset.top, before offset is returned.
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : ($(document).scrollTop()||document.body.scrollTop));
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? ($(document).scrollTop()||document.body.scrollTop) : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
**offset.top = offset.top + viewHeight;**
return offset;
},
Okay, I'm writing this answer by extending wmky's answer above & also, assuming that you've configured mysql for your metastore instead of derby.
select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='<table_name>');
The above query gives you all possible values of the partition columns.
Example:
hive> desc clicks_fact;
OK
time timestamp
..
day date
file_date varchar(8)
# Partition Information
# col_name data_type comment
day date
file_date varchar(8)
Time taken: 1.075 seconds, Fetched: 28 row(s)
I'm going to fetch the values of partition columns.
mysql> select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='clicks_fact');
+-----------------------------------+
| PART_NAME |
+-----------------------------------+
| day=2016-08-16/file_date=20160816 |
| day=2016-08-17/file_date=20160816 |
....
....
| day=2017-09-09/file_date=20170909 |
| day=2017-09-08/file_date=20170909 |
| day=2017-09-09/file_date=20170910 |
| day=2017-09-10/file_date=20170910 |
+-----------------------------------+
1216 rows in set (0.00 sec)
Returns all partition columns.
Note: JOIN
table DBS
ON DB_ID
when there is a DB involved (i.e, when, multiple DB's have same table_name)
In file /etc/ssh/sshd_config
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no
Uncomment the second line, and, if needed, change yes to no.
Then run
service ssh restart
$(document).ready(function () {_x000D_
var form = $('#login_form')[0];_x000D_
form.onsubmit = function(e){_x000D_
var data = $("#login_form :input").serializeArray();_x000D_
console.log(data);_x000D_
$.ajax({_x000D_
url: "the url to post",_x000D_
data: data,_x000D_
processData: false,_x000D_
contentType: false,_x000D_
type: 'POST',_x000D_
success: function(data){_x000D_
alert(data);_x000D_
},_x000D_
error: function(xhrRequest, status, error) {_x000D_
alert(JSON.stringify(xhrRequest));_x000D_
}_x000D_
});_x000D_
return false;_x000D_
}_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
<label>Username:</label>_x000D_
<input type="text" name="username" id="username"/>_x000D_
<label>Password:</label>_x000D_
<input type="password" name="password" id="password"/>_x000D_
<input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
This will achieve what you're asking about:
INSERT INTO table1 (ID, Name)
VALUES (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally');
For future developers, you can also insert from another table:
INSERT INTO table1 (ID, Name)
SELECT
ID,
Name
FROM table2
Or even from multiple tables:
INSERT INTO table1 (column2, column3)
SELECT
t2.column,
t3.column
FROM table2 t2
INNER JOIN table3 t3
ON t2.ID = t3.ID
I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.
//database initialization. Uncomment to clear the database
//deleteDatabase("questions.db");
Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
If you're using Linux, you can also follow this official wiki pages:
Basically:
Now, the following command will add the certificate (where YOUR_FILE is your exported file):
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n YOUR_FILE -i YOUR_FILE
To list all your certificates, run the following command:
certutil -d sql:$HOME/.pki/nssdb -L
If it still doesn't work, you could be affected by this bug: Issue 55050: Ubuntu SSL error 8179
P.S. Please also make sure that you have libnss3-tools
, before you can use above commands.
If you don't have, please install it by:
sudo apt-get install libnss3-tools # on Ubuntu
sudo yum install nss-tools # on Fedora, Red Hat, etc.
As a bonus, you can use the following handy scripts:
$ cat add_cert.sh
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n $1 -i $1
$ cat list_cert.sh
certutil -d sql:$HOME/.pki/nssdb -L # add '-h all' to see all built-in certs
$ cat download_cert.sh
echo QUIT | openssl s_client -connect $1:443 | sed -ne '/BEGIN CERT/,/END CERT/p'
Usage:
add_cert.sh [FILE]
list_cert.sh
download_cert.sh [DOMAIN]
Run Chrome with --auto-ssl-client-auth
parameter
google-chrome --auto-ssl-client-auth
So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713
.
Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:
Check for errors first. (ln 1669)
Not an error. Is it a result set? (ln 1680)
Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:
- a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
- a zero indicating no rows affected, or the statement was DDL, or
- a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)
Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)
(Emphasis mine)
So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1
. :)
I'm not familiar with paramiko, but this may work:
ssh_stdin.write('input value')
ssh_stdin.flush()
For information on stdin:
http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin
I do this in node.js (on Windows 10) by opening 2 separate cmd instances and running each program in each instance.
This has the advantage that writing to the console is easily visible for each script.
I see that in python can do the same: 2 shells.
You can run multiple instances of IDLE/Python shell at the same time. So open IDLE and run the server code and then open up IDLE again, which will start a separate instance and then run your client code.
If you still can not find anything wrong with your setup, you can try Project -> Clean and clean all the projects in the workspace.
EDIT: Sorry, did not see the suggestion of verbose_mode ... same thing
The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t
is a Tensor
object, t.eval()
is shorthand for sess.run(t)
(where sess
is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)
c = tf.constant(5.0)
with tf.Session():
print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with
block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run()
.
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
There are a lot of solutions out there. Here is a link to the apache wiki which deals with this issue directly.
http://wiki.apache.org/httpd/RewriteHTTPToHTTPS
RewriteEngine On
# This will enable the Rewrite capabilities
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e. http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context
Have a look on code below. Tested and found working on Mobile and Tablet devices.
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
As noted by StingyJack and mcbala, and in reference to comments made by Mike L, my experience is that on a Windows 2000 machine, when uninstalling / reinstalling .Net services, "installutil /u" does require a reboot, even when the service was previously stopped. "sc /delete", on the other hand, does not require a reboot - it deletes the service right away (as long as it is stopped).
I have often wondered, actually, whether there is a good reason "installutil /u" requires a reboot... Is "sc /delete" actually doing something wrong / leaving something hanging?
The fundamental issue here is that any machine written in HTML+CSS cannot evaluate infinitely many steps (i.e there can be no "real" recursion) unless the code is infinitely long. And the question will this machine reach configuration H
in n
steps or less is always answerable if n
is finite.
Your model properties don't have to be 'auto properties' Even though that is easier. And the DefaultValue attribute is really only informative metadata The answer accepted here is one alternative to the constructor approach.
public class Track
{
private const int DEFAULT_LENGTH = 400;
private int _length = DEFAULT_LENGTH;
[DefaultValue(DEFAULT_LENGTH)]
public int LengthInMeters {
get { return _length; }
set { _length = value; }
}
}
vs.
public class Track
{
public Track()
{
LengthInMeters = 400;
}
public int LengthInMeters { get; set; }
}
This will only work for applications creating and consuming data using this specific class. Usually this isn't a problem if data access code is centralized. To update the value across all applications you need to configure the datasource to set a default value. Devi's answer shows how it can be done using migrations, sql, or whatever language your data source speaks.
Parallel programming happens when code is being executed at the same time and each execution is independent of the other. Therefore, there is usually not a preoccupation about shared variables and such because that won't likely happen.
However, concurrent programming consists on code being executed by different processes/threads that share variables and such, therefore on concurrent programming we must establish some sort of rule to decide which process/thread executes first, we want this so that we can be sure there will be consistency and that we can know with certainty what will happen. If there is no control and all threads compute at the same time and store things on the same variables, how would we know what to expect in the end? Maybe a thread is faster than the other, maybe one of the threads even stopped in the middle of its execution and another continued a different computation with a corrupted (not yet fully computed) variable, the possibilities are endless. It's in these situations that we usually use concurrent programming instead of parallel.
how about like this
function isint(str){
if(str.match(/\d/g).length==str.length){
return true;
}
else {
return false
}
}
For reference: I had this error when trying to do an unattended VS 2013 install in a windowsservercore
docker container:
.\vs_professional.exe /Q
reason turned out to be having the installation files on a docker volume, copying to the disk of the container solved it.
You have to load jdbc driver
. Consider below Code.
try {
Class.forName("com.mysql.jdbc.Driver");
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/aavikme";
String user = "root";
String password = "aa";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/aavikme";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "aa");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
def palindrome(n):
d = []
while (n > 0):
d.append(n % 10)
n //= 10
for i in range(len(d)/2):
if (d[i] != d[-(i+1)]):
return "Fail."
return "Pass."
Check out commons math from apache. There is quite a lot there.
Consider using matplotlib.cbook pieces
for example:
import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
On your Terminal:
Type cd ~/
to go to your home folder.
Type touch .bash_profile
to create your new file.
open -e .bash_profile
to open it in TextEdit).. .bash_profile
to reload .bash_profile and update any
functions you add.Seems you forgot the ''
of your string.
In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)
In [44]: df
Out[44]:
a b c Value
0 -1.674308 foo 0.343801 0.044698
1 -2.163236 bar -2.046438 -0.116798
2 -0.199115 foo -0.458050 -0.199115
3 0.918646 bar -0.007185 -0.001006
4 1.336830 foo 0.534292 0.268245
5 0.976844 bar -0.773630 -0.570417
BTW, in my opinion, following way is more elegant:
In [53]: def my_test2(row):
....: return row['a'] % row['c']
....:
In [54]: df['Value'] = df.apply(my_test2, axis=1)
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
ARIA does not change functionality, it only changes the presented roles/properties to screen reader users. WebAIM’s WAVE toolbar identifies ARIA roles on the page.
import math
import matplotlib.pyplot as plt
import numpy
import pandas as pd
def normal_pdf(x, mu=0, sigma=1):
sqrt_two_pi = math.sqrt(math.pi * 2)
return math.exp(-(x - mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma)
df = pd.DataFrame({'x1': numpy.arange(-10, 10, 0.1), 'y1': map(normal_pdf, numpy.arange(-10, 10, 0.1))})
plt.plot('x1', 'y1', data=df, marker='o', markerfacecolor='blue', markersize=5, color='skyblue', linewidth=1)
plt.show()
var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
List of codepages : http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
I got the answer.
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
When you use GROUP BY
, the resulting rows will be usually less then incoming rows.
But, when you use PARTITION BY
, the resulting row count should be the same as incoming.
I have updated macOS to 10.13.4 and it works.
It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga
faulthandler.enable()
// bad code goes here
or
$ python3 -q -X faulthandler
>>> /// bad cod goes here
$("#element").removeAttr("class").addClass("yourClass");
To quote the specifications:
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's
__init__.py
module) should also list the modules and subpackages exported by the package.The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its
__init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.
Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).
The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).
Well I couldn't find a Django way, but I did find a python way from inside my model:
def format_price(self):
import locale
locale.setlocale(locale.LC_ALL, '')
return locale.format('%d', self.price, True)
You can add as many classes to an element, but you can add only one id per element.
<div id="unique" class="class1 class2 class3 class4"></div>
You can combine selectors like this
$(".alert-box.warn, .alert-box.dead");
Or if you want a wildcard use the attribute-contains selector
$("[class*='alert-box']");
Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.
$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");
Use:
import color
class Color(color.Color):
...
If this were Python 2.x, you would also want to derive color.Color
from object
, to make it a new-style class:
class Color(object):
...
This is not necessary in Python 3.x.
Your HTML
$html='<ul id="main">
<li>
<h1><a href="[link]">My Title</a></h1>
<span class="date">Date</span>
<div class="section">
[content]
</div>
</li>
</ul>';
//function call you can change the tag name
echo contentBetweenTags($html,"span");
// this function will help you to fetch the data from a specific tag
function contentBetweenTags($content, $tagname){
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $content, $matches);
if(empty($matches))
return;
$str = "<$tagname>".html_entity_decode($matches[1])."</$tagname>";
return $str;
}
This query can do the thing for you.
DECLARE
@search_string VARCHAR(100),
@table_name SYSNAME,
@table_id INT,
@column_name SYSNAME,
@sql_string VARCHAR(2000)
SET @search_string = 'StringtoSearch'
DECLARE tables_cur CURSOR FOR SELECT ss.name +'.'+ so.name [name], object_id FROM sys.objects so INNER JOIN sys.schemas ss ON so.schema_id = ss.schema_id WHERE type = 'U'
OPEN tables_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id
AND system_type_id IN (167, 175, 231, 239, 99)
OPEN columns_cur
FETCH NEXT FROM columns_cur INTO @column_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + ']
LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''
EXECUTE(@sql_string)
FETCH NEXT FROM columns_cur INTO @column_name
END
CLOSE columns_cur
DEALLOCATE columns_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END
CLOSE tables_cur
DEALLOCATE tables_cur
In Swift:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryRepresentation().keys.forEach { defaults.removeObjectForKey($0) }
This may give a hit for some, but I got the error as well and realized that I just misspelled the user model on importing.
wrong: const User = require('./UserModel');
correct: const User = require('./userModel');
Unbelievable but consider it.
You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.
WITH PercentageOfTotal (Id, Percentage)
AS
(
SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT
CASE
WHEN o.TotalType = 'Average' THEN r.avgscore
WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
ELSE o.cnt
END AS [displayscore]
FROM PercentageOfTotal pt
JOIN dbo.MyTable t ON pt.Id = t.Id
You can do it by following 3 steps:
- svn rm old_file_name
- svn add new_file_name
- svn commit
subprocess.check_output(...)
calls the process, raises if its error code is nonzero, and otherwise returns its stdout. It's just a quick shorthand so you don't have to worry about PIPE
s and things.
Uncheck "Power Save Mode" in "File" tab
system()
executes a shell which is then responsible for parsing the arguments and executing the desired program. To execute the program directly, use fork() and exec() (which is what system() uses to execute the shell as well as what the shell itself uses to execute commands).
#include <unistd.h>
int main() {
if (fork() == 0) {
/*
* fork() returns 0 to the child process
* and the child's PID to the parent.
*/
execl("/path/to/foo", "foo", "arg1", "arg2", "arg3", 0);
/*
* We woundn't still be here if execl() was successful,
* so a non-zero exit value is appropriate.
*/
return 1;
}
return 0;
}
you can try:
shift + right click
then, click on Open command prompt here
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
to chnage line endings from LF to CRLF:
open Sublime and follow the steps:-
1 press Ctrl+shift+p then install package name line unify endings
then again press Ctrl+shift+p
2 in the blank input box type "Line unify ending "
3 Hit enter twice
Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF
File file = ...
byte[] data = ...
try{
FileOutputStream fos = FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
}catch(Exception e){
}
but if the bytes array length is more than 1024 you should use loop to write the data.
Try to add type of configuration in dependency line. For example:
implementation project(path: ':some_module', **configuration: 'default'**)`
Try
isSubstring = first in theOther
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
there seems to be incorrect info posted here. some people report on how to clear the Android builder cache (with task cleanBuildCache
) but do not seem to realize that said cache is independent of Gradle's build cache, AFAIK.
my understanding is that Android's cache predates (and inspired) Gradle's, but i could be wrong. whether the Android builder will be/was updated to use Gradle's cache and retire its own, i do not know.
EDIT: the Android builder cache is obsolete and has been eliminated. the Android Gradle plugin now uses Gradle's build cache instead. to control this cache you must now interact with Gradle's generic cache infrastructure.
TIP: search for Gradle's cache help online without mentioning the keyword 'android' to get help for the currently relevant cache.
EDIT 2: due to tir38's question in a comment below, i am testing using an Android Gradle plugin v3.4.2 project. the gradle cache is enabled by org.gradle.caching=true
in gradle.properties
. i do a couple of clean build
and the second time most tasks show FROM-CACHE
as their status, showing that the cache is working.
surprisingly, i have a cleanBuildCache
gradle task and a <user-home>/.android/build-cache/3.4.2/
directory, both hinting the existence of an Android builder cache.
i execute cleanBuildCache
and the 3.4.2/
directory is gone. next i do another clean build
:
FROM-CACHE
as their status and the build completed at cache-enabled speeds.3.4.2/
directory is recreated.3.4.2/
directory is empty (save for 2 hidden, zero length marker files).conclusions:
cleanBuildCache
does not clear or affect the build cache in any way.next, i disable the Gradle cache by removing org.gradle.caching=true
from gradle.properties
and i try a couple of clean build
:
3.4.2/
directory continues to be empty.more conclusions:
EDIT 3: user tir38 confirmed that the Android builder cache is obsolete and has been eliminated with this find. tir38 also created this issue. thanks!
Go to Menu Server and Click on Data Export. There you can select the table and select the option Dump Structure and Data' from the drop-down.
The explode() function breaks a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
You can 'json_encode' to first encode your post variables via PHP. Then create a JS object (array) from the JSON encoded post variables. Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
I have to find distinct rows with the following details
class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries
public DbSet<SCountry> country { get; set; }
public List<SCountry> DoDistinct()
{
var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
return Countries;
}
The server's address is stored in config.php
Another method without WHERE, try this..
Will select both Empty and NULL values
SELECT ISNULL(NULLIF(fieldname,'')) FROM tablename
make clean
deletes all the already compiled object files.
With large arrays, print_r can show far more information than is useful. You can truncate it like this, showing the first 2000 characters or however many you need.
echo "<pre>" . substr(print_r($dataset, 1), 0, 2000) . "</pre>";
The Installed Packages Directory You will find this directory in the data directory. It contains a copy of every sublime-package installed. Used to restore Packages
So, you shouldn't put any plugin to this folder. For getting works of SidebarEnhancements plugin try to disable and reenable this plugin with using Package Control. If it doesn't work then try to remove folder "SidebarEnhancements" from "Packages" folder and install it again via Package Control.
string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
Some fixes to this util script
SET @DATABASE_NAME = 'Integradb';
SELECT CONCAT('ALTER TABLE ', table_schema, '.', table_name, ' ENGINE=InnoDB;') AS sql_statements
FROM information_schema.tables AS tb
WHERE table_schema = @DATABASE_NAME
AND `ENGINE` = 'MyISAM'
AND `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;
Run your script with .
. myscript.sh
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you say
FOO=1
export BAR=2
./runScript.sh
then $BAR
will be available in the environment of runScript.sh
, but $FOO
will not.
They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).
The main equations are:
frame.origin = center - bounds.size / 2
(which is the same as)
center = frame.origin + bounds.size / 2
(and there’s also)
frame.size = bounds.size
That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.
This stuff is all explained in more detail with a useful mini-library here:
Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant
directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME
to this directory, then pre-pend to the System PATH
variable, %ANT_HOME%\bin
. This way, you don't have to put in the whole directory name.
Assuming you did the above, try this:
C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build
This will do several things:
build.xml
in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.The -d
will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999
, and run cls
first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.
Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build
target. Here it is:
<target depends="build-subprojects,build-project" name="build"/>
The build
target does nothing itself. However, it depends upon two other targets, so these will be called first:
The first target is build-subprojects
:
<target name="build-subprojects"/>
This does nothing at all. It doesn't even have a dependency.
The next target specified is build-project
does have code:
<target depends="init" name="build-project">
This target does contain tasks, and some dependent targets. Before build-project
executes, it will first run the init
target:
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
This target creates a directory called bin
, then copies all files under the src
tree with the suffix *.java
over to the bin
directory. The includeemptydirs
mean that directories without non-java code will not be created.
Ant uses a scheme to do minimal work. For example, if the bin
directory is created, the <mkdir/>
task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src
directory tree, the <copy/>
task won't run. However, the init
target will still be executed.
Next, we go back to our previous build-project
target:
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="iControlSilk4J.classpath"/>
</javac>
</target>
Look at this line:
<echo message="${ant.project.name}: ${ant.file}"/>
That should have always executed. Did your output print:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
Maybe you didn't realize that was from your build.
After that, it runs the <javac/>
task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java
files have previously been compiled, the <javac/>
task won't execute.
And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean
task, and then build
:
C:\Silk4J\Automation\iControlSilk4J> ant -d clean build
However, Ant usually prints the target being executed. You should have seen this:
init:
build-subprojects:
build-projects:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
build:
Build Successful
Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.
bin
directory already exists, <mkdir/>
isn't going to execute.src
, or they have already been copied into bin
, the <copy/>
task won't execute.src
directory, or they have already been compiled, the <java/>
task won't run.If you look at the output from the -d
debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.
See if that helps.
I wanted to use the credential manager for normal use, but I have scripts where I obviously do not want any prompts whatsoever from git.exe
. This is how I invoke Git from my scripts:
set GIT_TERMINAL_PROMPT=0
git -c core.askpass= -c credential.helper= <command> ...
This way, the script always sees the "correct" no-prompt setting without having to adapt any configuration.
(Git for Windows 2.13.3)
A variation I found that might also come in handy is to set:
set GCM_INTERACTIVE=never
# Or: git config --global credential.interactive never
set GIT_TERMINAL_PROMPT=0
git.exe -c core.askpass= -c credential.helper=manager <command> ...
But note that git.exe -c credential.interactive=never <command> ...
does not work (it seems that the -c
thing isn't routed through to Git Credential Manager for Windows or whatever).
That way, you can use the GCMfW, but it will never prompt you; it will just lookup the credentials, which can be very helpful in non-interactive environs.
This is a slightly different answer, depending on what you have. If you have a list of files and need to get the name of the last directory that the file is in you can do this:
string path = "/attachments/1828_clientid/2938_parentid/somefiles.docx";
string result = new DirectoryInfo(path).Parent.Name;
This will return "2938_parentid"
If you want to use $.getJSON()
you can add the following before the call :
$.ajaxSetup({
scriptCharset: "utf-8",
contentType: "application/json; charset=utf-8"
});
You can use the charset you want instead of utf-8
.
The options are explained here.
contentType :
When sending data to the server, use this content-type
. Default is application/x-www-form-urlencoded
, which is fine for most cases.
scriptCharset :
Only for requests with jsonp
or script
dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.
You may need one or both ...
EDIT: (As per the comments in question:)
I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.
You can use LinkedList. It has methods peek, poll and offer.
If apache requires authentication (via .htaccess
), and you hit Cancel
, it will respond with a 401 Authorization Required
If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden
Meaning 1: Need to authenticate
The request requires user authentication. ...
Meaning 2: Authentication insufficient
... If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. ...
Meaning: Unrelated to authentication
... Authorization will not help ...
More details:
The server understood the request, but is refusing to fulfill it.
It SHOULD describe the reason for the refusal in the entity
The status code 404 (Not Found) can be used instead
(If the server wants to keep this information from client)
When your view loads, so does its associated controller. Instead of using ng-init
, simply call your init()
method in your controller:
$scope.init = function () {
if ($routeParams.Id) {
//get an existing object
} else {
//create a new object
}
$scope.isSaving = false;
}
...
$scope.init();
Since your controller runs before ng-init
, this also solves your second issue.
As John David Five
mentioned, you might not want to attach this to $scope
in order to make this method private.
var init = function () {
// do something
}
...
init();
If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.
var init = function () {
// do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
if( newVal && newVal.length > 0) {
unwatch();
init();
}
});
If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):
ALTER TABLE [Original] SWITCH TO [Original2]
exec sys.sp_rename
to rename the various schema objects back to the original names, and then you can recreate your foreign keys.For example, given:
CREATE TABLE Original
(
Id INT IDENTITY PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);
INSERT INTO Original
SELECT 'abcd'
UNION ALL
SELECT 'defg';
You can do the following:
--create new table with no IDENTITY
CREATE TABLE Original2
(
Id INT PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);
--data before switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
ALTER TABLE Original SWITCH TO Original2;
--data after switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
--clean up
IF NOT EXISTS (SELECT * FROM Original) DROP TABLE Original;
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';
UPDATE Original
SET Id = Id + 1;
SELECT *
FROM Original;
I had trouble with all the answers here because I was working with a HUGE file (~300Gb) and none of the solutions scaled. Here's my solution:
dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )
In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc
) and, set that position to be the end of the file (by dd
ing one byte of /dev/null
onto it).
This is fast because tail
starts reading from the end, and dd
will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.
NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!
Use a BigDecimal. It even lets you specify rounding rules (like ROUND_HALF_EVEN, which will minimize statistical error by rounding to the even neighbor if both are the same distance; i.e. both 1.5 and 2.5 round to 2).
If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);
To follow up the answer above, for a .war
artifact, I found I had to apply the equivalent configuration to maven-war-plugin
, rather than maven-jar-plugin
:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
This added the version information to MANIFEST.MF
in the project's .jar
(included in WEB-INF/lib
of the .war
)
Assuming that the items in your CheckedListBox are strings:
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if ((string)checkedListBox1.Items[i] == value)
{
checkedListBox1.SetItemChecked(i, true);
}
}
Or
int index = checkedListBox1.Items.IndexOf(value);
if (index >= 0)
{
checkedListBox1.SetItemChecked(index, true);
}
In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).
One idea might be to add clases to the body, then use CSS to style the document accordingly.
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.
I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.
Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.
How about:
SELECT * FROM sometable WHERE CHAR_LENGTH(LINK) > 1
Here's the MySql string functions page (5.0).
Note that I chose CHAR_LENGTH
instead of LENGTH
, as if there are multibyte characters in the data you're probably really interested in how many characters there are, not how many bytes of storage they take. So for the above, a row where LINK is a single two-byte character wouldn't be returned - whereas it would when using LENGTH
.
Note that if LINK
is NULL
, the result of CHAR_LENGTH(LINK)
will be NULL
as well, so the row won't match.
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
print( set( first_list + second_list ) )
You should have a look into JSON-P - that was a perfect solution for me when I had that problem:
https://en.wikipedia.org/wiki/JSONP
You basically define a javascript file that loads all your data and another javascript file that processes and displays it. That gets rid of the ugly scrollbar of iframes.
Give a try to return bootstrap alert message, this worked for me
return Content("<div class='alert alert-success'><a class='close' data-dismiss='alert'>
×</a><strong style='width:12px'>Thanks!</strong> updated successfully</div>");
Note: Don't forget to add bootstrap css
and js
in your view page
hope helps someone.
You can try the following:
theAnchorText = "I'm home";
OR
theAnchorText = 'I\'m home';
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
Another possible way of doing this would be to use Sys.time():
start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
Not the most elegant way to do it, compared to the answere above , but definitely a way to do it.
Well you can do it but may catch more exceptions.
So if the your script should runs as another user such as www U should make sure the PATH and other environment is ok.
sudo -u www -i /the/path/of/your/script
Please prefer the sudo manual~ -i [command] The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a loginshell...
Although a bit
late in posting an answer, here is an alternative approach without using margins.
<style>
#divMain { width: 500px; }
#div1 { width: 100px; float: left; background-color: #fcc; }
#div2 { overflow:hidden; background-color: #cfc; }
#div3 { width: 100px; float: right; background-color: #ccf; }
</style>
<div id="divMain">
<div id="div1">
div 1
</div>
<div id="div3">
div 3
</div>
<div id="div2">
div 2<br />bit taller
</div>
</div>
This method works like magic, but here is an explanation :)\
you can use also this way to write css for placeholder
input::placeholder{
text-align: center;
}
First put chart in some variable then history it next time before init
#Check if myChart object exist then distort it
if($scope.myChart) {
$scope.myChart.destroy();
}
$scope.myChart = new Chart(targetCanvas
I got the same error while I forgot to use shell=True
in the subprocess.call
.
subprocess.call('python modify_depth_images.py', shell=True)
To run an external command without interacting with it, such as one would do with
os.system()
, Use thecall()
function.import subprocess Simple command subprocess.call(['ls', '-1'], shell=True)
managed to fix this by copying the below folder from another Visual Studio setup (non-express)
from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc
to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc
Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:
update
MasterTbl
set
TotalX = Sum(DetailTbl.X),
TotalY = Sum(DetailTbl.Y),
TotalZ = Sum(DetailTbl.Z)
from
DetailTbl
where
DetailTbl.MasterID = MasterID
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
Iv'd found 2 solutions to the problem, which its implied that you detect touch with modernizr or something else and set a touch class on the html element.
This is good but not supported very well:
html.touch *:hover {
all:unset!important;
}
But this has a very good support:
html.touch *:hover {
pointer-events: none !important;
}
Works flawless for me, it makes all the hover effects be like when you have a touch on a button it will light up but not end up buggy as the initial hover effect for mouse events.
Detecting touch from no-touch devices i think modernizr has done the best job:
https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
EDIT
I found a better and simpler solution to this issue
Here is the complete solution as a function:
function varDumpToString ($var)
{
ob_start();
var_dump($var);
return ob_get_clean();
}
The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.
For example:
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
I was having a similar problem. (No problems training with GradientDescent optimizer, but error raised when using to Adam Optimizer, or any other optimizer with its own variables)
Changing to an interactive session solved this problem for me.
sess = tf.Session()
into
sess = tf.InteractiveSession()
If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);
I was facing such a problem, look at the picture below
and here is its HTML
<tr class="li1">
<td valign="top">1.</td>
<td colspan="5" valign="top">
<p>How to build e-book learning environment</p>
</td>
</tr>
so I fix it by changing valign Attribute in both td
tags to baseline
and it worked
hope this help you
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
The volatile
keyword is used:
long
and double
. (all other, primitive accesses are already guaranteed to be atomic!)The java.util.concurrent.atomic.*
classes are, according to the java docs:
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
The atomic classes are built around the atomic compareAndSet(...)
function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile
variables do. (with one exception: weakCompareAndSet(...)
).
From the java docs:
When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.
To your question:
Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile
in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).
What is the difference between
AtomicInteger
andvolatile int
?
AtomicInteger
provides atomic operations on an int
with proper synchronization (eg. incrementAndGet()
, getAndAdd(...)
, ...), volatile int
will just ensure the visibility of the int
to other threads.
If you're going to perform transfers on the waveform data then perhaps you should use SciPy, specifically scipy.io.wavfile
.
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works
with summary as (
Select Dbms_Random.Random As Ran_Number,
colmn1,
colm2,
colm3
Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
From table1, table2
Where Table1.Id = Table2.Id
Order By Dbms_Random.Random Asc)
Select tab1.col2,
tab1.col4,
tab1.col5,
From Summary s
Where s.Rank <= 2;
This worked for me:
$this->db->where('RecordDate >=', '2018-08-17 00:00:00');
$this->db->where('RecordDate <=', '2018-10-04 05:32:56');
This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.
No sizeToFit, preferredMaxLayoutWidth used
Below is how it will work.
Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:
Set the Label properties as below image:
Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton
Now set the priority of the trailing constraint of UILabel as 749
Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748
Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]
@IBAction func updateLabelText(sender: UIButton) {
if count > 3 {
count = 0
}
textLabel.text = items[count]
count = count + 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.textLabel.sizeToFit()
//self.textLabel.preferredMaxLayoutWidth = 500
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
W3C did not adopt the
language
attribute, favoring instead atype
attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes"text/javascript"
or"application/ecmascript"
or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write<script>
. It is smallest, and it works on the most browsers.
For entertainment purposes only, I tried out the following five scripts
<script type="application/ecmascript">alert("1");</script>
<script type="text/javascript">alert("2");</script>
<script type="baloney">alert("3");</script>
<script type="">alert("4");</script>
<script >alert("5");</script>
On Chrome, all but script 3 (type="baloney"
) worked. IE8 did not run script 1 (type="application/ecmascript"
) or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type
attribute, but that it you use it you better use a legal (browser dependent) value.
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset
to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
In the old console layout :
In the new cloud console layout :
In case of both procedures, you find your client ID and client secret at the same page. If you're using a different client ID and client secret, replace it with the ones you find here.
During my first experiments today, I've succesfully used the "Key for server apps" as a developer key for connecting with the "contacts", "userinfo" and "analytics" API. I did this using the PHP client.
Wading through the Google API docs certainly is a pain in the @$$... I hope this info will be useful to anyone.
We always forget about ACLs
. See setfacl
.
sudo setfacl -m user:$USER:rw /var/run/docker.sock
Currently (up to version 2.4.4), if any path (dbpath/logpath/config) contains spaces, then the service won't start, and show the error: "The service is not responding to the control function".
This solved my error:
I am on branch : "A"
git stash
Move to master branch:
git checkout master <br>
git pull*
Move back to my branch: "A"
git checkout A <br>
git stash pop*
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
It takes up to 24 hours before its available in each and every (country wise) app store. If you have waited more than that, and still have problems, contact Apple.
I confirm that git and msysgit can coexist on the same computer, as mentioned in "Which GIT version to use cygwin or msysGit or both?".
Git for Windows (msysgit) will run in its own shell (dos with git-cmd.bat
or bash with Git Bash.vbs
)
Update 2016: msysgit is obsolete, and the new Git for Windows now uses msys2
Git on Cygwin, after installing its package, will run in its own cygwin bash shell.
In there, you can do a sudo apt-get install git-core
and start using git on project-sources present either on the WSL container's "native" file-system (see below), or in the hosting Windows's file-system through the /mnt/c/...
, /mnt/d/...
directory hierarchies.
Specifically for the Bash on Windows or WSL (Windows Subsystem for Linux):
DrvFs
emulated file-system may not behave the same as files on the native VolFs
file-system).
- Unfortunately, it cannot invoke back into Windows executables, or
- interact with any native drivers (i.e. so no Graphic card, no USB drives yet).
If you're using getline
after cin >> something
, you need to flush the newline out of the buffer in between.
My personal favourite for this if no characters past the newline are needed is cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore()
. Or make use of std::ws
to remove leading whitespace if desirable:
int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
also,
the global new and delete can be overridden, malloc/free cannot.
further more new and delete can be overridden per type.
You just need to create an offset bypass to how far you want the backwards reading to go. So, we use getcwd()
to get the path and explode (split into array) to fetch the data between $root
and the ending of the path.
function getRoot($root = "public_html") {
return explode($root, getcwd())[0].$root."/";
}
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
=UNIQUE({filter(Core!L8:L27,isblank(Core!L8:L27)=false),query(ArrayFormula(countif(Core!L8:L27,Core!L8:L27)),"select Col1 where Col1 <> 0")})
Core!L8:L27 = list
The currently accepted answer works, but will install an outdated version of Mongo.
The Mongo documentation states that: MongoDB only provides packages for Ubuntu 12.04 LTS (Precise Pangolin) and 14.04 LTS (Trusty Tahr). However, These packages may work with other Ubuntu releases.
So, to get the lastest stable Mongo (3.0
), use this (the different step is the second one):
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list
apt-get update
apt-get install mongodb-org
Hope this helps.
I would like to add that as a previous step, you must check your GNU/Linux Distro Release, which will construct the Repo list url. For me, as I am using this:
DISTRIB_CODENAME=rafaela
DISTRIB_DESCRIPTION="Linux Mint 17.2 Rafaela"
NAME="Ubuntu"
VERSION="14.04.2 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.2 LTS"
The original 2nd step:
"Create a list file for MongoDB": "echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list"
Didn't work as intended because it generated an incorrect Repo url. Basically, it put the distribution codename "rafaela" within the url repo which doesn't exist. You can check the Repo url at your package manager under Software Sources, Additional Repositories.
What I did was to browse the site:
http://repo.mongodb.org/apt/ubuntu/dists/
And I found out that for Ubuntu, "trusty" and "precise" are the only web folders available, not "rafaela".
Solution: Open as root the file 'mongodb-org-3.1.list' or 'mongodb.list' and replace "rafaela" or your release version for the corresponding version (for me it was: "trusty"), save the changes and continue with next steps. Also, your package manager can let you change easily the repo url as well.
Hope it works for you.! ---
document.location.reload()
stores the position, see in the docs.
Add additional true
parameter to force reload, but without restoring the position.
document.location.reload(true)
MDN docs:
The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.
Here's a one liner answer for this question
List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();
Don't do this yourself, I suggest.
Use a library, e.g. the Gson library from Google.
Try this: It will open the default mail directly.
<a href="mailto:[email protected]"><img src="ICON2.png"></a>
If you want to write unit per meter (m^-1)
, use $m^{-1}$)
, which means -1
inbetween {}
Example:
plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )
This seems to work easily.
Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
Dim MyDoc As New mshtml.HTMLDocument
Dim DocElements As mshtml.IHTMLElementCollection = Nothing
Dim LoginForm As mshtml.HTMLFormElement = Nothing
ASPComplete = 0
WB.Navigate(VitecLoginURI)
BrowserLoop()
MyDoc = WB.Document.DomDocument
DocElements = MyDoc.getElementsByTagName("input")
For Each i As mshtml.IHTMLElement In DocElements
Select Case i.name
Case "seLogin$UserName"
i.value = UserID
Case "seLogin$Password"
i.value = Pass
Case Else
Exit Select
End Select
frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
Next i
'Old Method for Clicking submit
'WB.Document.Forms("form1").InvokeMember("submit")
'Better Method to click submit
LoginForm = MyDoc.forms.item("form1")
LoginForm.item("seLogin$LoginButton").click()
ASPComplete = 0
BrowserLoop()
MyDoc= WB.Document.DomDocument
DocElements = MyDoc.getElementsByTagName("input")
For Each j As mshtml.IHTMLElement In DocElements
frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf
Next j
frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
Return 1
End Function
First of all i will say Nice Thaught to develop such app.
Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.
Well i am not sure about it but still have give some view so you can get idea of it.
All the Best. :))
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
No need to get too complicated. If all you need is ² then use the unicode representation.
http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
(which is how I assume you got the ² to appear in your question. )
To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.
This is the proper way to access data in laravel :
@foreach($data-> ac as $link)
{{$link->url}}
@endforeach
It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
For example:
String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"
Hope it can help ...
Some DBMSs support the FROM (SELECT ...) AS alias_name
syntax.
Think of your two original queries as temporary tables. You can query them like so:
SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008"
FROM (query1) as t1, (query2) as t2
WHERE t1.Activity = t2.Activity
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
Try:
Closing all instances of VS and then deleting the account for the TFS server in Control Panel -> User Accounts-> Credentail manager
The properties that can be set for a figure
is referenced here.
You could then use:
figure_number = 1;
x = 0; % Screen position
y = 0; % Screen position
width = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)
figure(figure_number, 'Position', [x y width height]);
Here is the recent fix for dlib users link
cv::Mat img = ...
IplImage iplImage = cvIplImage(img);
The clearer option is to use tonumber.
As of 5.3.2, this function will automatically detect (signed) integers, float (if a point is present) and hexadecimal (both integers and floats, if the string starts by "0x" or "0X").
The following snippets are shorter but not equivalent :
a + 0 -- forces the conversion into float, due to how + works.
a | 0 -- (| is the bitwise or) forces the conversion into integer.
-- However, unlike `math.tointeger`, it errors if it fails.
.loc
accept row and column selectors simultaneously (as do .ix/.iloc
FYI)
This is done in a single pass as well.
In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
In [2]: df
Out[2]:
a b c d e
0 0.669701 0.780497 0.955690 0.451573 0.232194
1 0.952762 0.585579 0.890801 0.643251 0.556220
2 0.900713 0.790938 0.952628 0.505775 0.582365
3 0.994205 0.330560 0.286694 0.125061 0.575153
In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]:
a d
0 0.669701 0.451573
1 0.952762 0.643251
2 0.900713 0.505775
And if you want the values (though this should pass directly to sklearn as is); frames support the array interface
In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]:
array([[ 0.66970138, 0.45157274],
[ 0.95276167, 0.64325143],
[ 0.90071271, 0.50577509]])
Simple fix for me was
Use this code:
switch($a) {
case 1:
case 2:
.......
.......
.......
break;
}
The block is called for both 1 and 2.
Simplest way is to just drag and drop the image into the drawable folder. The important thing to keep in mind if you are using Android Studio 2.2.x version make sure you are in PROJECT VIEW else it will not allow to drag and drop the image.
If your project budged allows you to have enough RAM memory on your environment - answer is Redis. Especially taking in account new Redis 3.2 with cluster functionality.
I think leverage this functionality using Java
long time= System.currentTimeMillis();
this will return current time in milliseconds mode . this will surely work
long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);
Here is my logcat using the above function
05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157
If you got any doubt with millisecond value .Check Here
EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds
that mentioned in log to match with time in log you might get a different value based your system timezone
EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support
Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).
It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).
But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.
A good example: here
And a good documentation from Mozilla: here
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
Try This
SELECT Title from #Movies
SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies
OR
SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies
If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:
select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;
Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.
For a start, you have them backwards: &
is reference and *
is dereference.
Referencing a variable means accessing the memory address of the variable:
int i = 5;
int * p;
p = &i; //&i returns the memory address of the variable i.
Dereferencing a variable means accessing the variable stored at a memory address:
int i = 5;
int * p;
p = &i;
*p = 7; //*p returns the variable stored at the memory address stored in p, which is i.
//i is now 7
you may try the TO_CHAR function to convert the result
e.g.
SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL
SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL
Hope it helps
You can use dblink to create a view that is resolved in another database. This database may be on another server.
Quoting from the gcc website:
C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
So probably you use a version of g++ which doesn't support -std=c++11
. Try -std=c++0x
instead.
Availability of C++11 features is for versions >= 4.3 only.
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
If you prefer to do this without VBA, you can try the following:
Cell B999 will now contain the concatenated text string you are looking for.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
command.Parameters.AddWithValue("@param1", klantId));
command.Parameters.AddWithValue("@param2", klantNaam));
command.Parameters.AddWithValue("@param3", klantVoornaam));
command.ExecuteNonQuery();
}
}
It might be overkill but your MySQL command history can also be wiped from:
~/.mysql_history
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers
) mandates that identifiers must not start with a digit:
identifier:
identifier-nondigit
identifier identifier-nondigit
identifier digit
identifier-nondigit:
nondigit
universal-character-name
other implementation-defined characters>
nondigit: one of
_ a b c d e f g h i j k l m
n o p q r s t u v w x y z
A B C D E F G H I J K L M
N O P Q R S T U V W X Y Z
digit: one of
0 1 2 3 4 5 6 7 8 9
The correct form for using the pre-processor to block out code is:
#if 0
: : :
#endif
You can also use:
#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif
but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED
or DONOTCOMPILE
which others may also use. To be safe, the #if
option should be preferred.
try this:
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
use JSON.stringify(userData)
to coverty json object to string.
var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));
and for getting back from cookie use JSON.parse()
var data=JSON.parse($.cookie("basket-data"))
Set libraries search path first:
LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)
And then just do
TARGET_LINK_LIBRARIES(GLBall mylib)
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
Maybe try with
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
and see if it will work.
You could create a commit which contains an empty working copy.
This is a generally safe, non-destructive approach because it does not involve the use of any brute-force reset mechanisms. First you hide all managed content with git checkout empty
, then you are free to manually review and remove whatever unmanaged content remains.
## create a stand-alone, tagged, empty commit
true | git mktree | xargs git commit-tree | xargs git tag empty
## clear the working copy
git checkout empty
Your working copy should now be clear of any managed content. All that remains are unmanaged files and the .git
folder itself.
To re-populate your working copy...
git checkout master ## or whatever branch you will be using
If you're a forward thinking individual, you might start your repository off on the right foot by basing everything on an initial empty commit...
git init
git commit --allow-empty --allow-empty-message -m ""
git tag empty
...
There are various uses for a tagged empty worktree. My favorite at the moment is to depopulate the root under a set of git worktree
subfolders.
I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.
private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";
public static Calendar isoToCalendar(final String inputDate) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
Date date = dateFormat.parse(inputDate);
calendar.setTime(date);
} catch (ParseException e) {
Log.e("TAG",e.getMessage());
}
return calendar;
}
REMEMBER: The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.
Here's an example using IterableDiffer with ngDoCheck. IterableDiffer is especially useful if you need to track changes over time as it lets you do things like iterate over only added/changed/removed values etc.
A simple example not using all advantages of IterableDiffer, but it works and shows the principle:
export class FeedbackMessagesComponent implements DoCheck {
@Input()
messages: UserFeedback[] = [];
// Example UserFeedback instance { message = 'Ooops', type = Notice }
@HostBinding('style.display')
display = 'none';
private _iterableDiffer: IterableDiffer<UserFeedback>;
constructor(private _iterableDiffers: IterableDiffers) {
this._iterableDiffer = this._iterableDiffers.find([]).create(null);
}
ngDoCheck(): void {
const changes = this._iterableDiffer.diff(this.messages);
if (changes) {
// Here you can do stuff like changes.forEachRemovedItem()
// We know contents of this.messages was changed so update visibility:
this.display = this.messages.length > 0 ? 'block' : 'none';
}
}
}
This will now automatically show/hide depending on myMessagesArray count:
<app-feedback-messages
[messages]="myMessagesArray"
></app-feedback-messages>
_x000D_
Check my answer here : https://stackoverflow.com/a/50039345/2647919
"OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.
Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.
Open your folder which you want to upload. drag and drop on the listing in browser. See the image here."
Fix ImageView's size with dp
or fill_parent
and set android:scaleType
to fitXY
.
Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.
Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto
link that lets them do that.
// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';
// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);
// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;
// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);
// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';
Note: the above assumes you are outputting to a text/html
document. If your output media type is text/json
then simply use $retval['url'] = $mailToUri;
because output encoding is handled by json_encode()
.
You should see:
"args": {
"token": "w%a&!e#\"^2(^@azW"
},
And of course this is the JSON representation of $token
above.
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input
with input
.