I had the same issue:
raise SSLError(e)
requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
I had fiddler running, I stopped fiddler capture and did not see this error. Could be because of fiddler.
In Axis webservice and if you have to disable the certificate checking then use below code:
AxisProperties.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");
you can use
$('option:selected').next('option')
or
$('option:selected + option')
And set the value:
var nextVal = $('option:selected + option').val();
$('select').val(nextVal);
Here is shortest way of doing it.
$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();
Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.
In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.
If Not Directory.Exists(somePath) then
Directory.CreateDirectory(somePath)
End If
Try using OPENDATASOURCE The syntax is like this:
select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable
For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version
Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.
I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem
It's much simpler than all that:
while(str.Contains(" ")) str = str.Replace(" ", " ");
Declare the a
element as display: inline-block
and drop the width and height from the li
element.
Alternatively, apply a float: left
to the li
element and use display: block
on the a
element. This is a bit more cross browser compatible, as display: inline-block
is not supported in Firefox <= 2 for example.
The first method allows you to have a dynamically centered list if you give the ul
element a width of 100% (so that it spans from left to right edge) and then apply text-align: center
.
Use line-height
to control the text's Y-position inside the element.
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
To center Button in panel o in other container follow this step:
fwiw, I received this error due to some custom initialization within the constructor attempting to access a null object.
I needed to trim the values in a primary key column that had first and last names, so I did not want to trim all white space as that would remove the space between the first and last name, which I needed to keep. What worked for me was...
UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);
Note that the first instance of FIELD is in single quotes but the second is not in quotes at all. I had to do it this way or it gave me a syntax error saying it was a duplicate primary key when I had both in quotes.
It's been quite some time but it's a core part of the stdlib and has dozens of potential methods so I think it's useful to have some benchmarks for the different suggestions and include the numpy method which can be by far the fastest.
import random
from timeit import timeit
import numpy as np
l = [random.random() for i in range(10**4)]
l[10**4 - 100] = 5
# method 1
def fun1(l:list, x:int, e = -1) -> int:
return [[i for i,elem in enumerate(l) if elem == x] or [e]][0]
# method 2
def fun2(l:list, x:int, e = -1) -> int:
for i,elem in enumerate(l):
if elem == x:
return i
else:
return e
# method 3
def fun3(l:list, x:int, e = -1) -> int:
try:
idx = l.index(x)
except ValueError:
idx = e
return idx
# method 4
def fun4(l:list, x:int, e = -1) -> int:
return l.index(x) if x in l else e
l2 = np.array(l)
# method 5
def fun5(l:list or np.ndarray, x:int, e = -1) -> int:
res = np.where(np.equal(l, x))
if res[0].any():
return res[0][0]
else:
return e
if __name__ == "__main__":
print("Method 1:")
print(timeit(stmt = "fun1(l, 5)", number = 1000, globals = globals()))
print("")
print("Method 2:")
print(timeit(stmt = "fun2(l, 5)", number = 1000, globals = globals()))
print("")
print("Method 3:")
print(timeit(stmt = "fun3(l, 5)", number = 1000, globals = globals()))
print("")
print("Method 4:")
print(timeit(stmt = "fun4(l, 5)", number = 1000, globals = globals()))
print("")
print("Method 5, numpy given list:")
print(timeit(stmt = "fun5(l, 5)", number = 1000, globals = globals()))
print("")
print("Method 6, numpy given np.ndarray:")
print(timeit(stmt = "fun5(l2, 5)", number = 1000, globals = globals()))
print("")
When run as main, this results in the following printout on my machine indicating time in seconds to complete 1000 trials of each function:
Method 1: 0.7502102799990098
Method 2: 0.7291318440002215
Method 3: 0.24142152300009911
Method 4: 0.5253471979995084
Method 5, numpy given list: 0.5045417560013448
Method 6, numpy given np.ndarray: 0.011147511999297421
Of course the question asks specifically about lists so the best solution is to use the try-except method, however the speed improvements (at least 20x here compared to try-except) offered by using the numpy data structures and operators instead of python data structures is significant and if building something on many arrays of data that is performance critical then the author should try to use numpy throughout to take advantage of the superfast C bindings. (CPython interpreter, other interpreter performances may vary)
Btw, the reason Method 5 is much slower than Method 6 is because numpy first has to convert the given list to it's own numpy array, so giving it a list doesn't break it it just doesn't fully utilise the speed possible.
If you wish to download a version of a file, you need to use get_object
.
import boto3
bucket = 'bucketName'
prefix = 'path/to/file/'
filename = 'fileName.ext'
s3c = boto3.client('s3')
s3r = boto3.resource('s3')
if __name__ == '__main__':
for version in s3r.Bucket(bucket).object_versions.filter(Prefix=prefix + filename):
file = version.get()
version_id = file.get('VersionId')
obj = s3c.get_object(
Bucket=bucket,
Key=prefix + filename,
VersionId=version_id,
)
with open(f"{filename}.{version_id}", 'wb') as f:
for chunk in obj['Body'].iter_chunks(chunk_size=4096):
f.write(chunk)
Ref: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html
Since MySQL 5.6.X you can do this:
ALTER TABLE `schema`.`users`
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
That way your column will be updated with the current timestamp when a new row is inserted, or updated.
If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
in the DEFAULT value field, like so:
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
This is how I solved
<a href="#" >
<button type="button" class="btn btn-info">Button Text</button>
</a>
These are the changes since python 2:
try:
1 / 0
except Exception as e: # (as opposed to except Exception, e:)
# ^ that will just look for two classes, Exception and e
# for the repr
print(repr(e))
# for just the message, or str(e), since print calls str under the hood
print(e)
# the arguments that the exception has been called with.
# the first one is usually the message. (OSError is different, though)
print(e.args)
You can look into the standard library module traceback for fancier stuff.
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
document.location === window.location
returns true
also
document.location.constructor === window.location.constructor
is true
Note: Just tested on , Firefox 3.6, Opera 10 and IE6
One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.
Hope it helps,
SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.
First rule of securing any script or page that attaches to a database instance is Do not trust user input.
Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a '
to a paramater, your 'injection' is hoping for the following type of statement:
SELECT username,password FROM users WHERE username='$username'
By appending a '
to that statement, you could then add additional SQL paramaters or queries.: ' OR username --
SELECT username,password FROM users WHERE username='' OR username -- '$username
That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.
Generally there are three types of SQL injection methods:
Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.
Edit:
As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.
SELECT * FROM information_schema.tables;
Eric Petroelje almost has it right:
SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )
Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)
Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:
l = locals()
for i in xrange(3):
exec("group" + str(i) + "= self.getGroup(selected, header + i)")
Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:
Class A(models.Model):
....
def __getitem__(self, item): # a.__getitem__('id')
#exec("attrb = self." + item)
#return attrb
return self.__dict__[item]
It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.
A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.
You can try out this implementation for running Swift 5 on XCode 11
class CustomView: UIView {
var customParam: customType
var container = UIView()
required init(customParamArg: customType) {
self.customParam = customParamArg
super.init(frame: .zero)
// Setting up the view can be done here
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
// Can do the setup of the view, including adding subviews
setupConstraints()
}
func setupConstraints() {
// setup custom constraints as you wish
}
}
Just to add a new method to an old (but still relevant question). In the new portal, clicking the help icon from any screen and selecting 'Show Diagnostics' will show you a JSON document containing all your tenant information including TenantId, Tenant Name, and much, much more useful information
The context classes for badge
are indeed removed from Bootstrap 3, so you'd have to add some custom CSS to create the same effect like...
.badge-important{background-color:#b94a48;}
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
I believe the command you are looking for is passwd
SELECT
OBJECT_NAME(PARENT_OBJECT_ID) AS PARENT_TABLE,
OBJECT_NAME(OBJECT_ID) TRIGGER_TABLE,
*
FROM
SYS.OBJECTS
WHERE TYPE = 'TR'
Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:
You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
HTML CODE
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
formGroup: FormGroup;
ngOnInit() {
this.myInput.valueChanges
.subscribe(() => {
this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
});
}
get myInput(): AbstractControl {
return this.myForm.controls['myInput'];
}
<form id="yourFormName" >
<input type="text" value="" id="val1">
<input type="text" value="" id="val2">
<input type="text" value="" id="val3">
<button type="button" onclick="yourFunction()"> Check </button>
</form>
<script type="text/javascript">
function yourFunction()
{
var elements = document.querySelectorAll("#yourFormName input[type=text]")
console.log(elements);
for (var i = 0; i<elements.length; i++ )
{
var check = document.getElementById(elements[i].id).value);
console.log(check);
// write your logic here
}
}
</script>
With Visual Studio 2017 Community edition on mac, the shortcut is:
To see these commands, navigate to the top menu: Search > Go To
Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]
In Windows open the Run window (Win + R):
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --allow-running-insecure-content
In OS-X Terminal.app
run the following command ⌘+space:
open /Applications/Google\ Chrome.app --args --allow-running-insecure-content
Note:
You seem to be able to add the argument --allow-running-insecure-content
to bypass this for development. But its not a recommended solution.
it is varchar right? So it then doesn't matter if you use 50 or 25, better be safe and use 50, that said I believe the longest I have seen is about 19 or so. Last names are longer
It's not clear exactly what you want to do with the index of a substring [update: it is clearer now - thanks] but you may be able to use the function substring-after
or substring-before
:
substring-before('My name is Fred', 'Fred')
returns 'My name is '
.
If you need more detailed control, the substring()
function can take two or three arguments: string, starting-index, length. Omit length to get the whole rest of the string.
There is no index-of()
function for strings in XPath (only for sequences, in XPath 2.0). You can use string-length(substring-before($string, $substring))+1
if you specifically need the position.
There is also contains($string, $substring)
. These are all documented here. In XPath 2.0 you can use regular expression matching.
(XSLT mostly uses XPath for selecting nodes and processing values, so this is actually more of an XPath question. I tagged it thus.)
Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:
Check if $n is between $a and $b even if:
$a < $b
$a > $b
$a = $b
All numbers can be real, not only integer.
There is an easy way to test.
I base the test it in the fact that ($n-$a)
and ($n-$b)
have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.
function between($n, $a, $b)
{
return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}
I was a little bit worried about using only touchmove for my project, since it only seems to fire when your touch moves from one location to another (and not on the initial touch). So I combined it with touchstart, and this seems to work very well for the initial touch and any movements.
<script>
function doTouch(e) {
e.preventDefault();
var touch = e.touches[0];
document.getElementById("xtext").innerHTML = touch.pageX;
document.getElementById("ytext").innerHTML = touch.pageY;
}
document.addEventListener('touchstart', function(e) {doTouch(e);}, false);
document.addEventListener('touchmove', function(e) {doTouch(e);}, false);
</script>
X: <div id="xtext">0</div>
Y: <div id="ytext">0</div>
If you are looking for a very simple lastIndex lookup with RegExp and don't care if it mimics lastIndexOf to the last detail, this may catch your attention.
I simply reverse the string, and subtract the first occurence index from length - 1. It happens to pass my test, but I think there could arise a performance issue with long strings.
interface String {
reverse(): string;
lastIndex(regex: RegExp): number;
}
String.prototype.reverse = function(this: string) {
return this.split("")
.reverse()
.join("");
};
String.prototype.lastIndex = function(this: string, regex: RegExp) {
const exec = regex.exec(this.reverse());
return exec === null ? -1 : this.length - 1 - exec.index;
};
Dim row As DataRow
For Each row In dtDataTable.Rows
Dim strDetail As String
strDetail = row("Detail")
Console.WriteLine("Processing Detail {0}", strDetail)
Next row
The correct solution to the problem is to make sure SQL server authentication is turned on for your SQL Server.
Swift 3
For a simple solution without third party code:
Just use a normal UIAlertController but with style = actionSheet (look at code down below)
let alertDisapperTimeInSeconds = 2.0
let alert = UIAlertController(title: nil, message: "Toast!", preferredStyle: .actionSheet)
self.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + alertDisapperTimeInSeconds) {
alert.dismiss(animated: true)
}
The advantage of this solution:
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
A Looper has a synchronized
MessageQueue
that's used to process Messages placed on the queue.
It implements a Thread
Specific Storage Pattern.
Only one Looper
per Thread
. Key methods include prepare()
,loop()
and quit()
.
prepare()
initializes the current Thread
as a Looper
. prepare()
is static
method that uses the ThreadLocal
class as shown below.
public static void prepare(){
...
sThreadLocal.set
(new Looper());
}
prepare()
must be called explicitly before running the event loop. loop()
runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop()
method dispatches the Message to its target handlerquit()
shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special messageLooper
can be programmed in a Thread
via several steps
Extend Thread
Call Looper.prepare()
to initialize Thread as a Looper
Create one or more Handler
(s) to process the incoming messages
Looper.loop()
to process messages until the loop is told to quit()
. A _ttoi
function can convert CString
to integer, both wide char and ansi char can work. Below is the details:
CString str = _T("123");
int i = _ttoi(str);
I made a simple code that doesn't even need JQuery and probably gonna help some people. It gets the total height of 'ID1' after loaded and use it on 'ID2'
function anyName(){
var varname=document.getElementById('ID1').offsetHeight;
document.getElementById('ID2').style.height=varname+'px';
}
Then just set the body to load it
<body onload='anyName()'>
The following site demonstrates how to export a DataTable, DataSet or List<> into a "proper" Excel 2007 .xlsx file (rather than exporting a .csv file, and getting Excel to open it).
It uses the OpenXML libraries, so you don't need to have Excel installed on your server.
Mikes Knowledge Base - ExportToExcel
All of the source code is given, free of charge, aswell as a demo application.
It's very easy to add to your own applications, you just need to call one function, passing in an Excel filename, and your data source:
DataSet ds = CreateSampleData();
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);
Hope this helps.
The task boils down to iterating over characters of the string and collecting them into a list. The most naïve solution would look like
result = []
for character in string:
result.append(character)
Of course, it can be shortened to just
result = [character for character in string]
but there still are shorter solutions that do the same thing.
list
constructor can be used to convert any iterable (iterators, lists, tuples, string etc.) to list.
>>> list('abc')
['a', 'b', 'c']
The big plus is that it works the same in both Python 2 and Python 3.
Also, starting from Python 3.5 (thanks to the awesome PEP 448) it's now possible to build a list from any iterable by unpacking it to an empty list literal:
>>> [*'abc']
['a', 'b', 'c']
This is neater, and in some cases more efficient than calling list
constructor directly.
I'd advise against using map
-based approaches, because map
does not return a list in Python 3. See How to use filter, map, and reduce in Python 3.
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
I wrote the following procedure for concatenation of several array:
static public byte[] concat(byte[]... bufs) {
if (bufs.length == 0)
return null;
if (bufs.length == 1)
return bufs[0];
for (int i = 0; i < bufs.length - 1; i++) {
byte[] res = Arrays.copyOf(bufs[i], bufs[i].length+bufs[i + 1].length);
System.arraycopy(bufs[i + 1], 0, res, bufs[i].length, bufs[i + 1].length);
bufs[i + 1] = res;
}
return bufs[bufs.length - 1];
}
It uses Arrays.copyOf
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
It was used for "intermediate materialization (Google search)"
Good article: Adam Machanic: Exploring the secrets of intermediate materialization
He even raised an MS Connect so it can be done in a cleaner fashion
My view is "not inherently bad", but don't use it unless 100% sure. The problem is, it works only at the time you do it and probably not later (patch level, schema, index, row counts etc)...
This may fail because you don't know in which order things are evaluated
SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1 AND CAST(foo AS int) > 100
And this may also fail because
SELECT foo
FROM
(SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1) bar
WHERE
CAST(foo AS int) > 100
However, this did not in SQL Server 2000. The inner query is evaluated and spooled:
SELECT foo
FROM
(SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC (foo) = 1 ORDER BY foo) bar
WHERE
CAST(foo AS int) > 100
Note, this still works in SQL Server 2005
SELECT TOP 2000000000 ... ORDER BY...
Yes, but not with that version of the constructor. You can do this:
>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}
There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."
It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.
On modern browsers, you can use the input
event:
$("#textbox").on('input',function() {alert("Change detected!");});
With Blend for Visual Studio, which is included in Visual Studio starting with version 2013, you can find the DLL in the following folder:
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries
You will have to add the reference to the System.Windows.Interactivity.dll
yourself though, unless you use Blend for Visual Studio with an existing project to add functionality that makes use of the Interactivity namespace. In that case, Blend will add the reference automatically.
FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
This is all you need: http://api.jquery.com/click/
Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.
Or 4. Put them in the class that contains the logic that uses the constants the most
... sorry, couldn't resist ;-)
suggestion here looks like a good candidate for this question as well
Performing click event on a disabled element? Javascript jQuery
jQuery('input#submit').click(function(e) {
if ( something ) {
return false;
}
});
You can use this function:
function mapMap(map, fn) {
return new Map(Array.from(map, ([key, value]) => [key, fn(value, key, map)]));
}
usage:
var map1 = new Map([["A", 2], ["B", 3], ["C", 4]]);
var map2 = mapMap(map1, v => v * v);
console.log(map1, map2);
/*
Map { A ? 2, B ? 3, C ? 4 }
Map { A ? 4, B ? 9, C ? 16 }
*/
This works too
var i = 1;_x000D_
$('button').click(function() {_x000D_
$('#red').clone().appendTo('#test').prop('id', 'red' + i);_x000D_
i++; _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<div id="test">_x000D_
<button>Clone</button>_x000D_
<div class="red" id="red">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
.red {_x000D_
width:20px;_x000D_
height:20px;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
</style>
_x000D_
100,000 should be fine.
I have (anecdotally) seen people having problems with many millions of files and I have had problems myself with Explorer just not having a clue how to count past 60-something thousand files, but NTFS should be good for the volumes you're talking.
In case you're wondering, the technical (and I hope theoretical) maximum number of files is: 4,294,967,295
Link statically to libstdc++ with -static-libstdc++
gcc option.
Forcing the buttons stay in the same line will make them go beyond the fixed width of the div they are in. If you are okay with that then you can make another div inside the div you already have. The new div in turn will hold the buttons and have the fixed width of however much space the two buttons need to stay in one line.
Here is an example:
<div id="parentDiv" style="width: [less-than-what-buttons-need]px;">
<div id="holdsButtons" style="width: [>=-than-buttons-need]px;">
<button id="button1">1</button>
<button id="button2">2</button>
</div>
</div>
You may want to consider overflow property for the chunk of the content outside of the parentDiv
border.
Good luck!
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
Since looks like node-curl
is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.
Usage example:
var Curl = require( 'node-libcurl' ).Curl;
var curl = new Curl();
curl.setOpt( Curl.option.URL, 'www.google.com' );
curl.setOpt( 'FOLLOWLOCATION', true );
curl.on( 'end', function( statusCode, body, headers ) {
console.info( statusCode );
console.info( '---' );
console.info( body.length );
console.info( '---' );
console.info( headers );
console.info( '---' );
console.info( this.getInfo( Curl.info.TOTAL_TIME ) );
this.close();
});
curl.on( 'error', function( err, curlErrorCode ) {
console.error( err.message );
console.error( '---' );
console.error( curlErrorCode );
this.close();
});
curl.perform();
Perform is async, and there is no way to use it synchronous currently (and probably will never have).
It's still in alpha, but this is going to change soon, and help is appreciated.
Now it's possible to use Easy
handle directly for sync requests, example:
var Easy = require( 'node-libcurl' ).Easy,
Curl = require( 'node-libcurl' ).Curl,
url = process.argv[2] || 'http://www.google.com',
ret, ch;
ch = new Easy();
ch.setOpt( Curl.option.URL, url );
ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {
console.log( buf );
return size * nmemb;
});
ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {
console.log( arguments );
return size * nmemb;
});
// this call is sync!
ret = ch.perform();
ch.close();
console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );
Also, the project is stable now!
If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).
Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...
You will have to split your string into a list of values using split()
So,
lines = text_file.read().split(',')
EDIT: I didn't realise there would be so much traction to this. Here's a more idiomatic approach.
import csv
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
# do something
In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
I tried some of the other answers here, but originalEvent was also undefined. Upon inspection, found a TouchList classed property (as suggested by another poster) and managed to get to pageX/Y this way:
var x = e.changedTouches[0].pageX;
You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
For getting permissions at runtime, you will have to request the user. You can do that in following way.
First request for permissions.
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
And then you can check the results in
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_REQUEST_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission granted.
//Continue with writing files...
}
else{
//Permission denied.
}
break;
}
}
Here is good learning source requesting-runtime-permissions-in-android-marshmallow/
I have read some article before and it's working fine but really don't know is safe or not
a. Create new folder local.
b. Move all project into the local folder expect public folder.
c. Move all the content of public folder to project root.
d. Delete the blank public folder
f. Edit the index file.
Edit the index.php
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
to
require __DIR__.'/local/bootstrap/autoload.php';
$app = require_once __DIR__.'/local/bootstrap/app.php';
Sometimes You just open too much applications in Windows and make the gradle have no enough memory to start the daemon process.So when you come across with this situation,you can just close some applications such as Chrome and so on. Then restart your android studio.
Here are the examples of Filter, map and reduce functions.
numbers = [10,11,12,22,34,43,54,34,67,87,88,98,99,87,44,66]
//Filter
oddNumbers = list(filter(lambda x: x%2 != 0, numbers))
print(oddNumbers)
//Map
multiplyOf2 = list(map(lambda x: x*2, numbers))
print(multiplyOf2)
//Reduce
The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:
from functools import reduce
sumOfNumbers = reduce(lambda x,y: x+y, numbers)
print(sumOfNumbers)
First of all - setTimeout and setInterval is what should be used, because of javascript's callback-ish nature. If you want to use sleep()
it's the control flow or the architecture of your code that is incorrect.
Having said that I suppose I still can help with two implementation of a sleep.
faking synchronous run off the top of my head:
//a module to do taht //dual-license: MIT or WTF [you can use it anyhow and leave my nickname in a comment if you want to]
var _=(function(){
var queue=[];
var play=function(){
var go=queue.shift();
if(go){if(go.a){go.f();play();}else{setTimeout(play,go.t);}}
}
return {
go:function(f){
queue.push({a:1,f:f});
},
sleep:function(t){
queue.push({a:0,t:t});
},
playback:play
}
})();
[making playback automatic should also be possible]
//usage
_.go(function(){
//your code
console.log('first');
});
_.sleep(5000);
_.go(function(){
//your code
console.log('next');
});
//this triggers the simulation
_.playback();
real synchronous run
I gave it a lot of thought one day and the only idea I had for a true sleep in javascript is technical.
a sleep function would have to be a synchronous AJAX call with a timeout set to the sleep value. That's all and an only way to have a real sleep()
Add this:
<div class="footer navbar-fixed-bottom">
https://stackoverflow.com/a/21604189
EDIT: class navbar-fixed-bottom
has been changed to fixed-bottom
as of Bootstrap v4-alpha.6.
http://v4-alpha.getbootstrap.com/components/navbar/#placement
Linux users can find the locations of all the installed packages like this:
pip list | xargs -exec pip show
Use the xattr
command. You can inspect the extended attributes:
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine
and use the -d
option to delete one extended attribute:
$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
you can also use the -c
option to remove all extended attributes:
$ xattr -c s.7z
$ xattr s.7z
xattr -h
will show you the command line options, and xattr has a man page.
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
For those who need the input file to open directly the camera, you just have to declare capture
parameter to the input file, like this :
<input type="file" accept="image/*" capture>
As to std::vector<int> vec
, vec to get int*
, you can use two method:
int* arr = &vec[0];
int* arr = vec.data();
If you want to convert any type T
vector to T* array
, just replace the above int
to T
.
I will show you why does the above two works, for good understanding?
std::vector
is a dynamic array essentially.
Main data member as below:
template <class T, class Alloc = allocator<T>>
class vector{
public:
typedef T value_type;
typedef T* iterator;
typedef T* pointer;
//.......
private:
pointer start_;
pointer finish_;
pointer end_of_storage_;
public:
vector():start_(0), finish_(0), end_of_storage_(0){}
//......
}
The range (start_, end_of_storage_)
is all the array memory the vector allocate;
The range(start_, finish_)
is all the array memory the vector used;
The range(finish_, end_of_storage_)
is the backup array memory.
For example, as to a vector vec. which has {9, 9, 1, 2, 3, 4} is pointer may like the below.
So &vec[0]
= start_ (address.) (start_ is equivalent to int* array head)
In c++11
the data()
member function just return start_
pointer data()
{
return start_; //(equivalent to `value_type*`, array head)
}
To switch to other branch without committing the changes when git stash doesn't work. You can use the below command:
git checkout -f branch-name
Google's Guava library also has a copy method:
public static void copy(File from, File to) throws IOException
Warning: If to
represents an existing file, that file
will be overwritten with the contents of from
. If to
and
from
refer to the same file, the contents of that file
will be deleted.
Parameters:from
- the source fileto
- the destination file
Throws:
IOException
- if an I/O error occurs
IllegalArgumentException
- if from.equals(to)
// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);??
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter
attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter
that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter
attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter
, then specify the date format in the constructor of the subclass. Apply the JsonConverter
attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(as seen in the source code).
You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.
I know this works since I'm doing the very same thing.
First of all you need to install json-loader
:
npm i json-loader --save-dev
Then, there are two ways how you can use it:
In order to avoid adding json-loader
in each import
you can add to webpack.config
this line:
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
// other loaders
]
Then import json
files like this
import suburbs from '../suburbs.json';
Use json-loader
directly in your import
, as in your example:
import suburbs from 'json!../suburbs.json';
Note:
In webpack 2.*
instead of keyword loaders
need to use rules
.,
also webpack 2.*
uses json-loader
by default
*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.
Suppose you have a data frame(say df) with columns "x" and "y", you can find mean of column (x or y) using:
1.Using mean() function
z<-mean(df$x)
2.Using the column name(say x) as a variable using attach()
function
attach(df)
mean(x)
When done you can call detach()
to remove "x"
detach()
3.Using with()
function, it lets you use columns of data frame as distinct variables.
z<-with(df,mean(x))
The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this(1) SO answer.
Step (6) is since Android studio expects native libs in app/src/main/jniLibs
instead of older libs
folder. For those new to Android OpenCV, don't miss below steps
static{ System.loadLibrary("opencv_java"); }
(Note: for OpenCV version 3 at this step you should instead load the library opencv_java3
.)OpenCV written is in C/C++. Java wrappers are
It should be as simple as git log <somepath>
; check the manpage (git-log(1)
).
Personally I like to use git log --stat <path>
so I can see the impact of each commit on the file.
An easy way of doing this is to use JavaScript like so:
element.addEventListener('click', (e => {
e.preventDefault();
element.style = '<insert CSS here as you would in a style attribute>';
}));
This could be one of the two problems you mention yourself.
To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:
$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");
Even if this works, post some code since this is not optimal, imo :-)
The best way to go is:
TextView tv = findViewById(R.id.textView);
tv.setTypeface(Typeface.DEFAULT_BOLD);
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
I have just created the function with the same names to convert and overwrite to the new one php7:
$host = "your host";
$un = "username";
$pw = "password";
$db = "database";
$MYSQLI_CONNECT = mysqli_connect($host, $un, $pw, $db);
function mysql_query($q) {
global $MYSQLI_CONNECT;
return mysqli_query($MYSQLI_CONNECT,$q);
}
function mysql_fetch_assoc($q) {
return mysqli_fetch_assoc($q);
}
function mysql_fetch_array($q){
return mysqli_fetch_array($q , MYSQLI_BOTH);
}
function mysql_num_rows($q){
return mysqli_num_rows($q);
}
function mysql_insert_id() {
global $MYSQLI_CONNECT;
return mysqli_insert_id($MYSQLI_CONNECT);
}
function mysql_real_escape_string($q) {
global $MYSQLI_CONNECT;
return mysqli_real_escape_string($MYSQLI_CONNECT,$q);
}
It works for me , I hope it will work for you all , if I mistaken , correct me.
You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:
<ul class="yourlinks">
<li><a href="http://www.google.com/"></li>
<li><a href="http://www.yahoo.com/"></li>
</ul>
$(function() { // On DOM content ready...
var urls = [];
$('.yourlinks a').each(function() {
urls.push(this.href); // Store the URLs from the links...
});
var multilink = $('<a href="#">Click here</a>'); // Create a new link...
multilink.click(function() {
for (var i in urls) {
window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
}
});
$('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});
This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
Try figsize
param in df.plot(figsize=(width,height))
:
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));
The size in figsize=(5,3)
is given in inches
per (width, height)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html
Exceptions are related to Design by Contract.
The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts
1) all input the method is valid, in which case you must return null when the object is not found.
2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example
is_present(key)
find(key) throws Exception
IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!
Change the position
attribute to fixed
instead of absolute
.
let idsArray = ids.split(',').map((x) => parseInt(x));
The .navbar-static-top
you are using forces your navbar
to become full-width. Remove that class and you will get a resizable navbar
. Then, you can wrap it in a span#
of the size you want.
<div class="container">
<div class="row">
<div class="span6 offset3">
<div class="navbar">
...
</div>
</div>
</div>
You might consider turning your python script into a proper python daemon, as described here.
python-daemon is a good tool that can be used to run python scripts as a background daemon process rather than a forever running script. You will need to modify existing code a bit but its plain and simple.
If you are facing problems with python-daemon, there is another utility supervisor that will do the same for you, but in this case you wont have to write any code (or modify existing) as this is a out of the box solution for daemonizing processes.
Using for:
for each in "${alpha[@]}"
do
echo "$each"
done
Using history; note this will fail if your values contain !
:
history -p "${alpha[@]}"
Using basename; note this will fail if your values contain /
:
basename -a "${alpha[@]}"
Using shuf; note that results might not come out in order:
shuf -e "${alpha[@]}"
Swift 4
//MARK:- Show Status Bar
UIApplication.shared.isStatusBarHidden = false
//MARK:- Hide Status Bar
UIApplication.shared.isStatusBarHidden = true
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
I know this is an old post, however I thought I'd share the method I use to remove new line characters.
s.Replace(Environment.NewLine, "");
References:
MSDN String.Replace Method and MSDN Environment.NewLine Property
You should have a look on the -regextype
argument of find
, see manpage:
-regextype type
Changes the regular expression syntax understood by -regex and -iregex
tests which occur later on the command line. Currently-implemented
types are emacs (this is the default), posix-awk, posix-basic,
posix-egrep and posix-extended.
I guess the emacs
type doesn't support the [[:digit:]]
construct. I tried it with posix-extended
and it worked as expected:
find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
If you're trying to get the string into a variable, another easy way is something like this:
USAGE=$(cat <<-END
This is line one.
This is line two.
This is line three.
END
)
If you indent your string with tabs (i.e., '\t'), the indentation will be stripped out. If you indent with spaces, the indentation will be left in.
NOTE: It is significant that the last closing parenthesis is on another line. The END
text must appear on a line by itself.
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
In C++11, this is the preferred way:
std::vector<X> f();
That is, return by value.
With C++11, std::vector
has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.
Here is a simple function for converting a byte buffer to string:
public String byteBufferToString(ByteBuffer bufferData) {
byte[] buffer = new byte[bufferData.readableByteCount()];
// read bufferData and insert into buffer
data.read(buffer);
// CharsetUtil supports UTF_16, ASCII, and many more
String text = new String(buffer, CharsetUtil.UTF_8);
System.out.println("Text: "+text);
return text;
}
EDIT Until such time as StackOverflow allows us to version our answers, this is an answer that works for Android 3 and below. Please don't downvote it because it's not working for you now, because it definitely works with older Android versions.
You should only need to add one line to your onCreateDialog()
method:
@Override
protected Dialog onCreateDialog(int id) {
//all other dialog stuff (which dialog to display)
//this line is what you need:
dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
return dialog;
}
Here is the simplest example that has the key lines of code:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
plt.imshow(H, interpolation='none')
plt.show()
For all the Swift lovers out there, here is the answer by @Travis translated into SWIFT:
Do what @Travis explained before the Objective C code. Then,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController
self.window?.rootViewController = exampleViewController
self.window?.makeKeyAndVisible()
return true
}
The ExampleViewController
would be the new initial view controller you would like to show.
The steps explained:
Enjoy and happy programming!
Assuming Java (JDK + JRE) is installed in your system, do the following:
C:/>javap javax.servlet.http.HttpServletRequest
It should show a bunch of classes
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');
Optional! Convert to JS Date obj for Angular binding.
var date = new Date(dateMnsFive.toISOString());
Optional! Format
var date = dateMnsFive.format("YYYY-MM-DD");
I have encountered the same problem. I solved by creating an instance for every inner public Class. as for you situation, i suggest you use inheritance other than inner classes.
public class Shape {
private String shape;
public ZShape zShpae;
public SShape sShape;
public Shape(){
int[][] coords = noShapeCoords;
shape = "NoShape";
zShape = new ZShape();
sShape = new SShape();
}
class ZShape{
int[][] coords = zShapeCoords;
String shape = "ZShape";
}
class SShape{
int[][] coords = sShapeCoords;
String shape = "SShape";
}
//etc
}
then you can new Shape(); and visit ZShape through shape.zShape;
It because every time
void pthread_exit(void *ret);
will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().
Now at
int pthread_join(pthread_t tid, void **ret);
will be always called from where thread is created so here to accept that returned pointer you need double pointer ..
i think this code will help you to understand this
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
void* thread_function(void *ignoredInThisExample)
{
char *a = malloc(10);
strcpy(a,"hello world");
pthread_exit((void*)a);
}
int main()
{
pthread_t thread_id;
char *b;
pthread_create (&thread_id, NULL,&thread_function, NULL);
pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
value so to use that we need double pointer
printf("b is %s\n",b);
free(b); // lets free the memory
}
You can use a heredoc. e.g. from a prompt:
$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF
so sqlplus
will consume everything up to the EOF
marker as stdin.
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
You can do this:
Put in httpBody the data
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let pjson = attendences.toJSONString(prettyPrint: false)
let data = (pjson?.data(using: .utf8))! as Data
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
print(response)
}
You have used '/0'
instead of '\0'
. This is incorrect: the '\0'
is a null character, while '/0'
is a multicharacter literal.
Moreover, in C it is OK to skip a zero in your condition:
while (*(forward++)) {
...
}
is a valid way to check character, integer, pointer, etc. for being zero.
This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:
... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.
The configuration related to this was:
ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/
"No protocol handler was valid for the URL /~socket.io/
" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/
"
I had proxy_http
loaded, but also needed proxy_wstunnel
. Once that was enabled all was good.
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
Think of Observables as a pipe with flowing water in it, sometimes water flows and sometimes it doesn't. In some cases, you may actually need a pipe that has always water in it, you can do this by creating a special pipe which always contains a water no matter how small it is, lets call this special pipe BehaviorSubject, if you happens to be a water supply provider in your community, you can sleep peacefully at night knowing that your newly installed pipe just works.
In technical terms: you may encounter usescases where an Observable should always have value in it, perhaps you want to capture the value of a input text over time, you can then create an instance of BehaviorSubject to ensure this kind of behavior, lets say:
const firstNameChanges = new BehaviorSubject("<empty>");
// pass value changes.
firstNameChanges.next("Jon");
firstNameChanges.next("Arya");
You can then use "value" to sample changes over time.
firstNameChanges.value;
This comes handy when you combine Observables later, by taking a look at the type of your stream as BehaviorSubject you can then ensure that the stream at least fires or signal just once atleast.
Ok, Here's what I found out.
What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)
What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
Log.d(TAG, "constructor: detaching fragment " + mTag);
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab"));
Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number"));
}
When the tab was selected it would be reattached in the onTabSelected callback.
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
Log.d(TAG, "onTabSelected adding fragment " + mTag);
ft.add(android.R.id.content, mFragment, mTag);
} else {
Log.d(TAG, "onTabSelected attaching fragment " + mTag);
ft.attach(mFragment);
}
}
The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time.
The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
Log.d(TAG, "onTabSelected adding fragment " + mTag);
ft.add(android.R.id.content, mFragment, mTag);
} else {
if(mFragment.isDetached()) {
Log.d(TAG, "onTabSelected attaching fragment " + mTag);
ft.attach(mFragment);
} else {
Log.d(TAG, "onTabSelected fragment already attached " + mTag);
}
}
}
For me this is the best way:
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Reset form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").reset();
}
</script>
here: C:\Program Files\Java\jre7\bin it is an exe keytool.exe
Layer draws out of clip region, you need to set it to mask to bounds:
self.mainImageView.layer.masksToBounds = true
From the docs:
By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners
This is how you call an instance method on the Controller:
@{
((HomeController)this.ViewContext.Controller).Method1();
}
This is how you call a static method in any class
@{
SomeClass.Method();
}
This will work assuming the method is public and visible to the view.
You can use this for color without alpha:
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
or this with alpha:
String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));
You can do this and it will always work:
child.center = [parent convertPoint:parent.center fromView:parent.superview];
And for Swift:
child.center = parent.convert(parent.center, from:parent.superview)
In my case it turns out my
new server was running MySQL 5.5
,
old server was running MySQL 5.6
.
So I got this error when trying to import the .sql
file I'd exported from my old server.
MySQL 5.5 does not support utf8mb4_unicode_520_ci
, but
MySQL 5.6 does.
Updating to MySQL 5.6
on the new server solved collation the error !
If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql
file
- replace instances of utf8mb4unicode520_ci
and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql
file.
Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:
Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)
EDIT:
Modify last line to :
cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False)
if you want it to work even if there are spaces or other funny characters in the sheet name.
See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input>
elements -- in other words, use autocomplete="off"
.
go to bin folder path in cmd and then run following command
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
you will get your key hash
This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.
- hosts: all
roles:
- php
- nginx
environment:
MY_ENV_VARIABLE: whatever_value
You need to use a directed graph instead of a graph, i.e.
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw
(as shown by @Marius).
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.
session_destroy();
// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>
You do the same way as any other character matching, but you use \uXXXX where XXXX is the unicode number of the character.
File files = new File("src");
// src is folder name...
//This will return the list of the subDirectories
List<File> subDirectories = Arrays.stream(files.listFiles()).filter(File::isDirectory).collect(Collectors.toList());
// this will print all the sub directories
Arrays.stream(files.listFiles()).filter(File::isDirectory).forEach(System.out::println);
data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.
You can use DT[order(-rank(x), y)]
.
x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6
You can turn off foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
/* DO WHAT YOU NEED HERE */
SET FOREIGN_KEY_CHECKS = 1;
Please make sure to NOT use this on production and have a backup.
Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.
You can get the column name details from sys.columns table
Try the following query:
SELECT * FROM SYS.COLUMNS
WHERE object_id = OBJECT_ID('dbo.TableName')
AND [Name] <> 'ColumnName'
DECLARE @sql as VARCHAR(8000)
SET @sql = 'SELECT '
SELECT @sql += [Name] + ', ' FROM SYS.COLUMNS
WHERE object_id = OBJECT_ID('dbo.TableName')
AND [Name] <> 'ColumnName'
SELECT @sql += ' FROM Dbo.TableName'
EXEC(@sql)
to change the object owner try the following
EXEC sp_changedbowner 'sa'
that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex
magic that makes the whole cell Latex without the $$
wrapper for each line.
Refer notebook tour for Rich Display System
(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None]
notation:
n_lists = np.append(n_list_converted, n_last[:, None], axis=1)
Alternatively, when extracting n_last
you can use
n_last = n_list_converted[:, -1:]
to get a (20, 1)
array.
To Close a fragment while inside the same fragment
getActivity().onBackPressed();
You can also check this tree-extended package. It can be used as a command line app by using node >= 6.x.
It is very similar to tree
but also has the option of configuring the max deep in the tree, that is one of the awful things of it. Also you can filter by using .gitignore
file.
Just to simplify -
Entity framework doesn't support primitives. You either create a class to wrap it or add another property to format the list as a string:
public ICollection<string> List { get; set; }
public string ListString
{
get { return string.Join(",", List); }
set { List = value.Split(',').ToList(); }
}
Check this link: Assigning Roles to Users. You can add a step to your CreateUserWIzard control and choose the roles in that step.
<asp:CreateUserWizard ID="RegisterUserWithRoles" runat="server"
ContinueDestinationPageUrl="~/Default.aspx" LoginCreatedUser="False"
onactivestepchanged="RegisterUserWithRoles_ActiveStepChanged">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
</asp:CreateUserWizardStep>
<asp:WizardStep ID="SpecifyRolesStep" runat="server" AllowReturn="False"
StepType="Step" Title="Specify Roles">
<h3>Choose the role.</h3>
<asp:CheckBoxList ID="RoleList" runat="server">
</asp:CheckBoxList>
</asp:WizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
And in the code-behind you will have:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Reference the SpecifyRolesStep WizardStep
WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
// Reference the RoleList CheckBoxList
CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
// Bind the set of roles to RoleList
RoleList.DataSource = Roles.GetAllRoles();
RoleList.DataBind();
}
}
protected void RegisterUserWithRoles_ActiveStepChanged(object sender, EventArgs e)
{
// Have we JUST reached the Complete step?
if (RegisterUserWithRoles.ActiveStep.Title == "Complete")
{
// Reference the SpecifyRolesStep WizardStep
WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
// Reference the RoleList CheckBoxList
CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
// Add the checked roles to the just-added user
foreach (ListItem li in RoleList.Items)
{
if (li.Selected)
Roles.AddUserToRole(RegisterUserWithRoles.UserName, li.Text);
}
}
}
I really appreciate @raykrow's answer when one has this problem only in a test file! That is where I encountered it.
As it is often helpful to have another way to do something as a backup, I wanted to mention this technique that also works (instead of importing RouterTestingModule
):
import { MockComponent } from 'ng2-mock-component';
. . .
TestBed.configureTestingModule({
declarations: [
MockComponent({
selector: 'a',
inputs: [ 'routerLink', 'routerLinkActiveOptions' ]
}),
. . .
]
(Typically, one would use routerLink
on an <a>
element but adjust the selector accordingly for other components.)
The second reason I wanted to mention this alternate solution is that, though it served me well in a number of spec files, I ran into a problem with it in one case:
Error: Template parse errors:
More than one component matched on this element.
Make sure that only one component's selector can match a given element.
Conflicting components: ButtonComponent,Mock
I could not quite figure out how this mock and my ButtonComponent
were using the same selector, so searching for an alternate approach led me here to @raykrow's solution.
var arrayOne = [1,2,3]
var arrayTwo = [4,5,6]
if you want result as : [1,2,3,[4,5,6]]
arrayOne.append(arrayTwo)
above code will convert arrayOne as a single element and add it to the end of arrayTwo.
if you want result as : [1, 2, 3, 4, 5, 6] then,
arrayOne.append(contentsOf: arrayTwo)
above code will add all the elements of arrayOne at the end of arrayTwo.
Thanks.
Here you go other approach with less looping:
calculateTotalMonthsDifference = function(firstDate, secondDate) {
var fm = firstDate.getMonth();
var fy = firstDate.getFullYear();
var sm = secondDate.getMonth();
var sy = secondDate.getFullYear();
var months = Math.abs(((fy - sy) * 12) + fm - sm);
var firstBefore = firstDate > secondDate;
firstDate.setFullYear(sy);
firstDate.setMonth(sm);
firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
return months;
}
You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)
$form = $this->createFormBuilder()
->add('status', 'choice', array(
'choices' => array(
0 => 'Published',
1 => 'Draft'
),
'data' => 1
))
->getForm();
In this example, 'Draft' would be set as the default selected value.
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
The Developer Toolbar GCLI and Shift+F2 shortcut were removed in Firefox version 60. To take a screenshot in 60 or newer:
:screenshot
or :screenshot --fullpage
Find out more regarding screenshots and other features
For Firefox versions < 60:
Press Shift+F2 or go to Tools > Web Developer > Developer Toolbar to open a command line. Write:
screenshot
and press Enter in order to take a screenshot.
To fully answer the question, you can even save the whole page, not only the visible part of it:
screenshot --fullpage
And to copy the screenshot to clipboard, use --clipboard
option:
screenshot --clipboard --fullpage
Firefox 18 changes the way arguments are passed to commands, you have to add "--" before them.
You can find some documentation and the full list of commands here.
PS. The screenshots are saved into the downloads directory by default.
The best one by far is
bool(re.search('ba[rzd]', 'foobarrrr'))
Returns True
My working solution is:
cd /opt/genymobile/genymotion/tools
./adb shell
You have to use its own adb tool.
If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.
Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.
Native JSON support has been included in PHP since 5.2 in the form of methods json_encode()
and json_decode()
. You would use the first to output a PHP variable in JSON.
public class LockableScrollView extends ScrollView {
private boolean mScrollable = true;
public LockableScrollView(Context context) {
super(context);
}
public LockableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LockableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public LockableScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setScrollable(boolean enabled) {
mScrollable = enabled;
}
public boolean isScrollable() {
return mScrollable;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return mScrollable && super.onTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mScrollable && super.onInterceptTouchEvent(ev);
}
}
If you don't want to deal with interactive mode then do this:
Update your last pushed commit
git commit --amend -m "New commit message."
Push your new commit message (this will replace the old last commit message to this new one)
git push origin --force **branch-name**
More on this - https://linuxize.com/post/change-git-commit-message/
create constant file with any name like my_constants.py declare constant like that
CONSTANT_NAME = "SOME VALUE"
For accessing constant in your code import file like that
import my_constants as constant
and access the constant value as -
constant.CONSTANT_NAME
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s]
will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
As Matt J wrote, there is itoa
, but it's not standard. Your code will be more portable if you use snprintf
.
$this->container->get('security.token_storage')->getToken()->getUser();
Make the function abstract, so that derived classes have no other choice than to override it.
@Ray Your code is invalid.
class parent {
public:
virtual void handle_event(int something) const = 0 {
// boring default code
}
};
Abstract functions cannot have bodies defined inline. It must be modified to become
class parent {
public:
virtual void handle_event(int something) const = 0;
};
void parent::handle_event( int something ) { /* do w/e you want here. */ }
I know this is kind of an old question by this one works better.
if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
//Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}
As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
So as another answer mentioned Guava has support for this by using:
Streams.stream(iterable);
I want to highlight that the implementation does something slightly different than other answers suggested. If the Iterable
is of type Collection
they cast it.
public static <T> Stream<T> stream(Iterable<T> iterable) {
return (iterable instanceof Collection)
? ((Collection<T>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
}
public static <T> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(iterator, 0),
false
);
}
white-space: nowrap
is the correct solution but it will prevent any break in a line. If you only want to prevent line breaks between two elements it gets a bit more complicated:
<p>
<span class="text">Some text</span>
<span class="icon"></span>
</p>
To prevent breaks between the spans but to allow breaks between "Some" and "text" can be done by:
p {
white-space: nowrap;
}
.text {
white-space: normal;
}
That's good enough for Firefox. In Chrome you additionally need to replace the whitespace between the spans with an
. (Removing the whitespace doesn't work.)
UPDATE
From v0.20, melt
is a first order function, you can now use
df.melt(id_vars=["location", "name"],
var_name="Date",
value_name="Value")
location name Date Value
0 A "test" Jan-2010 12
1 B "foo" Jan-2010 18
2 A "test" Feb-2010 20
3 B "foo" Feb-2010 20
4 A "test" March-2010 30
5 B "foo" March-2010 25
OLD(ER) VERSIONS: <0.20
You can use pd.melt
to get most of the way there, and then sort:
>>> df
location name Jan-2010 Feb-2010 March-2010
0 A test 12 20 30
1 B foo 18 20 25
>>> df2 = pd.melt(df, id_vars=["location", "name"],
var_name="Date", value_name="Value")
>>> df2
location name Date Value
0 A test Jan-2010 12
1 B foo Jan-2010 18
2 A test Feb-2010 20
3 B foo Feb-2010 20
4 A test March-2010 30
5 B foo March-2010 25
>>> df2 = df2.sort(["location", "name"])
>>> df2
location name Date Value
0 A test Jan-2010 12
2 A test Feb-2010 20
4 A test March-2010 30
1 B foo Jan-2010 18
3 B foo Feb-2010 20
5 B foo March-2010 25
(Might want to throw in a .reset_index(drop=True)
, just to keep the output clean.)
Note: pd.DataFrame.sort
has been deprecated in favour of pd.DataFrame.sort_values
.
from inside vim, use one of the following
open a new window below the current one:
:new filename.ext
open a new window beside the current one:
:vert new filename.ext
This error can arise from several different sources. One case (not mentioned in other answers to this question) occurs when Eclipse does not implement the version of the JSP specification set in the TLD document. Eclipse releases typically lag behind up to a year in implementing newer servlet and JSP specifications. See this Eclipse bug for example.
In this case, your web application may run fine in the latest version of Tomcat, but Eclipse may still complain about a missing TLD. The short term solution (short of ignoring the error in Eclipse) is to bump down the JSP version to the one that your version of Eclipse supports.
Also, keep in mind the TLD version you are implementing. The tag names have changed slightly from v1.1 to v2.0 (i.e., info
is now description
on taglib
and is not a valid element under tag
, many of the element names now contain a hyphen). Eclipse has no tolerance for misspelled TLD tag names.
For compatibility with all browsers stick with .ico
.
.png is getting more and more support though as it is easier to create using multiple programs.
for .ico
<link rel="shortcut icon" href="http://example.com/myicon.ico" />
for .png, you need to specify the type
<link rel="icon" type="image/png" href="http://example.com/image.png" />
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:
//Store your XML Request in a variable
$input_xml = '<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>JFK</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<PreferredClass>E</PreferredClass>
<Eticket>true</Eticket>
<Clientid>777ClientID</Clientid>
<Clientpassword>*Your API Password</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>';
Now I've made a little changes in the above curl_setopt declaration as follows:
$url = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.
Use:
if [[ `command --help` ]]; then
echo "This command exists"
else
echo "This command does not exist";
fi
Put in a working switch, such as "--help" or "-v" in the if
check: if [[ command --help
]]; then
You could subclass ArrayList, and call Collections.sort(this) after any element is added - you would need to override two versions of add, and two of addAll, to do this.
Performance would not be as good as a smarter implementation which inserted elements in the right place, but it would do the job. If addition to the list is rare, the cost amortised over all operations on the list should be low.
You can use below command as you don't want file name but you want to search from all the files. Here are i am capturing "TEXT" form All the log files making sure that file name is not printed
grep -e TEXT *.log | cut -d' ' --complement -s -f1
grep with -e option is quite quick compared to other option as it is for PATTERN match
Modern browsers support vh and vw units, which are a percentage of the window viewport.
So you can have pure CSS borders as a percentage of the window size:
border: 5vw solid red;
Try this example and change window width; the border will change thickness as the window changes size. box-sizing: border-box;
may be useful too.