Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
Pandas is great for time series in general, and has direct support for date ranges.
import pandas as pd
daterange = pd.date_range(start_date, end_date)
You can then loop over the daterange to print the date:
for single_date in daterange:
print (single_date.strftime("%Y-%m-%d"))
It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range. See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps
The power of Pandas is really its dataframes, which support vectorized operations (much like numpy) that make operations across large quantities of data very fast and easy.
EDIT: You could also completely skip the for loop and just print it directly, which is easier and more efficient:
print(daterange)
As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)
Just for the future
we need to observe that [(ngModel)]="hero.name"
is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event"
.
So if we de-sugar code we would end up with:
<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">
or
<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">
If you inspect the above code you will notice that we end up with 2 ngModelChange
events and those need to be executed in some order.
Summing up: If you place ngModelChange
before ngModel
, you get the $event
as the new value, but your model object still holds previous value.
If you place it after ngModel
, the model will already have the new value.
After installing python3 with brew install python3
I was getting the error:
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
After typing brew link python3
the error was:
Linking /usr/local/Cellar/python/3.6.4_3... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
To solve the problem:
sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/*
brew link python3
After this, I could open python3 by typing python3
(From https://github.com/Homebrew/homebrew-core/issues/20985)
@RequestParam
is the HTTP GET
or POST
parameter sent by client, request mapping is a segment of URL which's variable:
http:/host/form_edit?param1=val1¶m2=val2
var1
& var2
are request params.
http:/host/form/{params}
{params}
is a request mapping. you could call your service like : http:/host/form/user
or http:/host/form/firm
where firm & user are used as Pathvariable
.
Yes, there is better. Check the stat
or the fstat
function
Update 2018-02-03 with Spring Boot 1.5.8.RELEASE.
In pom.xml, you need to tell Spring plugin when it is building that it is a war file by change package to war, like this:
<packaging>war</packaging>
Also, you have to excluded the embedded tomcat while building the package by adding this:
<!-- to deploy as a war in tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
The full runable example is in here https://www.surasint.com/spring-boot-create-war-for-tomcat/
The solution is somewhat simple; once you have deleted the row from the datagrid (Your code ONLY removes the row from the grid and NOT the datasource) then you do not need to do anything else. As you are doing a databind operation immediately after, without updating the datasource, you are re-adding all the rows from the source to the gridview control (including the row removed from the grid in the previous statement).
To simply delete from the grid without a datasource then just call the delete operation on the grid and that is all you need to do... no databinding is needed after that.
Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/
var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);
function markerOnClick(e)
{
alert("hi. you clicked the marker at " + e.latlng);
}
If you are not very offended by the GOTO
keyword, it can be used to simulate a DO
/ WHILE
in T-SQL. Consider the following rather nonsensical example written in pseudocode:
SET I=1
DO
PRINT I
SET I=I+1
WHILE I<=10
Here is the equivalent T-SQL code using goto:
DECLARE @I INT=1;
START: -- DO
PRINT @I;
SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10
Notice the one to one mapping between the GOTO
enabled solution and the original DO
/ WHILE
pseudocode. A similar implementation using a WHILE
loop would look like:
DECLARE @I INT=1;
WHILE (1=1) -- DO
BEGIN
PRINT @I;
SET @I+=1;
IF NOT (@I<=10) BREAK; -- WHILE @I<=10
END
Now, you could of course rewrite this particular example as a simple WHILE
loop, since this is not such a good candidate for a DO
/ WHILE
construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO
/ WHILE
are rare.
REPEAT / UNTIL, anyone (does NOT work in T-SQL)?
SET I=1
REPEAT
PRINT I
SET I=I+1
UNTIL I>10
... and the GOTO
based solution in T-SQL:
DECLARE @I INT=1;
START: -- REPEAT
PRINT @I;
SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10
Through creative use of GOTO
and logic inversion via the NOT
keyword, there is a very close relationship between the original pseudocode and the GOTO
based solution. A similar solution using a WHILE
loop looks like:
DECLARE @I INT=1;
WHILE (1=1) -- REPEAT
BEGIN
PRINT @I;
SET @I+=1;
IF @I>10 BREAK; -- UNTIL @I>10
END
An argument can be made that for the case of the REPEAT
/ UNTIL
, the WHILE
based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.
If it wasn't for all of the disdain around the use of GOTO
, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.
Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO
.
Actually, casting doesn't always work. If the object is not an instanceof
the class you're casting it to you will get a ClassCastException
at runtime.
convert to Array
var array = like.ToArray();
var first = array[0];
To subset by column index (to avoid typing their names) you can do
dt[, .SD, .SDcols = -c(1:3, 5L)]
result seems ok
V4 V6 V7 V8 V9 V10
1: 0.51500037 0.919066234 0.49447244 0.19564261 0.51945102 0.7238604
2: 0.36477648 0.828889808 0.04564637 0.20265215 0.32255945 0.4483778
3: 0.10853112 0.601278633 0.58363636 0.47807015 0.58061000 0.2584015
4: 0.57569100 0.228642846 0.25734995 0.79528506 0.52067802 0.6644448
5: 0.07873759 0.840349039 0.77798153 0.48699653 0.98281006 0.4480908
6: 0.31347303 0.670762371 0.04591664 0.03428055 0.35916057 0.1297684
7: 0.45374290 0.957848949 0.99383496 0.43939774 0.33470618 0.9429592
8: 0.99403107 0.009750809 0.78816609 0.34713435 0.57937680 0.9227709
9: 0.62776909 0.400467655 0.49433474 0.81536420 0.01637135 0.4942351
10: 0.10318372 0.177712847 0.27678497 0.59554454 0.29532020 0.7117959
It's simple. Just do this:
#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
//now you can access argList[n]
}
@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.
Either set $/
to undef
(see jrockway's answer) or just concatenate all the file's lines:
$content = join('', <$fh>);
It's recommended to use scalars for filehandles on any Perl version that supports it.
You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.
Read all file content. Make a replacement with String.Replace
. Write content back to file.
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);
By the way, if you use Bootstrap, you can just use this variant:
.form-control {
font-size: 16px;
}
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
Within your <jre location>\lib\security\java.policy
try adding:
grant {
permission java.security.AllPermission;
};
And see if it allows you. If so, you will have to add more granular permissions.
See:
Java 8 Documentation for java.policy files
and
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html
You can use this function:
function createStringArray(arr, prop) {
var result = [];
for (var i = 0; i < arr.length; i += 1) {
result.push(arr[i][prop]);
}
return result;
}
Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.
Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.
It's worth to mention that using concerns is considered bad idea by many.
Some reasons:
include
method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.Concerns are easy way to shoot yourself in the leg, be careful with them.
swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry
Here's a checklist guide to debug not running cronjobs:
ps ax | grep cron
and look for cron.service cron start
or service cron restart
* * * * * /bin/echo "cron works" >> /tmp/file
/tmp
which does not currently exist should always be writable.2>&1
to include standard error as well as standard output, or separately output standard error to another file with 2>>/tmp/errors
/var/log/cron.log
or /var/log/messages
for errors.grep CRON /var/log/syslog
/var/log/cron
chmod +x /var/www/app/cron/do-stuff.php
30 1 * * * command > /dev/null 2>&1
>/dev/null 2>&1
altogether; or perhaps redirect to a file in a location where you have write access: >>cron.out 2>&1
will append standard output and standard error to cron.out
in the invoking user's home directory./etc/default/cron
EXTRA_OPTS="-L 2"
service cron restart
tail -f /var/log/syslog
to see the scripts executed/etc/rsyslog.d/50-default.conf
cron.crit /var/log/cron.log
sudo /etc/init.d/rsyslog reload
/var/log/cron.log
and look for detailed error output# Minute Hour Day of Month Month Day of Week User Command
# (0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat)
0 2 * * * root /usr/bin/find
This syntax is only correct for the root
user. Regular user crontab
syntax doesn't have the User field (regular users aren't allowed to run code as any other user);
# Minute Hour Day of Month Month Day of Week Command
# (0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat)
0 2 * * * /usr/bin/find
crontab -l
crontab -e
, for a specific user: crontab -e -u agentsmith
crontab -r
This happens because in r6 it shows an error when you try to extend private styles.
Refer to this link
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
This is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.
So here is the answer to that:
if %ERRORLEVEL% NEQ 0 exit %ERRORLEVEL%
I use setdefault()
when I want a default value in an OrderedDict
. There isn't a standard Python collection that does both, but there are ways to implement such a collection.
From iOS 11 Photos framework allows to add animated Gifs playback.
Sample app can be dowloaded here
More info about animated Gifs playback (starting from 13:35 min): https://developer.apple.com/videos/play/wwdc2017/505/
As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget
in this way.
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
I then can declare the event as KonvaMouseEvent
in my onclick MouseEventHandler function.
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.
I would like to suggest yet another alternative that I find the cleanest, but it requires react-redux
or something simular - also I'm using a few other fancy features along the way:
// actions.js
export const someAction = (items) => ({
type: 'SOME_ACTION',
payload: {items},
});
// Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction}) => (<div
onClick={boundSomeAction}
/>);
const mapState = ({otherReducer: {items}}) => ({
items,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => mappedDispatches.someAction(mappedState.items),
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
// (with other mapped state or dispatches) Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction, otherAction, otherMappedState}) => (<div
onClick={boundSomeAction}
onSomeOtherEvent={otherAction}
>
{JSON.stringify(otherMappedState)}
</div>);
const mapState = ({otherReducer: {items}, otherMappedState}) => ({
items,
otherMappedState,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
otherAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
const {items, ...remainingMappedState} = mappedState;
const {someAction, ...remainingMappedDispatch} = mappedDispatch;
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => someAction(items),
...remainingMappedState,
...remainingMappedDispatch,
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
If you want to reuse this you'll have to extract the specific mapState
, mapDispatch
and mergeProps
into functions to reuse elsewhere, but this makes dependencies perfectly clear.
if(TextUtils.isEmpty(firstName.getText().toString()){
firstName.setError("TEXT ERROR HERE");
}
Or you can also use TextInputLayout which has some useful method and some user friendly animation
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
This is a take on Mike W's answer:
internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
if (returnLastDayOfMonth) return lastDayOfLastMonth;
return firstDayOfThisMonth.AddMonths(-1);
}
You can call it like so:
dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
use
python manage.py dumpdata
then look at the end you will find the user name
Admittedly, my solution wouldn't work for negative integers, but it will extract all positive integers from input text containing integers. It makes use of numeric_only
locale:
int main() {
int num;
std::cin.imbue(std::locale(std::locale(), new numeric_only()));
while ( std::cin >> num)
std::cout << num << std::endl;
return 0;
}
Input text:
the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
Output integers:
5
25
7987
78
9878
The class numeric_only
is defined as:
struct numeric_only: std::ctype<char>
{
numeric_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
return &rc[0];
}
};
Complete online demo : http://ideone.com/dRWSj
You can use string formatting:
>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'
But this is removed in Python 3, you should use "str.format()":
>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'
What I use everywhere :
Runtime.getRuntime().exec("pm clear me.myapp");
Executing above piece of code closes application and removes all databases and shared preferences
Usually, we define classes for this.
class XClass( object ):
def __init__( self ):
self.myAttr= None
x= XClass()
x.myAttr= 'magic'
x.myAttr
However, you can, to an extent, do this with the setattr
and getattr
built-in functions. However, they don't work on instances of object
directly.
>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'
They do, however, work on all kinds of simple classes.
class YClass( object ):
pass
y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr
for f in `find`; do mv -v "$f" "`echo $f | tr '[A-Z]' '[a-z]'`"; done
<form id="myform">
<input type="textbox" id="field"/>
<input type="button" value="submit">
</form>
<script>
$(function () {
$("#field").keyup(function (event) {
if (event.which === 13) {
document.myform.submit();
}
}
});
</script>
Use the ngOnChanges()
lifecycle method in your component.
ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.
Here are the Docs.
just add dateFormat:'yy-mm-dd'
to your .datepicker({})
settings, your .datepicker({})
can look something like this
$( "#datepicker" ).datepicker({
showButtonPanel: true,
changeMonth: true,
dateFormat: 'yy-mm-dd'
});
});
</script>
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789
I found a simple way to fix that problem. At binding datagridview you've just done: datagridview.DataSource = dataSetName.Tables["TableName"];
If you code like:
datagridview.DataSource = dataSetName;
datagridview.DataMember = "TableName";
the datagridview will never load data again when filtering.
Eventually I used
db.my_collection.find({moop: {$exists: true}}).forEach(function(obj) {
obj.moop = new NumberInt(obj.moop);
db.my_collection.save(obj);
});
to turn moop
from string to integer in my_collection following the example in Simone's answer MongoDB: How to change the type of a field?.
I typically use something like this:
if exists (select * from dbo.sysobjects
where id = object_id(N'dbo.MyView') and
OBJECTPROPERTY(id, N'IsView') = 1)
drop view dbo.MyView
go
create view dbo.MyView [...]
If someone can show me an example of something that can be done with an
IntentService
and can not be done with aService
and the other way around.
By definition, that is impossible. IntentService
is a subclass of Service
, written in Java. Hence, anything an IntentService
does, a Service
could do, by including the relevant bits of code that IntentService
uses.
Starting a service with its own thread is like starting an IntentService. Is it not?
The three primary features of an IntentService
are:
the background thread
the automatic queuing of Intent
s delivered to onStartCommand()
, so if one Intent
is being processed by onHandleIntent()
on the background thread, other commands queue up waiting their turn
the automatic shutdown of the IntentService
, via a call to stopSelf()
, once the queue is empty
Any and all of that could be implemented by a Service
without extending IntentService
.
There's this bug in the latest version of pandas (pandas 0.23) that gives you an error on importing pandas.
But this can be easily fixed by installing an earlier version of pandas (pandas 0.22) using the command pip install pandas==0.22
on Windows Command Prompt.
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
.show() and .hide() modify the css display rule. I think you want:
$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element
Both the two most upvoted answers are wrong. It should have nothing to do with "store different/multiple languages". You can support Spanish characters like ñ
and English, with just common varchar
field and Latin1_General_CI_AS
COLLATION
, e.g.
Short Version
You should use NVARCHAR
/NCHAR
whenever the ENCODING
, which is determined by COLLATION
of the field, doesn't support the characters needed.
Also, depending on the SQL Server version, you can use specific COLLATIONs
, like Latin1_General_100_CI_AS_SC_UTF8
which is available since SQL Server 2019. Setting this collation on a VARCHAR
field (or entire table/database), will use UTF-8
ENCODING
for storing and handling the data on that field, allowing fully support UNICODE
characters, and hence any languages embraced by it.
To FULLY UNDERSTAND:
To fully understand what I'm about to explain, it's mandatory to have the concepts of UNICODE
, ENCODING
and COLLATION
all extremely clear in your head. If you don't, then first take a look below at my humble and simplified explanation on "What is UNICODE, ENCODING, COLLATION and UTF-8, and how they are related" section and supplied documentation links. Also, everything I say here is specific to Microsoft SQL Server
, and how it stores and handles data in char
/nchar
and varchar
/nvarchar
fields.
Let's say we wanna store a peculiar text on our MSSQL Server database. It could be an Instagram comment as "I love stackoverflow! ".
The plain English part would be perfectly supported even by ASCII, but since there are also an emoji, which is a character specified in the UNICODE
standard, we need an ENCODING
that supports this Unicode character.
MSSQL Server uses the COLLATION
to determine what ENCODING
is used on char
/nchar
/varchar
/nvarchar
fields. So, differently than a lot think, COLLATION
is not only about sorting and comparing data, but also about ENCODING
, and by consequence: how our data will be stored!
So, HOW WE KNOW WHAT IS THE ENCODING USED BY OUR COLLATION? With this:
SELECT COLLATIONPROPERTY( 'Latin1_General_CI_AI' , 'CodePage' ) AS [CodePage]
--returns 1252
This simple SQL returns the Windows Code Page
for a COLLATION
. A Windows Code Page
is nothing more than another mapping to ENCODINGs
. For the Latin1_General_CI_AI
COLLATION
it returns the Windows Code Page
code 1252
, that maps to Windows-1252
ENCODING
.
So, for a varchar
column, with Latin1_General_CI_AI
COLLATION
, this field will handle its data using the Windows-1252
ENCODING
, and only correctly store characters supported by this encoding.
If we check the Windows-1252 ENCODING
specification Character List for Windows-1252, we will find out that this encoding won't support our emoji character. And if we still try it out:
OK, SO HOW CAN WE SOLVE THIS?? Actually, it depends, and that is GOOD!
NCHAR
/NVARCHAR
Before SQL Server 2019 all we had was NCHAR
and NVARCHAR
fields. Some say they are UNICODE
fields. THAT IS WRONG!. Again, it depends on the field's COLLATION
and also SQLServer Version.
Microsoft's "nchar and nvarchar (Transact-SQL)" documentation specifies perfectly:
Starting with SQL Server 2012 (11.x), when a Supplementary Character (SC) enabled collation is used, these data types store the full range of Unicode character data and use the UTF-16 character encoding. If a non-SC collation is specified, then these data types store only the subset of character data supported by the UCS-2 character encoding.
In other words, if we use SQL Server older that 2012, like SQL Server 2008 R2 for example, the ENCODING
for those fields will use UCS-2 ENCODING
which support a subset of UNICODE
. But if we use SQL Server 2012 or newer, and define a COLLATION
that has Supplementary Character
enabled, than with our field will use the UTF-16
ENCODING
, that fully supports UNICODE
.
BUT WHAIT, THERE IS MORE! WE CAN USE UTF-8 NOW!!
CHAR
/VARCHAR
Starting with SQL Server 2019, WE CAN USE CHAR
/VARCHAR
fields and still fully support UNICODE
using UTF-8
ENCODING
!!!
From Microsoft's "char and varchar (Transact-SQL)" documentation:
Starting with SQL Server 2019 (15.x), when a UTF-8 enabled collation is used, these data types store the full range of Unicode character data and use the UTF-8 character encoding. If a non-UTF-8 collation is specified, then these data types store only a subset of characters supported by the corresponding code page of that collation.
Again, in other words, if we use SQL Server older that 2019, like SQL Server 2008 R2 for example, we need to check the ENCODING
using the method explained before. But if we use SQL Server 2019 or newer, and define a COLLATION
like Latin1_General_100_CI_AS_SC_UTF8
, then our field will use UTF-8
ENCODING
which is by far the most used and efficient encoding that supports all the UNICODE
characters.
Bonus Information:
Regarding the OP's observation on "I have seen that most of the European languages (German, Italian, English, ...) are fine in the same database in VARCHAR columns", I think it's nice to know why it is:
For the most common COLLATIONs
, like the default ones as Latin1_General_CI_AI
or SQL_Latin1_General_CP1_CI_AS
the ENCODING
will be Windows-1252
for varchar
fields. If we take a look on it's documentation, we can see that it supports:
English, Irish, Italian, Norwegian, Portuguese, Spanish, Swedish. Plus also German, Finnish and French. And Dutch except the ? character
But as I said before, it's not about language, it's about what characters do you expect to support/store, as shown in the emoji example, or some sentence like "The electric resistance of a lithium battery is 0.5O" where we have again plain English, and a Greek letter/character "omega" (which is the symbol for resistance in ohms), which won't be correctly handled by Windows-1252
ENCODING
.
Conclusion:
So, there it is! When use char
/nchar
and varchar
/nvarchar
depends on the characters that you want to support, and also the version of your SQL Server that will determines which COLLATIONs
and hence the ENCODINGs
you have available.
What is UNICODE, ENCODING, COLLATION and UTF-8, and how they are related
Note: all the explanations below are simplifications. Please, refer to the supplied documentation links to know all the details about those concepts.
UNICODE
- Is a standard, a convention, that aims to regulate all the characters in a unified and organized table. In this table, every character has an unique number. This number is commonly called character's code point
.
UNICODE IS NOT AN ENCODING!
ENCODING
- Is a mapping between a character and a byte/bytes sequence. So a encoding is used to "transform" a character to bytes and also the other way around, from bytes to a character. Among the most popular ones are UTF-8
, ISO-8859-1
, Windows-1252
and ASCII
. You can think of it as a "conversion table" (i really simplified here).
COLLATION
- That one is important. Even Microsoft's documentation doesn't let this clear as it should be. A Collation specifies how your data would be sorted, compared, AND STORED!. Yeah, I bet you was not expecting for that last one, right!? The collations on SQL Server
determines too what would be the ENCODING
used on that particular char
/nchar
/varchar
/nvarchar
field.
ASCII ENCODING
- Was one of the firsts encodings. It is both the character table (like an own tiny version of UNICODE
) and its byte mappings. So it doesn't map a byte to UNICODE
, but map a byte to its own character's table. Also, it always use only 7bits, and supported 128 different characters. It was enough to support all English letters upper and down cased, numbers, punctuation and some other limited number of characters. The problem with ASCII is that since it only used 7bits and almost every computer was 8bits at the time, there were another 128 possibilities of characters to be "explored", and everybody started to map this "available" bytes to its own table of characters, creating a lot of different ENCODINGs
.
UTF-8 ENCODING
- This is another ENCODING
, one of the most (if not the most) used ENCODING
around. It uses variable byte width (one character can be from 1 to 6 bytes long, by specification) and fully supports all UNICODE
characters.
Windows-1252 ENCODING
- Also one of the most used ENCODING
, it's widely used on SQL Server. It's fixed-size, so every one character is always 1byte. It also supports a lot of accents, from various languages but doesn't support all existing, nor supports UNICODE
. That's why your varchar
field with a common collation like Latin1_General_CI_AS
supports á
,é
,ñ
characters, even that it isn't using a supportive UNICODE
ENCODING
.
Resources:
https://blog.greglow.com/2019/07/25/sql-think-that-varchar-characters-if-so-think-again/
https://medium.com/@apiltamang/unicode-utf-8-and-ascii-encodings-made-easy-5bfbe3a1c45a
https://www.johndcook.com/blog/2019/09/09/how-utf-8-works/
https://www.w3.org/International/questions/qa-what-is-encoding
https://en.wikipedia.org/wiki/List_of_Unicode_characters
https://www.fileformat.info/info/charset/windows-1252/list.htm
https://docs.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/statements/windows-collation-name-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/statements/sql-server-collation-name-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/relational-databases/collations/collation-and-unicode-support?view=sql-server-ver15#SQL-collations
SQL Server default character encoding
https://en.wikipedia.org/wiki/Windows_code_page
I ran into the same problem because I set the http_proxy and https_proxy environment variables. But occasionally, I connect to a different network and need to bypass the proxy temporarily. The easiest way to do this (without changing the environment variables) is:
curl --noproxy '*' stackoverflow.com
From the manual: "The only wildcard is a single * character, which matches all hosts, and effectively disables the proxy."
The * character is quoted so that it is not erroneously expanded by the shell.
AttendStar created a free add-on that suppresses the print dialog box and removes all headers and footers for most versions of Firefox.
https://addons.mozilla.org/en-US/firefox/addon/attendprint/
With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.
Work out the solution according to what you want...
There are two things that getResource
/getResourceAsStream()
will get from the class it is called on...
So if you do
this.getClass().getResource("foo.txt");
it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.
this.getClass().getResource("/x/y/z/foo.txt")
will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).
Thread.currentThread().getContextClassLoader().getResource(name)
will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)
System.class.getResource(name)
Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).
Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
Lots of hard ways to do an easy thing:
<form name="foo" onsubmit="return false">
alert(xml.data[0].city);
use xml.data["Data"][0].city instead
If you are using Linux, these settings are available using /usr/bin/jcontrol
(or your path setting to get the current Java tools). You can also edit the files in ~/.java/deployment/deployment.properties
to set "deployment.security.level=MEDIUM".
Surprisingly, this information is not readily available from the Oracle web site. I miss java.sun.com...
Since there are no limits to the length of text in a data attribute, use data attributes! And then you can use regular css selectors to select your element(s) like the OP wants.
for (const element of document.querySelectorAll("*")) {_x000D_
element.dataset.myInnerText = element.innerText;_x000D_
}_x000D_
_x000D_
document.querySelector("*[data-my-inner-text='Different text.']").style.color="blue";
_x000D_
<div>SomeText, text continues.</div>_x000D_
<div>Different text.</div>
_x000D_
Ideally you do the data attribute setting part on document load and narrow down the querySelectorAll selector a bit for performance.
Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.
I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home
There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.
If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:
<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>'
type="text/javascript"></script>
In Kotlin
evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
doTheLoginWork()
}
true
}
Partial Xml Code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginUserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="actionDone"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
Here is a slight improvement to the given thread-based solution.
The code below supports exceptions:
def runFunctionCatchExceptions(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
except Exception, message:
return ["exception", message]
return ["RESULT", result]
def runFunctionWithTimeout(func, args=(), kwargs={}, timeout_duration=10, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = runFunctionCatchExceptions(func, *args, **kwargs)
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
if it.result[0] == "exception":
raise it.result[1]
return it.result[1]
Invoking it with a 5 second timeout:
result = timeout(remote_calculate, (myarg,), timeout_duration=5)
Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.
For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.
foreach (var strServer in listServer)
{
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
if (regCurrentUser == null)
throw new ApplicationException("Not found registry SubKey ...");
if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
throw new ApplicationException("Not found value in SubKey ...");
}
catch (ApplicationException appEx)
{
Console.WriteLine(appEx);
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
}
catch(Exception ex)
{
Console.WriteLine($"{ex} Pipec kakoito ...");
}
}
}
I'm going to have to say curl http://127.0.0.1:8000 -o outfile
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
Yes the workaround shown in all answer is correct , that is we need to customize the linear layout manager to calculate the height of its child items dynamically at run time. But all answers not working as expected .Please the below answer for custom layout manger with all orientation support.
public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private final RecyclerView view;
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
super(context);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
super(view.getContext());
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
super(view.getContext(), orientation, reverseLayout);
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
public void setOverScrollMode(int overScrollMode) {
if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
if (this.view == null) throw new IllegalStateException("view == null");
this.overScrollMode = overScrollMode;
ViewCompat.setOverScrollMode(view, overScrollMode);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSize, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (hasHeightSize && height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSize, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (hasWidthSize && width >= widthSize) {
break;
}
}
}
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
if (hasWidthSize) {
width = Math.min(width, widthSize);
}
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
if (hasHeightSize) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
final View child;
try {
child = recycler.getViewForPosition(position);
} catch (IndexOutOfBoundsException e) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
return;
}
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
makeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
calculateItemDecorationsForChild(child, tmpRect);
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
// as view is recycled let's not keep old measured values
makeInsetsDirty(p);
recycler.recycleView(child);
}
private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
if (!canMakeInsetsDirty) {
return;
}
try {
if (insetsDirtyField == null) {
insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
insetsDirtyField.setAccessible(true);
}
insetsDirtyField.set(p, true);
} catch (NoSuchFieldException e) {
onMakeInsertDirtyFailed();
} catch (IllegalAccessException e) {
onMakeInsertDirtyFailed();
}
}
private static void onMakeInsertDirtyFailed() {
canMakeInsetsDirty = false;
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
}
}
}
My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were
S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class
My code contained the following line
System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());
First, I had to move to the classpath directory
cd /D "S:\Accessibility\tools\src\test\java"
Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.
set classpath=%classpath%;.;..\..\..\src\main\resources;
Then, I had to run java using the classname.
java com.accessibility.HelloWorld
Possible in IE and chrome although it does not work in firefox:
<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>
<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
In Python 3 (I haven't tried this in Python 2), you can also simply do
with open('output.csv','w',newline='') as f:
writer=csv.writer(f)
writer.writerow(mystuff)
...
as per documentation.
More on this in the doc's footnote:
If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.
Another possible problem is that the csv file contains a byte order mark "FEFF". The byte order mark is intended to detect whether the file has been moved from a system using big endian or little endian byte ordering to a system of the opposite endianness. https://en.wikipedia.org/wiki/Byte_order_mark
Removing the "FEFF" byte order mark using a hex editor should allow Excel to read the file.
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
Can try like this
var code = "<script></" + "script>";
$("#someElement").append(code);
The only reason you can't do "<script></script>"
is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.
I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image"
android:layout_alignParentRight="true"
android:paddingRight="4dp" />
<TextView
android:id="@+id/title"
android:layout_toLeftOf="@id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="23sp"
android:maxLines="1" />
<TextView
android:id="@+id/subtitle"
android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assuming you have a custom class like this
public class CustomClass {
private long id;
private String title, subtitle, picture;
public CustomClass () {
}
public CustomClass (long id, String title, String subtitle, String picture) {
this.id = id;
this.title= title;
this.subtitle= subtitle;
this.picture= picture;
}
//add getters and setters
}
And a CustomAdapter.java
uses the xml-layout
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int resource;
private LayoutInflater inflater;
public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever
super(context, R.layout.customlistviewitem, values);
this.context = context;
this.resource = R.layout.customlistview;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = (RelativeLayout) inflater.inflate(resource, null);
CustomClass item = (CustomClass) getItem(position);
TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
ImageView imageview = (ImageView) convertView.findViewById(R.id.image);
//fill the textviews and imageview with the values
textviewTitle = item.getTtile();
textviewSubtitle = item.getSubtitle();
if (item.getAfbeelding() != null) {
int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
}
imageview.setImageDrawable(image);
return convertView;
}
}
Did you manage to do it? Feel free to ask if you want more info on something :)
EDIT: Changed the adapter to suit a List instead of just a List
Using a template trigger:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="White"></Setter>
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The ast.literal_eval
function comes close, but it will expect the string to be properly quoted first.
Of course Python's interpretation of backslash escapes depends on how the string is quoted (""
vs r""
vs u""
, triple quotes, etc) so you may want to wrap the user input in suitable quotes and pass to literal_eval
. Wrapping it in quotes will also prevent literal_eval
from returning a number, tuple, dictionary, etc.
Things still might get tricky if the user types unquoted quotes of the type you intend to wrap around the string.
The difference between pointers and references is quite simple: a pointer can be null, a reference can not.
Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).
Here it looks like references are more appropriate.
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
In short: It's a shorthand notation for a mathematical hack.
Long explanation:
You can't do a cross product with vectors in 2D space. The operation is not defined there.
However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.
If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.
That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.
From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
I tried sudo apt install nginx-full. You will get all the required packages.
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add
Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays
Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours
Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds
Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes
Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths
Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds
Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks
Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears
Returns a new DateTime that adds the specified number of years to the value of this instance.
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
To let your shell expand the variable, you need to use double-quotes like
sed -i "s#12345678#$replace#g" file.txt
This will break if $replace
contain special sed
characters (#
, \
). But you can preprocess $replace
to quote them:
replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
sed -i "s#12345678#$replace_quoted#g" file.txt
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
The best solution is the word-spacing
property.
Add the <p>
in a container with a specific size (example 300px
) and after you have to add that size as the value in the word-spacing.
HTML
<div>
<p>Sentence Here</p>
</div>
CSS
div {
width: 300px;
}
p {
width: auto;
text-align: center;
word-spacing: 300px;
}
In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.
Here an example Codepen
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
The short answer
There is none. They are exactly the same.
The long answer
Both .htm and .html are exactly the same and will work in the same way. The choice is down to personal preference, provided you’re consistent with your file naming you won’t have a problem with either.
Depending on the configuration of the web server, one of the file types will take precedence over the other. This should not be an issue since it’s unlikely that you’ll have both index.htm and index.html sitting in the same folder.
We always use the shorter .htm for our file names since file extensions are typically 3 characters long.
AND MORE ON: http://www.sightspecific.com/~mosh/WWW_FAQ/ext.html or http://www.sightspecific.com/~mosh/WWW_FAQ/ext.htm
I think I should add this part here:
There is one single slight difference between .htm and .html files. Consider a path in your server like: mydomain.com/myfolder. If you create an index.htm file inside that folder and you open that like this:mydomain.com/myfolder/, it will goes crazy and spit out your files as it is in your server,
but if you create an index.html file in there and open that directory in your browser, it will load that file.
I tested this on my VPS and found this
Maybe you could somehow set your server to load index.htm files by default, but I guess the .html file is the default file type for browsers to open in each directory.
To list the largest directories from the current directory in human readable format:
du -sh * | sort -hr
A better way to restrict number of rows can be
du -sh * | sort -hr | head -n10
Where you can increase the suffix of -n
flag to restrict the number of rows listed
Sample:
[~]$ du -sh * | sort -hr
48M app
11M lib
6.7M Vendor
1.1M composer.phar
488K phpcs.phar
488K phpcbf.phar
72K doc
16K nbproject
8.0K composer.lock
4.0K README.md
It makes it more convenient to read :)
Yes, SELECT from table_schema could be very usefull for system administration. If you have lot of servers, databases, tables... sometimes you need to DROP or UPDATE bunch of elements. For example to create query for DROP all tables with prefix name "wp_old_...":
SELECT concat('DROP TABLE ', table_name, ';') FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = '*name_of_your_database*'
AND table_name LIKE 'wp_old_%';
Use Data.List.Split
, which uses split
:
[me@localhost]$ ghci
Prelude> import Data.List.Split
Prelude Data.List.Split> let l = splitOn "," "1,2,3,4"
Prelude Data.List.Split> :t l
l :: [[Char]]
Prelude Data.List.Split> l
["1","2","3","4"]
Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read }
Prelude Data.List.Split> let l2 = convert l
Prelude Data.List.Split> :t l2
l2 :: [Integer]
Prelude Data.List.Split> l2
[1,2,3,4]
I fixed this problem by increasing the amount of memory available to the vagrant VM where the database was located.
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
Below is my onload
event handler.
I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.
function onLoadDialog(frame) {
try {
var body = frame.contentDocument.body;
var $body = $(body);
var $frame = $(frame);
var contentDiv = frame.parentNode;
var $contentDiv = $(contentDiv);
var savedShow = $contentDiv.dialog('option', 'show');
var position = $contentDiv.dialog('option', 'position');
// disable show effect to enable re-positioning (UI bug?)
$contentDiv.dialog('option', 'show', null);
// show dialog, otherwise sizing won't work
$contentDiv.dialog('open');
// Maximize frame width in order to determine minimal scrollHeight
$frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
contentDiv.offsetWidth + frame.offsetWidth);
var minScrollHeight = body.scrollHeight;
var maxWidth = body.offsetWidth;
var minWidth = 0;
// decrease frame width until scrollHeight starts to grow (wrapping)
while (Math.abs(maxWidth - minWidth) > 10) {
var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
$body.css('width', width);
if (body.scrollHeight > minScrollHeight) {
minWidth = width;
} else {
maxWidth = width;
}
}
$frame.css('width', maxWidth);
// use maximum height to avoid vertical scrollbar (if possible)
var maxHeight = $contentDiv.dialog('option', 'maxHeight')
$frame.css('height', maxHeight);
$body.css('width', '');
// correct for vertical scrollbar (if necessary)
while (body.clientWidth < maxWidth) {
$frame.css('width', maxWidth + (maxWidth - body.clientWidth));
}
var minScrollWidth = body.scrollWidth;
var minHeight = Math.min(minScrollHeight, maxHeight);
// descrease frame height until scrollWidth decreases (wrapping)
while (Math.abs(maxHeight - minHeight) > 10) {
var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
$body.css('height', height);
if (body.scrollWidth < minScrollWidth) {
minHeight = height;
} else {
maxHeight = height;
}
}
$frame.css('height', maxHeight);
$body.css('height', '');
// reset widths to 'auto' where possible
$contentDiv.css('width', 'auto');
$contentDiv.css('height', 'auto');
$contentDiv.dialog('option', 'width', 'auto');
// re-position the dialog
$contentDiv.dialog('option', 'position', position);
// hide dialog
$contentDiv.dialog('close');
// restore show effect
$contentDiv.dialog('option', 'show', savedShow);
// open using show effect
$contentDiv.dialog('open');
// remove show effect for consecutive requests
$contentDiv.dialog('option', 'show', null);
return;
}
//An error is raised if the IFrame domain != its container's domain
catch (e) {
window.status = 'Error: ' + e.number + '; ' + e.description;
alert('Error: ' + e.number + '; ' + e.description);
}
};
No need to complicate things. With Bootstrap 4, you can simply align items horizontally inside a column using the margin auto class my-auto
<div class="col-md-6 my-auto">
<h3>Lorem ipsum.</h3>
</div>
Still, this can be done with the following steps:
send an https ajax request to your web-site (the same domain)
jQuery.ajax({
'url' : '//same_domain.com/ajax_receiver.php',
'type' : 'get',
'data' : {'foo' : 'bar'},
'success' : function(response) {
console.log('Successful request');
}
}).fail(function(xhr, err) {
console.error('Request error');
});
get ajax request, for example, by php, and make a CURL get request to any desired website via http.
use linslin\yii2\curl;
$curl = new curl\Curl();
$curl->get('http://example.com');
Based on the answers above I'm using this shorter one liner:
git remote prune origin | awk 'BEGIN{FS="origin/"};/pruned/{print $2}' | xargs -r git branch -d
Also, if you already pruned and have local dangling branches, then this will clean them up:
git branch -vv | awk '/^ .*gone/{print $1}' | xargs -r git branch -d
pip <command> --user
changes the scope of the current pip command to work on the current user account's local python package install location, rather than the system-wide package install location, which is the default.
This only really matters on a multi-user machine. Anything installed to the system location will be visible to all users, so installing to the user location will keep that package installation separate from other users (they will not see it, and would have to install it themselves separately to use it). Because there can be version conflicts, installing a package with dependencies needed by other packages can cause problems, so it's best not to push all packages a given user uses to the system install location.
--user
location. It will be installed to a different folder, that may or may not need to be added to the path, depending on the package and how it's used (many packages install command-line tools that must be on the path to run from a shell).--user
is preferred to using root/sudo or requiring administrator installation and affecting the Python environment of every user, except in cases of general packages that the administrator wants to make available to all users by default.
apt
, rather than pip
.venv
command in the Python VENV docs.The --user
option in an active venv/virtualenv environment will install to the local user python location (same as without a virtual environment).
Packages are installed to the virtual environment by default, but if you use --user
it will force it to install outside the virtual environments, in the users python script directory (in Windows, this currently is c:\users\<username>\appdata\roaming\python\python37\scripts
for me with Python 3.7).
However, you won't be able to access a system or user install from within virtual environment (even if you used --user
while in a virtual environment).
If you install a virtual environment with the --system-site-packages
argument, you will have access to the system script folder for python. I believe this included the user python script folder as well, but I'm unsure. However, there may be unintended consequences for this and it is not the intended way to use virtual environments.
You can find the location of the user install folder for python with python -m site --user-base
. I'm finding conflicting information in Q&A's, the documentation and actually using this command on my PC as to what the defaults are, but they are underneath the user home directory (~
shortcut in *nix, and c:\users\<username>
typically for Windows).
The --user
option is not a valid for every command. For example pip uninstall
will find and uninstall packages wherever they were installed (in the user folder, virtual environment folder, etc.) and the --user
option is not valid.
Things installed with pip install --user
will be installed in a local location that will only be seen by the current user account, and will not require root access (on *nix) or administrator access (on Windows).
The --user
option modifies all pip
commands that accept it to see/operate on the user install folder, so if you use pip list --user
it will only show you packages installed with pip install --user
.
Here is a production ready pure JavaScript solution:
<View styles={{backgroundColor: `the main color you want`}}>
<Image source={`A white to transparent gradient png`}>
</View>
Here is the source code of a npm package using this solution: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329
Here is the gradient palette screenshot of saturation and brightness using this npm package: https://github.com/flyskywhy/react-native-slider-color-picker
If you work in MVC 4, you can watch this solution, it worked for me.
Add the following Application_Error method to my Global.asax
:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
The controller itself is really simple:
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
Check the full source code of Mvc4CustomErrorPage at GitHub.
In my case the problem was I was trying to add same view multiple times to linear layout
View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
for (int i = 1; i <= totalCount; i++) {
parentLayout.addView(childView);
}
just initialize view every time to fix the issue
for (int i = 1; i <= totalCount; i++) {
View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
parentLayout.addView(childView);
}
Use the astype
method.
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
array([[1, 2],
[1, 2]])
TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise
Your particular example obfuscates some important distinctions between them:
Because you are error handling inside a promise chain, thrown exceptions get automatically converted to rejected promises. This may explain why they seem to be interchangeable - they are not.
Consider the situation below:
checkCredentials = () => {
let idToken = localStorage.getItem('some token');
if ( idToken ) {
return fetch(`https://someValidateEndpoint`, {
headers: {
Authorization: `Bearer ${idToken}`
}
})
} else {
throw new Error('No Token Found In Local Storage')
}
}
This would be an anti-pattern because you would then need to support both async and sync error cases. It might look something like:
try {
function onFulfilled() { ... do the rest of your logic }
function onRejected() { // handle async failure - like network timeout }
checkCredentials(x).then(onFulfilled, onRejected);
} catch (e) {
// Error('No Token Found In Local Storage')
// handle synchronous failure
}
Not good and here is exactly where Promise.reject
( available in the global scope ) comes to the rescue and effectively differentiates itself from throw
. The refactor now becomes:
checkCredentials = () => {
let idToken = localStorage.getItem('some_token');
if (!idToken) {
return Promise.reject('No Token Found In Local Storage')
}
return fetch(`https://someValidateEndpoint`, {
headers: {
Authorization: `Bearer ${idToken}`
}
})
}
This now lets you use just one catch()
for network failures and the synchronous error check for lack of tokens:
checkCredentials()
.catch((error) => if ( error == 'No Token' ) {
// do no token modal
} else if ( error === 400 ) {
// do not authorized modal. etc.
}
MS SQL Server has supported ANSI SQL FETCH FIRST
for many years now:
SELECT * FROM TABLE
ORDER BY ID DESC
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY
(Works with most modern databases.)
This works well enough for me :)
// deg2rad * degrees = radians
#define deg2rad (3.14159265/180.0)
// rad2deg * radians = degrees
#define rad2deg (180/3.14159265)
while condition is True:
stuff()
else:
stuff()
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
If you would like to prepend array (a1 with an array a2) you could use the following:
var a1 = [1, 2];
var a2 = [3, 4];
Array.prototype.unshift.apply(a1, a2);
console.log(a1);
// => [3, 4, 1, 2]
Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression
select datediff(dd,Invdate,'2009/01/31')+1 as DaysOld,
case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else
case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else
case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end
end
end
end
end
end as Bucket
from rm20090131atb
Just make sure you have an end statement for every case statement
Try
File.open("out.txt", "w") do |f|
f.write(data_you_want_to_write)
end
without using the
File.new "out.txt"
As others have correctly pointed out, the first part of the ternary needs to return true
or false
and in your question the return value is a jQuery object.
The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.
So with the CSS:
#blackbox {
background:pink;
width:10px;
height:10px;
}
The following jQuery will flip the colour:
var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));
C# has two "equals" concepts: Equals
and ReferenceEquals
. For most classes you will encounter, the ==
operator uses one or the other (or both), and generally only tests for ReferenceEquals
when handling reference types (but the string
Class is an instance where C# already knows how to test for value equality).
Equals
compares values. (Even though two separate int
variables don't exist in the same spot in memory, they can still contain the same value.)ReferenceEquals
compares the reference and returns whether the operands point to the same object in memory.Example Code:
var s1 = new StringBuilder("str");
var s2 = new StringBuilder("str");
StringBuilder sNull = null;
s1.Equals(s2); // True
object.ReferenceEquals(s1, s2); // False
s1 == s2 // True - it calls Equals within operator overload
s1 == sNull // False
object.ReferenceEquals(s1, sNull); // False
s1.Equals(sNull); // Nono! Explode (Exception)
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
Try Demo Here
var list ={}; var count= Object.keys(list).length;
In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable z is undefined as:
if(uemail === undefined)
{
}
I had an issue where I was trying to hide the form from a table cell element, but still show the forms submit-button. The problem was that the form element was still taking up an extra blank space, making the format of my table cell look weird. The display:none and visibility:hidden attributes didn't work because it would hide the submit button as well, since it was contained within the form I was trying to hide. The simple answer was to set the forms height to barely nothing using CSS
So,
CSS -
#formID {height:4px;}
worked for me.
The Python Magic library provides the functionality you need.
You can install the library with pip install python-magic
and use it as follows:
>>> import magic
>>> magic.from_file('iceland.jpg')
'JPEG image data, JFIF standard 1.01'
>>> magic.from_file('iceland.jpg', mime=True)
'image/jpeg'
>>> magic.from_file('greenland.png')
'PNG image data, 600 x 1000, 8-bit colormap, non-interlaced'
>>> magic.from_file('greenland.png', mime=True)
'image/png'
The Python code in this case is calling to libmagic beneath the hood, which is the same library used by the *NIX file
command. Thus, this does the same thing as the subprocess/shell-based answers, but without that overhead.
Generally, Push method is used to add elements at the end of an array.
Here, you have used the push method to an object and not an array which is 'order'.
Steps to debug...
Change the object into an empty array,
var order = [], stack = [];
Now you can use the push method for this array as usual.
To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.
var order = [], stack = [];
for(var i = 0; i<a.length; i++){
if(parseInt(a[i].daysleft) == 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) > 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) < 0){
order.push(a[i]);
}
}
seeing how the rules are fairly complicated, I'd suggest the following:
/^[a-z](\w*)[a-z0-9]$/i
match the whole string and capture intermediate characters. Then either with the string functions or the following regex:
/__/
check if the captured part has two underscores in a row. For example in Python it would look like this:
>>> import re
>>> def valid(s):
match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
if match is not None:
return match.group(1).count('__') == 0
return False
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace data_seniens
{
class Program
{
static void Main(string[] args)
{
//new list
float [] x=new float[]{11.25f,18.0f,20.0f,10.75f,9.50f, 11.25f, 18.0f, 20.0f, 10.75f, 9.50f };
//variable
float eat_sleep_area=x[1]+x[3];
//print
foreach (var VARIABLE in x)
{
if (VARIABLE < x[7])
{
Console.WriteLine(VARIABLE);
}
}
//keep app run
Console.ReadLine();
}
}
}
set ONE column's width to any value, i.e. width="*"
Use LoadXml Method of XmlDocument;
string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);
This also could be easiest way to add items in ListBox.
for (int i = 0; i < MyList.Count; i++)
{
listBox1.Items.Add(MyList.ElementAt(i));
}
Further improvisation of this code can add items at runtime.
I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.
However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
Demo
$( '.expand' ).click(function() {_x000D_
$( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
margin-left:auto;_x000D_
margin-right:auto;_x000D_
width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
height:20px;_x000D_
background-color:#CCC;_x000D_
display:block;_x000D_
border:#333 solid 1px;_x000D_
margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
float:right;_x000D_
height: 100%;_x000D_
padding-right:5px;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
width: 100%;_x000D_
height:100px; _x000D_
background-color:#0F3;_x000D_
margin-top: -2px;_x000D_
display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
http://api.jquery.com/toggle/
"Display or hide the matched elements."
This is much shorter in code than using show() and hide() methods.
Using Apache Commons Lang:
!StringUtils.isAlphanumeric(String)
Alternativly iterate over String's characters and check with:
!Character.isLetterOrDigit(char)
You've still one problem left:
Your example string "abcdefà" is alphanumeric, since à
is a letter. But I think you want it to be considered non-alphanumeric, right?!
So you may want to use regular expression instead:
String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);
$('tableName').find('tr').length
parentElement
is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.
In most cases, it is the same as parentNode
. The only difference comes when a node's parentNode
is not an element. If so, parentElement
is null
.
As an example:
document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element
document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null
(document.documentElement.parentNode === document); // true
(document.documentElement.parentElement === document); // false
Since the <html>
element (document.documentElement
) doesn't have a parent that is an element, parentElement
is null
. (There are other, more unlikely, cases where parentElement
could be null
, but you'll probably never come across them.)
Request.Url.PathAndQuery
should work perfectly, especially if you only want the relative Uri (but keeping querystrings)
Thanks to this post, I finally found the solution. Here is the code:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;
public class Main extends Activity {
private WebView mWebview ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("http://www.google.com");
setContentView(mWebview );
}
}
For those using Swift 3, the equivalent method for the accepted answer is:
movieArr.sorted { $0.Name < $1.Name }
CSS?
td {
padding-top: 2px;
padding-bottom: 2px;
}
You can also refine Hash::each
so it will support recursive enumeration. Here is my version of Hash::each
(Hash::each_pair
) with block and enumerator support:
module HashRecursive
refine Hash do
def each(recursive=false, &block)
if recursive
Enumerator.new do |yielder|
self.map do |key, value|
value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
yielder << [[key], value]
end
end.entries.each(&block)
else
super(&block)
end
end
alias_method(:each_pair, :each)
end
end
using HashRecursive
Here are usage examples of Hash::each
with and without recursive
flag:
hash = {
:a => {
:b => {
:c => 1,
:d => [2, 3, 4]
},
:e => 5
},
:f => 6
}
p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2
p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6
hash.each do |key, value|
puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6
hash.each(true) do |key, value|
puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6
hash.each_pair(recursive=true) do |key, value|
puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6
Here is example from the question itself:
hash = {
1 => ["a", "b"],
2 => ["c"],
3 => ["a", "d", "f", "g"],
4 => ["q"]
}
hash.each(recursive=false) do |key, value|
puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]
Also take a look at my recursive version of Hash::merge
(Hash::merge!
) here.
In python, bool(sequence)
is False
if the sequence is empty. Since strings are sequences, this will work:
cookie = ''
if cookie:
print "Don't see this"
else:
print "You'll see this"
Maybe just an OR operator |
could be enough for your problem:
String: foo,bar,baz
Regex: (foo)|(baz)
Result: ["foo", "baz"]
What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.
In my case, the problem was with the submodules. master
was merged with another branch which added a new submodule to the project. The branch I was trying to checkout didn't have it, that's why git was complaining about untracked files and none of the other suggested solutions worked for me. I forced the checkout to my new branch, and pulled master.
git checkout -f my_branch
git pull origin master
git submodule update --init
Try the below code-
mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
//delete success.
} else {
//delete failed.
}
We can mock list properly for foreach loop. Please find below code snippet and explanation.
This is my actual class method where I want to create test case by mocking list.
this.nameList
is a list object.
public void setOptions(){
// ....
for (String str : this.nameList) {
str = "-"+str;
}
// ....
}
The foreach loop internally works on iterator, so here we crated mock of iterator.
Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn()
, i.e. on hasNext()
we pass 1st true and on second call false, so that our loop will continue only two times. On next()
we just return actual return value.
@Test
public void testSetOptions(){
// ...
Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
Mockito.when(itr.hasNext()).thenReturn(true, false);
Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);
List mockNameList = Mockito.mock(List.class);
Mockito.when(mockNameList.iterator()).thenReturn(itr);
// ...
}
In this way we can avoid sending actual list to test by using mock of list.
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
If you wish more look at: http://developer.android.com/intl/pt-br/guide/topics/resources/string-resource.html#FormattingAndStyling
If you're going with Manoj's solution (https://stackoverflow.com/a/29509007/2024713) and still having the problem try switching off "Enable interactive mode" if available in your version of IntelliJ. It worked for me
u want select all data from database then u can try this:-
dbclassDataContext dc= new dbclassDataContext()
List<tableName> ObjectName= dc.tableName.ToList();
otherwise You can try this:-
var Registration = from reg in dcdc.GetTable<registration>() select reg;
and method Syntex :-
var Registration = dc.registration.Select(reg => reg);
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
The Best way is do not use any pairing code.
Instead of onClick
go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.
or see this link for better understanding
Below is code for the same:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
// **add this 2 line code**
Intent myIntent = new Intent(view.getContext(), Connect.class);
startActivityForResult(myIntent, 0);
finish();
}
};
Connect.java file is :
public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
private InputStream in;
byte[] arrayOfByte = new byte[4096];
int bytes;
public BluetoothDevice mDevice;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
try {
setup();
} catch (ZeoMessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ZeoMessageParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup() throws ZeoMessageException, ZeoMessageParseException {
// TODO Auto-generated method stub
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("**:**:**:**:**:**");// add device mac adress
try {
sock = zee.createRfcommSocketToServiceRecord(
UUID.fromString("*******************")); // use unique UUID
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connecting");
try {
sock.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connected");
try {
in = sock.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Listening...");
while (true) {
try {
bytes = in.read(arrayOfByte);
Log.d(TAG, "++++ Read "+ bytes +" bytes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Done: test()");
}}
private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
public static class LogBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
Log.d("ZeoReceiver", paramAnonymousIntent.toString());
Bundle extras = paramAnonymousIntent.getExtras();
for (String k : extras.keySet()) {
Log.d("ZeoReceiver", " Extra: "+ extras.get(k).toString());
}
}
};
private BluetoothSocket sock;
@Override
public void onDestroy() {
getApplicationContext().unregisterReceiver(receiver);
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
You have to add a MySQL jdbc driver to the classpath.
Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.
You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27
If you have an object that can be converted to {key: 'stringValue'}
pairs, you can use this shortcut to convert it:
this._Http.get(myUrlString, {params: {...myParamsObject}});
I just love the spread syntax!
That's right. You could try it in the interpreter like this:
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
You can use MutationObserver to track attribute changes including data-*
changes. For example:
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
attributes: true, _x000D_
attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
<div id='foo'></div>_x000D_
_x000D_
Replace hidden
with none
. See MDN reference.
Update: I added a fix for the OP's comment.
tar -czf workspace.tar.gz .
will indeed change the current directory, but why not place the file somewhere else?
tar -czf somewhereelse/workspace.tar.gz .
mv somewhereelse/workspace.tar.gz . # Update
we can also use
(.*?\n)*?
to match everything including newline without greedy
This will make the new line optional
(.*?|\n)*?
Here is the script in Python.
You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.
element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)
Do you want to get the number of rows?
SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName
You can do it with anchor tags using css3 :target
pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example
Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.
If the display of the div is block by default, you can just use .show()
and .hide()
, or even simpler, .toggle()
to toggle between visibility.
I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )
So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:
/var/log/apache2/error.log
In Case of password also we need to pass one more parameter
redis-cli -h host -p port -a password
You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
Try using MYSQLI_ASSOC instead MYSQL_ASSOC... usually the problem is solved changing that
Good luck!
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, .
, which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
Yes.
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyTextbox as New Textbox
With MyTextbox
.Size = New Size(100,20)
.Location = New Point(20,20)
End With
AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
Me.Controls.Add(MyTextbox)
'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.
End Sub
Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
'Write code here.
End Sub
The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:
$xml_reader = new XMLReader;
$xml_reader->open($feed_url);
// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');
// loop through the products
while ($xml_reader->name == 'product')
{
// load the current xml element into simplexml and we’re off and running!
$xml = simplexml_load_string($xml_reader->readOuterXML());
// now you can use your simpleXML object ($xml).
echo $xml->element_1;
// move the pointer to the next product
$xml_reader->next('product');
}
// don’t forget to close the file
$xml_reader->close();
An update of Mogsdad's solution:
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(function(r){return r[0].length>0});
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)
The difference is the amount of memory allocated to each integer, and how large a number they each can store.
I had the same problem with slash in url get param, in my case following php code works:
$value = "hello/world"
$value = str_replace('/', '/', $value;?>
$value = urlencode($value);?>
# $value is now hello%26%2347%3Bworld
I first replace the slash by html entity and then I do the url encoding.
Many times it does happen that cpan install command fails with the message like "make test had returned bad status, won't install without force"
In that case following is the way to install the module:
perl -MCPAN -e "CPAN::Shell->force(qw(install Foo::Bar));"
You don't need the AND
keyword. Here's the correct syntax of the UPDATE statement:
UPDATE
shop_category
SET
name = 'Secolul XVI - XVIII',
name_eng = '16th to 18th centuries'
WHERE
category_id = 4768
You can use arg(), as follow:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
For complete removal old Xcode 7 you should remove
/Applications/Xcode.app
/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
~/Library/Developer/Xcode
~/Library/Developer/CoreSimulator
The other option in this particular case would be to type the degree symbol: °
R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
What you were missing was the float: left; here is an example just done in the HTML
<div id="form">
<form action="" method="post" name="registration" class="register">
<fieldset>
<label for="Student" style="float: left">Name:</label>
<input name="Student" />
<label for="Matric_no" style="float: left">Matric number:</label>
<input name="Matric_no" />
<label for="Email" style="float: left">Email:</label>
<input name="Email" />
<label for="Username" style="float: left">Username:</label>
<input name="Username" />
<label for="Password" style="float: left">Password:</label>
<input name="Password" type="password" />
<input name="regbutton" type="button" class="button" value="Register" />
</fieldset>
</form>
The more efficient way to do this is to add a class to the labels and set the float: left; to the class in CSS
I think this simple code would work:
if(!(image_array<=0)){
//Specify function needed
}
just adding this snipped in the build.gradle also works fine
android {
compileSdkVersion 22
buildToolsVersion "23.0.0"
defaultConfig {
minSdkVersion 14 //lower than 14 doesn't support multidex
targetSdkVersion 22
**// Enabling multidex support.
**multiDexEnabled true****
}
}
You could also use the CountDownLatch
object like explained here.
You can use the clearfix
to do "layout preserving" the same way overflow: hidden
does.
.clearfix:before,
.clearfix:after {
content: ".";
display: block;
height: 0;
overflow: hidden;
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */
add class="clearfix"
class to the parent, and remove overflow: hidden;
Change the rule on your <a>
element from:
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
}?
to
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
width:100%;
text-align:center;
}?
Just add two new rules (width:100%;
and text-align:center;
). You need to make the anchor expand to take up the full width of the list item and then text-align center it.
in JQuery you can use: in class for Select Option:
$('.className').each(function(){
className.push($("option:selected",this).val().substr(1));
});
in class for text Value:
$('.className').each(function(){
className.push($(this).val().substr(1));
});
in ID for text Value:
$("#id").val().substr(1)
Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here: Bjax Demo
Instead of defining IMyTable
as in interface, try defining it as a class. In typescript you can use a class like an interface.
So for your example, define/generate your class like this:
export class IMyTable {
constructor(
public id = '',
public title = '',
public createdAt: Date = null,
public isDeleted = false
)
}
Use it as an interface:
export class SomeTable implements IMyTable {
...
}
Get keys:
const keys = Object.keys(new IMyTable());
As mentioned, ini4j can be used to achieve this. Let me show one other example.
If we have an INI file like this:
[header]
key = value
The following should display value
to STDOUT:
Ini ini = new Ini(new File("/path/to/file"));
System.out.println(ini.get("header", "key"));
Check the tutorials for more examples.
this worked for me
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
EDIT: I wanted to expand on this based on the comments.
const scrollTo = (ref) => {
if (ref /* + other conditions */) {
ref.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}
<div ref={scrollTo}>Item</div>
I typically see a 30% speed improvement for compute-intensive code on x86-64 compared to x86. This is most likely due to the fact that we have 16 x 64 bit general purpose registers and 16 x SSE registers instead of 8 x 32 bit general purpose registers and 8 x SSE registers. This is with the Intel ICC compiler (11.1) on an x86-64 Linux - results with other compilers (e.g. gcc), or with other operating systems (e.g. Windows), may be different of course.