The subversion program code is linked into the TortoiseSVN binary. You can install a compatible discrete version if you need to access the repository from the command line.
UPDATE: Recent versions of the TortoiseSVN package can install a discrete svn.exe in addition to the one linked into the GUI binary. It is located in the same bin directory where the main program is installed. In the installer, the command line tools need to be selected for this:
(If you have already installed TortoiseSVN, then rerun the installer and select "Modify")
First choose or create the key you want to use for pushing to Bitbucket. Let's say its public key is at ~/.ssh/bitbucket.pub
~/.ssh/config
: Host bitbucket.org
IdentityFile ~/.ssh/bitbucket
Do which sshpass
in your command line to get the absolute path to sshpass
and replace it in the bash script.
You should also probably do the same with the command
you are trying to run.
The problem might be that it is not finding it.
mystring = mystring.replace(/["']/g, "");
Some of the answers here imply that given a "package" directory (with or without an explicit __init__.py
file), containing a __main__.py
file, there is no difference between running that directory with the -m
switch or without.
The big difference is that without the -m
switch, the "package" directory is first added to the path (i.e. sys.path), and then the files are run normally, without package semantics.
Whereas with the -m
switch, package semantics (including relative imports) are honoured, and the package directory itself is never added to the system path.
This is a very important distinction, both in terms of whether relative imports will work or not, but more importantly in terms of dictating what will be imported in the case of unintended shadowing of system modules.
Example:
Consider a directory called PkgTest
with the following structure
:~/PkgTest$ tree
.
+-- pkgname
¦ +-- __main__.py
¦ +-- secondtest.py
¦ +-- testmodule.py
+-- testmodule.py
where the __main__.py
file has the following contents:
:~/PkgTest$ cat pkgname/__main__.py
import os
print( "Hello from pkgname.__main__.py. I am the file", os.path.abspath( __file__ ) )
print( "I am being accessed from", os.path.abspath( os.curdir ) )
from testmodule import main as firstmain; firstmain()
from .secondtest import main as secondmain; secondmain()
(with the other files defined similarly with similar printouts).
If you run this without the -m
switch, this is what you'll get. Note that the relative import fails, but more importantly note that the wrong testmodule has been chosen (i.e. relative to the working directory):
:~/PkgTest$ python3 pkgname
Hello from pkgname.__main__.py. I am the file ~/PkgTest/pkgname/__main__.py
I am being accessed from ~/PkgTest
Hello from testmodule.py. I am the file ~/PkgTest/pkgname/testmodule.py
I am being accessed from ~/PkgTest
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "pkgname/__main__.py", line 10, in <module>
from .secondtest import main as secondmain
ImportError: attempted relative import with no known parent package
Whereas with the -m switch, you get what you (hopefully) expected:
:~/PkgTest$ python3 -m pkgname
Hello from pkgname.__main__.py. I am the file ~/PkgTest/pkgname/__main__.py
I am being accessed from ~/PkgTest
Hello from testmodule.py. I am the file ~/PkgTest/testmodule.py
I am being accessed from ~/PkgTest
Hello from secondtest.py. I am the file ~/PkgTest/pkgname/secondtest.py
I am being accessed from ~/PkgTest
Note: In my honest opinion, running without -m
should be avoided. In fact I would go further and say that I would create any executable packages
in such a way that they would fail unless run via the -m
switch.
In other words, I would only import from 'in-package' modules explicitly via 'relative imports', assuming that all other imports represent system modules. If someone attempts to run your package without the -m
switch, the relative import statements will throw an error, instead of silently running the wrong module.
I created an extension method on ObjectStateEntry to be able to flag properties (of Entity Framework POCO classes) as modified in a type safe manner, since the default method only accepts a string. Here's my way of getting the name from the property:
public static void SetModifiedProperty<T>(this System.Data.Objects.ObjectStateEntry state, Expression<Func<T>> action)
{
var body = (MemberExpression)action.Body;
string propertyName = body.Member.Name;
state.SetModifiedProperty(propertyName);
}
You have to set the contentSize
property of the UIScrollView
. For example, if your UIScrollView
is 320 pixels wide (the width of the screen), then you could do this:
CGSize scrollableSize = CGSizeMake(320, myScrollableHeight);
[myScrollView setContentSize:scrollableSize];
The UIScrollView
will then only scroll vertically, because it can already display everything horizontally.
If you want to create and copy the content in a single shot, just use the SELECT
:
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
Hope that helps.
Additionally you will probably want to redirect user to the given in headers URL. So finally it will looks like this:
$.ajax({
//.... other definition
complete:function(xmlHttp){
if(xmlHttp.status.toString()[0]=='3'){
top.location.href = xmlHttp.getResponseHeader('Location');
}
});
UPD: Opps. Have the same task, but it not works. Doing this stuff. I'll show you solution when I'll find it.
Add this, I think it is what you're looking for:
<meta name = "format-detection" content = "telephone=no">
This can be done by using SUMPRODUCT
as well. Update the ranges as you see fit
=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)
A2:A7 = First name range
B2:B7 = Last Name Range
C2:C7 = Numbers Range
This will find all the names with the same first and last name and sum the numbers in your numbers column
["The", animal, action, "the", second_animal].join(" ")
is another way to do it.
You can do it with:
/etc/passwd
Edit the user home directory and then move the required files and directories to it:
cp/mv -r /home/$user/.bash* /home/newdir
.bash_profile
.ssh/
Set the correct permission
chmod -R $user:$user /home/newdir/.bash*
Since most of the other replies often get the formatting wrong (due to the piping), the safest thing to do is as follows:
add-content $YourMasterFile -value (get-content $SomeAdditionalFile)
I know you wanted to avoid reading the content of $SomeAdditionalFile into a variable, but in order to save for example your newline formatting i do not think there is proper way to do it without.
A workaround would be to loop through your $SomeAdditionalFile line by line and piping that into your $YourMasterFile. However this is overly resource intensive.
This may work for you:
Scenario 1: primitive types
string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};
if(!dictToUpdate.ContainsKey(keyToMatchInDict))
dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;
Scenario 2: The approach I used for a List as Value
int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...
if(!dictToUpdate.ContainsKey(keyToMatch))
dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
dictToUpdate[keyToMatch] = objInValueListToAdd;
Hope it's useful for someone in need of help.
27
is the code for the escape key. :)
This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.
It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.
In this fast changing world most of these link are obsolet.
Now you can use Google Drive Web APIs:
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
1. Change the INNER JOIN before the WHERE clause.
2. You have two WHEREs which is not allowed.
Try this:
SELECT table1.f_id FROM table1 INNER JOIN table2 ON (table2.f_id = table1.f_id AND table2.f_type = 'InProcess') WHERE table1.f_com_id = '430' AND table1.f_status = 'Submitted'
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
Under Security, add the principal as a "SQL user without login", make it own the schema with the same name as the principal and then in Membership make it db_owner.
There are a couple of reasons for this:
SQL doesn't typically allow you to reference column aliases in WHERE, GROUP BY or HAVING clauses. MySQL does support referencing column aliases in the GROUP BY and HAVING, but I stress that it will cause problems when porting such queries to other databases.
When in doubt, use the actual column name:
SELECT t.lat AS latitude
FROM poi_table t
WHERE t.lat < 500
I added a table alias to make it easier to see what is an actual column vs alias.
A computed column, like the one you see here:
SELECT *,
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
FROM poi_table
WHERE distance < 500;
...doesn't change that you can not reference a column alias in the WHERE clause. For that query to work, you'd have to use:
SELECT *,
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
FROM poi_table
WHERE ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) < 500;
Be aware that using a function on a column (IE: RADIANS(lat)
) will render an index useless, if one exists on the column.
Further on to @Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.
It seems pretty much a tie between:
int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
Split your date into year, month, and day components then use Date:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Date will take care of fixing the year.
Example of how to perform a INSERT INTO SELECT with a WHERE clause.
INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2
Update for Xcode 7.1, facing problem 27.10.15:
The new value in the Info.plist is "App Transport Security Settings". From there, this dictionary should contain:
Use dict.setdefault()
:
dic.setdefault(key,[]).append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
@param
won't affect the number. It's just for making javadocs.
More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
You can set the onClick
event in your custom adapter's getView
method..
check the link http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html
I've just get now the same issue with my video
<video preload="none" autoplay="autoplay" loop="loop">
<source src="Home_Teaser.mp4" type="video/mp4">
<source src="Home_Teaser" type="video/webm">
<source src="Home_Teaser.ogv" type="video/ogg">
</video>
After search, I've found a solution:
If I set "preload" attributes to "true" the video start normally
Use geom_text
, with aes
label. You can play with hjust, vjust
to adjust text position.
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +
geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)
If you use eclipse, maybe PyUML. Haven't used it, though.
I had a similar need for splitting CSV values from SQL insert statements.
In my case, I could assume that strings were wrapped in single quotations and numbers were not.
csv.split(/,((?=')|(?=\d))/g).filter(function(x) { return x !== '';});
For some probably obvious reason, this regex produces some blank results. I could ignore those, since any empty values in my data were represented as ...,'',...
and not ...,,...
.
You can also delete cookies without using jquery.cookie plugin:
document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
If you want to use the --prefix
or -p
arguments, but want to avoid having to use the environment's full path to activate it, you need to edit the .condarc
config file before you create the environment.
The .condarc
file is in the home directory; C:\Users\<user>
on Windows. Edit the values under the envs_dirs
key to include the custom path for your environment. Assuming the custom path is D:\envs
, the file should end up looking something like this:
ssl_verify: true
channels:
- defaults
envs_dirs:
- C:\Users\<user>\Anaconda3\envs
- D:\envs
Then, when you create a new environment on that path, its name will appear along with the path when you run conda env list
, and you should be able to activate it using only the name, and not the full path.
In summary, if you edit .condarc
to include D:\envs
, and then run conda env create -p D:\envs\myenv python=x.x
, then activate myenv
(or source activate myenv
on Linux) should work.
Hope that helps!
P.S. I stumbled upon this through trial and error. I think what happens is when you edit the envs_dirs
key, conda updates ~\.conda\environments.txt
to include the environments found in all the directories specified under the envs_dirs
, so they can be accessed without using absolute paths.
You could attach the image (as a pixmap) to a label then add that to your layout...
...
QPixmap image("blah.jpg");
QLabel *imageLabel = new QLabel();
imageLabel->setPixmap(image);
mainLayout.addWidget(imageLabel);
...
Apologies, this is using Jambi (Qt for Java) so the syntax is different, but the theory is the same.
This issue started occurring for me all of a sudden, so I was sure, there could be some other reason. On digging deep, it was a simple issue where I used http
in the BaseUrl of Retrofit instead of https
. So changing it to https
solved the issue for me.
.gitattributes
- is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.
You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml
for our branch.
We need to set the merge=foo
to config.xml
in .gitattributes
file.
merge=foo
tell git to use our(current branch) file, if a merge conflict occurs.
Add a .gitattributes
file at the root level of the repository
You can set up an attribute for confix.xml in the .gitattributes
file
<pattern> merge=foo
Let's take an example for config.xml
config.xml merge=foo
And then define a dummy foo
merge strategy with:
$ git config --global merge.foo.driver true
If you merge the stag
form dev
branch, instead of having the merge conflicts with the config.xml
file, the stag branch's config.xml preserves at whatever version you originally had.
for more reference: merge_strategies
I had the same issue where the project compiles fine (even after clean & build), but intellisense complains about missing references.
I tried everything from deleting the cache and disabling resharper, but nothing worked. In the end, I realized it was only a single project reference that showed intellisense errors.
My solution was to simply remove the reference to this project and add it again Everything worked as expected afterwards.
Make the left and right margins of your UL auto and assign it a width:
#headermenu ul {
margin: 0 auto;
width: 620px;
}
Edit: As kleinfreund has suggested, you can also center align the container and give the ul an inline-block display, but you then also have to give the LIs either a left float or an inline display.
#headermenu {
text-align: center;
}
#headermenu ul {
display: inline-block;
}
#headermenu ul li {
float: left; /* or display: inline; */
}
Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.
In the non-Express version of VS, the import libray name is specfied in the project settings here:
Configuration Properties/Linker/Advanced/Import Library
I assume it's the same in Express (if it even provides the ability to configure the name).
Many people have answered the mechanical details already, but it's worth noting: This is a poor design choice, by Java.
Java's asList
method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add
method, it throws an UnsupportedOperationException
. This is unintuitive behavior! If a method says it returns a List
, the standard expectation is that it returns an object which supports the methods of interface List
. A developer shouldn't have to memorize which of the umpteen util.List
methods create List
s that don't actually support all the List
methods.
If they had named the method asImmutableList
, it would make sense. Or if they just had the method return an actual List
(and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the Principle of Least Surprise and the good-O.O. practice of avoiding UnsupportedOperationException
s.
(Also, the designers might have made a interface ImmutableList
, to avoid a plethora of UnsupportedOperationException
s.)
I was looking for the same issue, and imho the pretty solution is :
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
and using that to parse the string to boolean as suggested above.
Browsers control a lot of this functionality but
<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>
will attempt to open yahoo.com in a new window.
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener
, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick
method like this:
public class MyListener implements View.OnClickListener {
@Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener
takes View.OnClickListener
as its parameter.
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
I actually have a similar problem. I have a page with multiple radio buttons; each button will set the title and description meta tags of the page, via JavaScript upon change.
For example, if users select the first button, the meta tags will say:
<meta name="title" content="First Title">
<meta name="description" content="First Description">
If the user select the second button, this changes the meta tags to:
<meta name="title" content="Second Title">
<meta name="description" content="Second Description">
... and so on. I have confirmed that the code is working fine via Firebug (i.e. I can see that those two tags were properly changed).
Apparently, Facebook Share only pulls in the title and description meta tags that are available upon page load. The changes to those two tags post page load are completely ignored.
Does anybody have any ideas on how to solve this? That is, to force Facebook to get the latest values that are change after the page loads.
Far, far, far more refactorings.
set android:dividerHeight="1dp"
<ListView
android:id="@+id/myphnview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@drawable/dividerheight"
android:background="#E9EAEC"
android:clickable="true"
android:divider="@color/white"
android:dividerHeight="1dp"
android:headerDividersEnabled="true" >
</ListView>
You Could Do The same as abatishchev but without the UAC
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
var out_para_name refcursor;
execute package_name.procedure_name(inpu_para_val1,input_para_val2,... ,:out_para_name);
print :out_para_name;
For those using bootstrap 4 beta you can add max-width on your navbar link to have control on the size of your logo with img-fluid class on the image element.
<a class="navbar-brand" href="#" style="max-width: 30%;">
<img src="images/logo.png" class="img-fluid">
</a>
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
in template
<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
system_update_alt
</md-icon></md-button>
in controller
$scope.export = function(){ $window.location.href = $scope.export; };
In MySQL, the word 'type' is a Reserved Word.
This works, even when there are middle names:
=MID(A2,FIND(CHAR(1),SUBSTITUTE(A2," ",CHAR(1),LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))+1,LEN(A2))
If you want everything BUT the last name, check out this answer.
If there are trailing spaces in your names, then you may want to remove them by replacing all instances of A2
by TRIM(A2)
in the above formula.
Note that it is only by pure chance that your first formula =RIGHT(A2,FIND(" ",A2,1)-1)
kind of works for Alistair Stevens
. This is because "Alistair"
and " Stevens"
happen to contain the same number of characters (if you count the leading space in " Stevens"
).
If you want to add N days to your days. You can use the plus operator as follows -
SELECT ( SYSDATE + N ) FROM DUAL;
For log4j2 the solution is slightly different because AppenderSkeleton is not available anymore. Additionally, using Mockito, or similar library to create an Appender with an ArgumentCaptor will not work if you're expecting multiple logging messages because the MutableLogEvent is reused over multiple log messages. The best solution I found for log4j2 is:
private static MockedAppender mockedAppender;
private static Logger logger;
@Before
public void setup() {
mockedAppender.message.clear();
}
/**
* For some reason mvn test will not work if this is @Before, but in eclipse it works! As a
* result, we use @BeforeClass.
*/
@BeforeClass
public static void setupClass() {
mockedAppender = new MockedAppender();
logger = (Logger)LogManager.getLogger(MatchingMetricsLogger.class);
logger.addAppender(mockedAppender);
logger.setLevel(Level.INFO);
}
@AfterClass
public static void teardown() {
logger.removeAppender(mockedAppender);
}
@Test
public void test() {
// do something that causes logs
for (String e : mockedAppender.message) {
// add asserts for the log messages
}
}
private static class MockedAppender extends AbstractAppender {
List<String> message = new ArrayList<>();
protected MockedAppender() {
super("MockedAppender", null, null);
}
@Override
public void append(LogEvent event) {
message.add(event.getMessage().getFormattedMessage());
}
}
You can't have optional path variables, but you can have two controller methods which call the same service code:
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return getTestBean(type);
}
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
HttpServletRequest req,
@RequestParam("track") String track) {
return getTestBean();
}
Try This:
//urlPath = address of your picture on internet
URL url = new URL("urlPath");
BufferedImage c = ImageIO.read(url);
ImageIcon image = new ImageIcon(c);
jXImageView1.setImage(image);
You can also name columns directly in the cbind
call, e.g.
cbind(date=c(0,1), high=c(2,3))
Output:
date high
[1,] 0 2
[2,] 1 3
You can use Underscore String Library as following
var common="#box"
var href="#box1"
_(href).strRight(common)
result will be : 1
See :https://github.com/epeli/underscore.string
DEMO:
http://jsfiddle.net/abdennour/Vyqtt/
HTML Code :
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JS Code :
var comm="#box"
$('a').click(function(){
$('div').html(_($(this).attr('href')).strRight(comm))})
if you have suffix as following :
href="box1az"
You can use the next demo :
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all,prefix,suffix){
var left=_(all).strRight(prefix);
return _(left).strLeft(suffix);
}
I faced the same issue:
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
I resolved by using the following commands:
apt-get update
apt-get install gnupg
1)event.stopPropagation():
=>It is used to stop executions of its corresponding parent handler only.
2) event.stopImmediatePropagation():
=> It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler.
=> It also stops all the handler attached to the current element of entire DOM.
Here is the example: Jsfiddle!
Thanks, -Sahil
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
It took me quite a while to figure out, how to not get a false
when using openssl_decrypt()
and get encrypt and decrypt working.
// cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
$encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
$encrypted = $encrypted . ':' . base64_encode($iv);
// decrypt to get again $plaintext
$parts = explode(':', $encrypted);
$decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1]));
If you want to pass the encrypted string via a URL, you need to urlencode the string:
$encrypted = urlencode($encrypted);
To better understand what is going on, read:
To generate 16 bytes long keys you can use:
$bytes = openssl_random_pseudo_bytes(16);
$hex = bin2hex($bytes);
To see error messages of openssl you can use: echo openssl_error_string();
Hope that helps.
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
Now there is a special command which messes this up: &
cmd &
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
or, if you don't want any special handling/output simply
wait $BACK_PID
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
This is what you can do:
SELECT *
FROM yourTable
PIVOT (MAX(xCount)
FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
I know this is an old thread, but hope it helps some one.
public static void SetRequest(string mXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Decide your encoding here
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentType = "text/xml; charset=utf-8";
// You should setContentLength
byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var res = await httpRequest(webRequest);
}
The simplest way is to drop the user that owns the objects with the cascade command.
DROP USER username CASCADE
Further to pensz answer you can get more info using:
DESCRIBE EXTENDED my_table;
or
DESCRIBE EXTENDED my_table PARTITION (my_column='my_value');
check this solution for String to hex and hex to String vise-versa
public class TestHexConversion {
public static void main(String[] args) {
try{
String clearText = "testString For;0181;with.love";
System.out.println("Clear Text = " + clearText);
char[] chars = clearText.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}
String hexText = hex.toString();
System.out.println("Hex Text = " + hexText);
String decodedText = HexToString(hexText);
System.out.println("Decoded Text = "+decodedText);
} catch (Exception e){
e.printStackTrace();
}
}
public static String HexToString(String hex){
StringBuilder finalString = new StringBuilder();
StringBuilder tempString = new StringBuilder();
for( int i=0; i<hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
finalString.append((char)decimal);
tempString.append(decimal);
}
return finalString.toString();
}
Output as follows :
Clear Text = testString For;0181;with.love
Hex Text = 74657374537472696e6720466f723b303138313b776974682e6c6f7665
Decoded Text = testString For;0181;with.love
A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:
extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations
A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:
int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};
A definition can be used in the place of a declaration.
An identifier can be declared as often as you want. Thus, the following is legal in C and C++:
double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);
However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.
Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:
A declaration is a definition unless it [...] is a class name declaration [...].
3.1/3 then gives a few examples. Amongst them:
[Example: [...] struct S { int a; int b; }; // defines S, S::a, and S::b [...] struct S; // declares S —end example
To sum it up: The C++ standard considers struct x;
to be a declaration and struct x {};
a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)
Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.
DAYS360
does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-
) or MINUS()
. I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.
Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]
With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.
In a console I did the following:
import matplotlib
matplotlib.get_backend()
The result was: 'agg', while this should be 'TkAgg'.
The solution was simple:
Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:
> df[df=="" | df==12] <- NA
> df
A B
1 <NA> <NA>
2 xyz <NA>
3 jkl 100
For factors, zxzak's code already yields factors:
> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame': 3 obs. of 2 variables:
$ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
$ B: Factor w/ 3 levels "","100","12": 3 1 2
If in trouble, I'd suggest to temporarily drop the factors.
df[] <- lapply(df, as.character)
I solved the problem by changing
$db['default']['pconnect'] = TRUE;
TO
$db['default']['pconnect'] = FALSE;
in /application/config/database.php
Or may be its even simpler to remember like this, in case of optional arguments for a method:
public void Method(string parameter = "argument")
{
}
parameter
is the parameter, its value, "argument"
is the argument :)
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
The Python library pdf2image
(used in the other answer) in fact doesn't do much more than just launching pdttoppm
with subprocess.Popen
, so here is a short version doing it directly:
PDFTOPPMPATH = r"D:\Documents\software\____PORTABLE\poppler-0.51\bin\pdftoppm.exe"
PDFFILE = "SKM_28718052212190.pdf"
import subprocess
subprocess.Popen('"%s" -png "%s" out' % (PDFTOPPMPATH, PDFFILE))
Here is the Windows installation link for pdftoppm
(contained in a package named poppler): http://blog.alivate.com.au/poppler-windows/
In my opinion there are some idle queries running in the backgroud.
SELECT pid, age(clock_timestamp(), query_start), usename, query FROM pg_stat_activity WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' ORDER BY query_start desc;
SELECT pg_terminate_backend(procpid);
Note: Killing a select query doesnt make any bad impact
One liner if you want something compact:
String.prototype.pad = function(len, chr){_x000D_
return((((new Array(len)).fill(chr)).join("") +this).substring(this.length));_x000D_
}
_x000D_
The simplest way and will help you with is set CharSet to UTF-8
$mail->CharSet = "UTF-8"
The title of this thread asks how a subquery can be used in an update. Here's an example of that:
update [dbName].[dbo].[MyTable]
set MyColumn = 1
where
(
select count(*)
from [dbName].[dbo].[MyTable] mt2
where
mt2.ID > [dbName].[dbo].[MyTable].ID
and mt2.Category = [dbName].[dbo].[MyTable].Category
) > 0
It is pretty easy to add a collaborator to a free plan.
The added user should now be able to push to your repository on GitHub.
You should add & make your BOT as administrator of the PRIVATE channel, otherwise chat not found
error happens.
One way of achieving this behaviour is by setting the value to _id
(which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id
as the primary key then at the time of creating document in MongoDB; assign _id
value same as that of employee_id
.
How about:
SELECT * FROM sometable WHERE CHAR_LENGTH(LINK) > 1
Here's the MySql string functions page (5.0).
Note that I chose CHAR_LENGTH
instead of LENGTH
, as if there are multibyte characters in the data you're probably really interested in how many characters there are, not how many bytes of storage they take. So for the above, a row where LINK is a single two-byte character wouldn't be returned - whereas it would when using LENGTH
.
Note that if LINK
is NULL
, the result of CHAR_LENGTH(LINK)
will be NULL
as well, so the row won't match.
From Docker documentation:
docker export
does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container,docker export
will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.
I think you are missing your certificates.
You can try generating them by using InstallCerts app. Here you can see how to use it: https://github.com/escline/InstallCert
Once you get your certificate, you need to put it under your security directory within your jdk home, for example:
C:\Program Files\Java\jdk1.6.0_45\jre\lib\security
Let me know if it works.
Somewhat related - I was looking for a solution to do the same for directories.
Unfortunately the -j
option does not work for this :(
Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file
This will create a Date
exactly one year in the future with just one line. First we get the fullYear
from a new Date
, increment it, set that as the year of a new Date
. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date
object so we wrap the whole thing in a Date
constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
The EOF flag is only set after a read operation attempts to read past the end of the file. get()
is returning the symbolic constant traits::eof()
(which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof()
be true. If you want to check for this condition, you can do something like the following:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
If you want something that works well on windows there is a package called WinFoldersJava which wraps the native call to get the 'special' directories on Windows. We use it frequently and it works well.
strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
"xmlns:tem=""http://tempuri.org/"">" &_
"<soap:Header/>" &_
"<soap:Body>" &_
"<tem:Authorization>" &_
"<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
"<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
"<tem:CVV2>"&123&"</tem:CVV2>" &_
"<tem:strYR>"&23&"</tem:strYR>" &_
"<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
"</tem:Authorization>" &_
"</soap:Body>" &_
"</soap:Envelope>"
EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
"/trainingrite_epaysystem/tr_epaysys.asmx"
dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"
msgbox "REQUEST : " & strRequest
http.send strRequest
If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If
Call ParseTag(responseText,"AuthorizationResult")
Call CreateXMLEvidence(responseText,strRequest)
'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)
ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
Msgbox ResponseMessage
End Function
'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)
Set fso=createobject("Scripting.FileSystemObject")
Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)
qfile.write ResponseXML
qfile.close
qfile1.write strRequest
qfile1.close
End Function
if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '')
is faster.
see http://jsperf.com/cast-to-string/8
note - there are significant differences across browsers at this time.
Using like might take longer time so use full_text_search:
SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')
I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.
What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).
<script language="javascript" type="text/javascript">
window.onbeforeunload = function () {
// This function does nothing. It won't spawn a confirmation dialog
// But it will ensure that the page is not cached by the browser.
}
</script>
This has disabled all caching in all browsers for me without fail.
Adding to the other answers, in a Series
there are also map and apply.
Apply can make a DataFrame out of a series; however, map will just put a series in every cell of another series, which is probably not what you want.
In [40]: p=pd.Series([1,2,3])
In [41]: p
Out[31]:
0 1
1 2
2 3
dtype: int64
In [42]: p.apply(lambda x: pd.Series([x, x]))
Out[42]:
0 1
0 1 1
1 2 2
2 3 3
In [43]: p.map(lambda x: pd.Series([x, x]))
Out[43]:
0 0 1
1 1
dtype: int64
1 0 2
1 2
dtype: int64
2 0 3
1 3
dtype: int64
dtype: object
Also if I had a function with side effects, such as "connect to a web server", I'd probably use apply
just for the sake of clarity.
series.apply(download_file_for_every_element)
Map
can use not only a function, but also a dictionary or another series. Let's say you want to manipulate permutations.
Take
1 2 3 4 5
2 1 4 5 3
The square of this permutation is
1 2 3 4 5
1 2 5 3 4
You can compute it using map
. Not sure if self-application is documented, but it works in 0.15.1
.
In [39]: p=pd.Series([1,0,3,4,2])
In [40]: p.map(p)
Out[40]:
0 0
1 1
2 4
3 2
4 3
dtype: int64
The following code the easiest way:
<h:outputLabel value="value = 10" rendered="#{row == 10}" />
<h:outputLabel value="value = 15" rendered="#{row == 15}" />
<h:outputLabel value="value xyz" rendered="#{row != 15 and row != 10}" />
Link for EL expression syntax. http://developers.sun.com/docs/jscreator/help/jsp-jsfel/jsf_expression_language_intro.html#syntax
It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".
.img {
width: 100vw;
height: 100vh;
}
I think most of the answers here are over-engineered. The way i did it is through 2 helper methods, the first to wait for an element based on any selector; and the second to take a screenshot of it.
Note: We cast the WebElement
to a TakesScreenshot
instance, so we only capture that element in the image specifically. If you want the full page/window, you should cast driver
instead.
WebDriver driver = new FirefoxDriver(); // define this somewhere (or chrome etc)
public <T> T screenshotOf(By by, long timeout, OutputType<T> type) {
return ((TakesScreenshot) waitForElement(by, timeout))
.getScreenshotAs(type);
}
public WebElement waitForElement(By by, long timeout) {
return new WebDriverWait(driver, timeout)
.until(driver -> driver.findElement(by));
}
And then just screenshot whatever u want like this :
long timeout = 5; // in seconds
/* Screenshot (to file) based on first occurence of tag */
File sc = screenshotOf(By.tagName("body"), timeout, OutputType.FILE);
/* Screenshot (in memory) based on CSS selector (e.g. first image in body
who's "src" attribute starts with "https") */
byte[] sc = screenshotOf(By.cssSelector("body > img[href^='https']"), timeout, OutputType.BYTES);
To calculate gradients, the machine learning community uses Autograd:
To install:
pip install autograd
Here is an example:
import autograd.numpy as np
from autograd import grad
def fct(x):
y = x**2+1
return y
grad_fct = grad(fct)
print(grad_fct(1.0))
It can also compute gradients of complex functions, e.g. multivariate functions.
In case you need C++11 compatibility and cannot use boost, here is a boost-compatible drop-in with an example of usage:
#include <iostream>
#include <string>
static bool starts_with(const std::string str, const std::string prefix)
{
return ((prefix.size() <= str.size()) && std::equal(prefix.begin(), prefix.end(), str.begin()));
}
int main(int argc, char* argv[])
{
bool usage = false;
unsigned int foos = 0; // default number of foos if no parameter was supplied
if (argc > 1)
{
const std::string fParamPrefix = "-f="; // shorthand for foo
const std::string fooParamPrefix = "--foo=";
for (unsigned int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
try
{
if ((arg == "-h") || (arg == "--help"))
{
usage = true;
} else if (starts_with(arg, fParamPrefix)) {
foos = std::stoul(arg.substr(fParamPrefix.size()));
} else if (starts_with(arg, fooParamPrefix)) {
foos = std::stoul(arg.substr(fooParamPrefix.size()));
}
} catch (std::exception& e) {
std::cerr << "Invalid parameter: " << argv[i] << std::endl << std::endl;
usage = true;
}
}
}
if (usage)
{
std::cerr << "Usage: " << argv[0] << " [OPTION]..." << std::endl;
std::cerr << "Example program for parameter parsing." << std::endl << std::endl;
std::cerr << " -f, --foo=N use N foos (optional)" << std::endl;
return 1;
}
std::cerr << "number of foos given: " << foos << std::endl;
}
We can use four methods for this conversion
10
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
For the primitive type Number
, the safest max value is 253-1(Number.MAX_SAFE_INTEGER
).
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
All results will be incorrect.
That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER
. i.e.,
99999999999999999999 > 9007199254740991
This means all operation performed with the assumption that the string
can be converted to number
type fails.
For numbers greater than 253, primitive BigInt
has been added recently. Check browser compatibility of BigInt
here.
The conversion code will be like this.
const numString = '099999999999999999999';
const number = BigInt(numString);
parseInt
?If radix is undefined or 0 (or absent), JavaScript assumes the following:
Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.
For this reason, always specify a radix when using parseInt
The example from MySQL documentation http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html (i shrink it, documentation for this section is the same for 5.5)
mysql> create table t1 (i int, d1 double, d2 double);
mysql> insert into t1 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t1
group by
i
having a <> b; -- a != b
+------+-------------------+------+
| i | a | b |
+------+-------------------+------+
| 2 | 76.80000000000001 | 76.8 |
+------+-------------------+------+
1 row in set (0.00 sec)
Basically if you sum a you get 0-13.2+59.6+30.4 = 76.8. If we sum up b we get 0+0+46.4+30.4=76.8. The sum of a and b is the same but MySQL documentation says:
A floating-point value as written in an SQL statement may not be the same as the value represented internally.
If we repeat the same with decimal:
mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into t2 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
Query OK, 4 rows affected (0.07 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t2
group by
i
having a <> b;
Empty set (0.00 sec)
The result as expected is empty set.
So as long you do not perform any SQL arithemetic operations you can use DOUBLE, but I would still prefer DECIMAL.
Another thing to note about DECIMAL is rounding if fractional part is too large. Example:
mysql> create table t3 (d decimal(5,2));
Query OK, 0 rows affected (0.07 sec)
mysql> insert into t3 (d) values(34.432);
Query OK, 1 row affected, 1 warning (0.10 sec)
mysql> show warnings;
+-------+------+----------------------------------------+
| Level | Code | Message |
+-------+------+----------------------------------------+
| Note | 1265 | Data truncated for column 'd' at row 1 |
+-------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> select * from t3;
+-------+
| d |
+-------+
| 34.43 |
+-------+
1 row in set (0.00 sec)
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[ _x000D_
[ _x000D_
{ _x000D_
"b":"0.110547334",_x000D_
"cost":"0.000000",_x000D_
"w":"1.998889"_x000D_
}_x000D_
],_x000D_
[ _x000D_
{ _x000D_
"x":0,_x000D_
"y":0_x000D_
},_x000D_
{ _x000D_
"x":1,_x000D_
"y":2_x000D_
},_x000D_
{ _x000D_
"x":2,_x000D_
"y":4_x000D_
},_x000D_
{ _x000D_
"x":3,_x000D_
"y":6_x000D_
},_x000D_
{ _x000D_
"x":4,_x000D_
"y":8_x000D_
},_x000D_
{ _x000D_
"x":5,_x000D_
"y":10_x000D_
},_x000D_
{ _x000D_
"x":6,_x000D_
"y":12_x000D_
},_x000D_
{ _x000D_
"x":7,_x000D_
"y":14_x000D_
},_x000D_
{ _x000D_
"x":8,_x000D_
"y":16_x000D_
},_x000D_
{ _x000D_
"x":9,_x000D_
"y":18_x000D_
},_x000D_
{ _x000D_
"x":10,_x000D_
"y":20_x000D_
},_x000D_
{ _x000D_
"x":11,_x000D_
"y":22_x000D_
},_x000D_
{ _x000D_
"x":12,_x000D_
"y":24_x000D_
},_x000D_
{ _x000D_
"x":13,_x000D_
"y":26_x000D_
},_x000D_
{ _x000D_
"x":14,_x000D_
"y":28_x000D_
},_x000D_
{ _x000D_
"x":15,_x000D_
"y":30_x000D_
},_x000D_
{ _x000D_
"x":16,_x000D_
"y":32_x000D_
},_x000D_
{ _x000D_
"x":17,_x000D_
"y":34_x000D_
},_x000D_
{ _x000D_
"x":18,_x000D_
"y":36_x000D_
},_x000D_
{ _x000D_
"x":19,_x000D_
"y":38_x000D_
},_x000D_
{ _x000D_
"x":20,_x000D_
"y":40_x000D_
},_x000D_
{ _x000D_
"x":21,_x000D_
"y":42_x000D_
},_x000D_
{ _x000D_
"x":22,_x000D_
"y":44_x000D_
},_x000D_
{ _x000D_
"x":23,_x000D_
"y":46_x000D_
},_x000D_
{ _x000D_
"x":24,_x000D_
"y":48_x000D_
},_x000D_
{ _x000D_
"x":25,_x000D_
"y":50_x000D_
},_x000D_
{ _x000D_
"x":26,_x000D_
"y":52_x000D_
},_x000D_
{ _x000D_
"x":27,_x000D_
"y":54_x000D_
},_x000D_
{ _x000D_
"x":28,_x000D_
"y":56_x000D_
},_x000D_
{ _x000D_
"x":29,_x000D_
"y":58_x000D_
},_x000D_
{ _x000D_
"x":30,_x000D_
"y":60_x000D_
},_x000D_
{ _x000D_
"x":31,_x000D_
"y":62_x000D_
},_x000D_
{ _x000D_
"x":32,_x000D_
"y":64_x000D_
},_x000D_
{ _x000D_
"x":33,_x000D_
"y":66_x000D_
},_x000D_
{ _x000D_
"x":34,_x000D_
"y":68_x000D_
},_x000D_
{ _x000D_
"x":35,_x000D_
"y":70_x000D_
},_x000D_
{ _x000D_
"x":36,_x000D_
"y":72_x000D_
},_x000D_
{ _x000D_
"x":37,_x000D_
"y":74_x000D_
},_x000D_
{ _x000D_
"x":38,_x000D_
"y":76_x000D_
},_x000D_
{ _x000D_
"x":39,_x000D_
"y":78_x000D_
},_x000D_
{ _x000D_
"x":40,_x000D_
"y":80_x000D_
},_x000D_
{ _x000D_
"x":41,_x000D_
"y":82_x000D_
},_x000D_
{ _x000D_
"x":42,_x000D_
"y":84_x000D_
},_x000D_
{ _x000D_
"x":43,_x000D_
"y":86_x000D_
},_x000D_
{ _x000D_
"x":44,_x000D_
"y":88_x000D_
},_x000D_
{ _x000D_
"x":45,_x000D_
"y":90_x000D_
},_x000D_
{ _x000D_
"x":46,_x000D_
"y":92_x000D_
},_x000D_
{ _x000D_
"x":47,_x000D_
"y":94_x000D_
},_x000D_
{ _x000D_
"x":48,_x000D_
"y":96_x000D_
},_x000D_
{ _x000D_
"x":49,_x000D_
"y":98_x000D_
},_x000D_
{ _x000D_
"x":50,_x000D_
"y":100_x000D_
},_x000D_
{ _x000D_
"x":51,_x000D_
"y":102_x000D_
},_x000D_
{ _x000D_
"x":52,_x000D_
"y":104_x000D_
},_x000D_
{ _x000D_
"x":53,_x000D_
"y":106_x000D_
},_x000D_
{ _x000D_
"x":54,_x000D_
"y":108_x000D_
},_x000D_
{ _x000D_
"x":55,_x000D_
"y":110_x000D_
},_x000D_
{ _x000D_
"x":56,_x000D_
"y":112_x000D_
},_x000D_
{ _x000D_
"x":57,_x000D_
"y":114_x000D_
},_x000D_
{ _x000D_
"x":58,_x000D_
"y":116_x000D_
},_x000D_
{ _x000D_
"x":59,_x000D_
"y":118_x000D_
},_x000D_
{ _x000D_
"x":60,_x000D_
"y":120_x000D_
},_x000D_
{ _x000D_
"x":61,_x000D_
"y":122_x000D_
},_x000D_
{ _x000D_
"x":62,_x000D_
"y":124_x000D_
},_x000D_
{ _x000D_
"x":63,_x000D_
"y":126_x000D_
},_x000D_
{ _x000D_
"x":64,_x000D_
"y":128_x000D_
},_x000D_
{ _x000D_
"x":65,_x000D_
"y":130_x000D_
},_x000D_
{ _x000D_
"x":66,_x000D_
"y":132_x000D_
},_x000D_
{ _x000D_
"x":67,_x000D_
"y":134_x000D_
},_x000D_
{ _x000D_
"x":68,_x000D_
"y":136_x000D_
},_x000D_
{ _x000D_
"x":69,_x000D_
"y":138_x000D_
},_x000D_
{ _x000D_
"x":70,_x000D_
"y":140_x000D_
},_x000D_
{ _x000D_
"x":71,_x000D_
"y":142_x000D_
},_x000D_
{ _x000D_
"x":72,_x000D_
"y":144_x000D_
},_x000D_
{ _x000D_
"x":73,_x000D_
"y":146_x000D_
},_x000D_
{ _x000D_
"x":74,_x000D_
"y":148_x000D_
},_x000D_
{ _x000D_
"x":75,_x000D_
"y":150_x000D_
},_x000D_
{ _x000D_
"x":76,_x000D_
"y":152_x000D_
},_x000D_
{ _x000D_
"x":77,_x000D_
"y":154_x000D_
},_x000D_
{ _x000D_
"x":78,_x000D_
"y":156_x000D_
},_x000D_
{ _x000D_
"x":79,_x000D_
"y":158_x000D_
},_x000D_
{ _x000D_
"x":80,_x000D_
"y":160_x000D_
},_x000D_
{ _x000D_
"x":81,_x000D_
"y":162_x000D_
},_x000D_
{ _x000D_
"x":82,_x000D_
"y":164_x000D_
},_x000D_
{ _x000D_
"x":83,_x000D_
"y":166_x000D_
},_x000D_
{ _x000D_
"x":84,_x000D_
"y":168_x000D_
},_x000D_
{ _x000D_
"x":85,_x000D_
"y":170_x000D_
},_x000D_
{ _x000D_
"x":86,_x000D_
"y":172_x000D_
},_x000D_
{ _x000D_
"x":87,_x000D_
"y":174_x000D_
},_x000D_
{ _x000D_
"x":88,_x000D_
"y":176_x000D_
},_x000D_
{ _x000D_
"x":89,_x000D_
"y":178_x000D_
},_x000D_
{ _x000D_
"x":90,_x000D_
"y":180_x000D_
},_x000D_
{ _x000D_
"x":91,_x000D_
"y":182_x000D_
},_x000D_
{ _x000D_
"x":92,_x000D_
"y":184_x000D_
},_x000D_
{ _x000D_
"x":93,_x000D_
"y":186_x000D_
},_x000D_
{ _x000D_
"x":94,_x000D_
"y":188_x000D_
},_x000D_
{ _x000D_
"x":95,_x000D_
"y":190_x000D_
},_x000D_
{ _x000D_
"x":96,_x000D_
"y":192_x000D_
},_x000D_
{ _x000D_
"x":97,_x000D_
"y":194_x000D_
},_x000D_
{ _x000D_
"x":98,_x000D_
"y":196_x000D_
},_x000D_
{ _x000D_
"x":99,_x000D_
"y":198_x000D_
}_x000D_
]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
console.info(ch);_x000D_
_x000D_
scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
code sample - https://codepen.io/nagasai/pen/GGzZVB
Short answer: No.
The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.
So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.
Long answer #1 has been given by others.
Long answer #2:
Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.
Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.
The example you gave in your question would then look like this:
var commandList = new List<Command>() { new MyABCCommand() };
foreach (Command c in commandList)
{
if (c.Accept(mystring))
{
c.Execute(mystring);
break;
}
}
class MyABCCommand : Command
{
override bool Accept(string mystring)
{
return mystring.StartsWith("abc");
}
}
Try to create remote origin first, maybe is missing because you change name of the remote repo
git remote add origin URL_TO_YOUR_REPO
I got same issue in Visual Studio 2017 and TFS 2017. DefaultCollection must be mapped first to you local path. Somehow this step was skipped and I got only MyFirstProject mapped.
All you need to do is:
- 1. Go to your TFS web page and remove the project from the server.
- 2. Remove the project from your local "Worksapces"
- 3. Go to "Manage Connections" which will refresh your Home page in TeamExplorer.
- 4. You will get Configuration page which will allow you to setup root path to your DefaultCollection.
- 5. You should get message that it been done successfully. Now you can create your project.
It's important to map root of your collection to your workspace first and then map a new project.
Looks like this behavior is how Ansible currently works, although there is a lot of interest in fixing it to work as desired. There's currently a pull request with the desired functionality so hopefully this will get incorporated into Ansible eventually.
I think the one thing that I know GIT wins on is it's ability to "preserve line endings" on all files, whereas perforce seems to insist on translating them into either Unix, Dos/Windows or MacOS9 format ("\n", "\r\n" or "\r).
This is a real pain if you're writing Unix scripts in a Windows environment, or a mixed OS environment. It's not even possible to set the rule on a per-file-extension basis. For instance, it would convert .sh, .bash, .unix files to Unix format, and convert .ccp, .bat or .com files to Dos/Windows format.
In GIT (I'm not sure if that's default, an option or the only option) you can set it up to "preserve line endings". That means, you can manually change the line endings of a file, and then GIT will leave that format the way it is. This seems to me like the ideal way to do things, and I don't understand why this isn't an option with Perforce.
The only way you can achieve this behavior, is to mark the files as binary. As I see that, that would be a nasty hack to workaround a missing feature. Apart from being tedious to have to do on all scripts, etc, it would also probably break most diffs, etc.
The "solution" that we've settled for at the moment, is to run a sed command to remove all carriage returns from the scripts every time they're deployed to their Unix environment. This isn't ideal either, especially since some of them are deployed inside WAR files, and the sed line has to be run again when they're unpacked.
This is just something I think gives GIT a great advantage, and which I don't think has been mentioned above.
EDIT: After having been using Perforce for a bit longer, I'd like to add another couple of comments:
A) Something I really miss in Perforce is a clear and instance diff, including changed, removed and added files. This is available in GIT with the git diff
command, but in Perforce, files have to be checked out before their changes are recorded, and while you might have your main editors (like Eclipse) set up to automatically check files out when you edit them, you might sometimes edit files in other ways (notepad, unix commands, etc). And new files don't seem to be added automatically at all, even using Eclipse and p4eclipse, which can be rather annoying. So to find all changes, you have to run a "Diff against..." on the entire workspace, which first of all takes a while to run, and secondly includes all kind of irrelevant things unless you set up very complicated exclusion lists, which leads me to the next point.
B) In GIT I find the .gitignore very simple and easy to manage, read and understand. However, the workspace ignore/exclude lists configurable in Perforce seem unwieldy and unnecessarily complex. I haven't been able to get any exclusions with wildcards working. I would like to do something like
-//Server/mainline/.../target/... //Svend_Hansen_Server/.../target/...
To exclude all target folders within all projects inside Server/mainline. However, this doesn't seem to work like I would have expected, and I've ended up adding a line for every project like:
-//Server/mainline/projectA/target/... //Svend_Hansen_Server/projectA/target/...
-//Server/mainline/projectB/target/... //Svend_Hansen_Server/projectB/target/...
...
And similar lines for bin folders, .classpath and .projet files and more.
C) In Perforce there are the rather useful changelists. However, assume I make a group of changes, check them all and put them in a changelist, to then work on something else before submitting that changelist. If I later make a change to one of the files included in the first changelist, that file will still be in that changelist, and I can't just later submit the changelist assuming that it only contains the changes that I originally added (though it will be the same files). In GIT, if you add a file and them make further changes to it, those changes will not have been added (and would still show in a git diff
and you wouldn't be able to commit the file without first adding the new changes as well. Of course, this isn't usefull in the same way the changelist can be as you only have one set of added files, but in GIT you can just commit the changes, as that doesn't actually push them. You could them work on other changes before pushing them, but you wouldn't be able to push anything else that you add later, without pushing the former changes as well.
Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.
To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.
dumps(s.decode()).replace("'", '"')[1:-1]
I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.
This worked for me in Oracle 11g:
REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*');
Following Mike's answer, I'd also add another step. Let's imagine you have your data in column A.
Hope it helps.
Ofc, if the word you want to add will always be the same, you won't need a column B (thus, C1="k"+A1)
Rgds
Configure another port number(eg:8181) in /src/main/resources/application.properties
server.port=8181
//in fragment page:
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity(), HORIZONTAL,true));
//this worked for me but before that please import :
implementation 'com.android.support:recyclerview-v7:28.0.0'
Click event Bubbles, now what is meant by bubbling, a good point to starts is here.
you can use event.stopPropagation()
, if you don't want that event should propagate further.
Also a good link to refer on MDN
Upgrade the pip via command prompt ( Python Directory )
D:\Python 3.7.2>python -m pip install --upgrade pip
Now you can install the required Module
D:\Python 3.7.2>python -m pip install <<yourModuleName>>
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />
therefore we use the following snippet
$.validator.addMethod(
"regex",
function(value, element, regstring) {
// fast exit on empty optional
if (this.optional(element)) {
return true;
}
var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
// the parsed pattern had delimiters and modifiers. handle them.
var regexp = new RegExp(regParts[1], regParts[2]);
} else {
// we got pattern string without delimiters
var regexp = new RegExp(regstring);
}
return regexp.test(value);
},
"Please check your input."
);
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js
Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH%
is used to represent value of existing path variable in Windows while ${PATH}
is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:
export CLASSPATH=${CLASSPATH}:/new/path
but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:
-cp
options overrides CLASSPATH
environment variable.-cp
and CLASSPATH
envorinment variable.Reference: How Classpath works in Java.
For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).
Or the -Remove parameter
Set-ADUser -Identity anyUser -Remove @{extensionAttribute4="myString"}
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
I just noticed something I can't explain, but hey, for me it works!
I was compiling Android from sources anyway and the built-in emulator started in a few seconds (my machine is dual core AMD 2.7 GHz) and in a minute, perhaps two at the first run, the system was up. Using Eclipse ADT bundle, on the other hand, resulted in half an hour of emulator startup. Unacceptable.
The solution that works here (I have no means to test it on other machines, so if you feel inclined, test and verify):
<source base dir>/out/host/linux-x86
Also, I agree with running from snapshot and saving state to snapshot. My advice concerns only emulator startup time. I still have no idea why it is so long by default. Anyway, if that works for you, enjoy :)
No, there is no other way than
def dictMinus(dct, val):
copy = dct.copy()
del copy[val]
return copy
However, often creating copies of only slightly altered dictionaries is probably not a good idea because it will result in comparatively large memory demands. It is usually better to log the old dictionary(if even necessary) and then modify it.
var str = "hello world";
console.log(str);
var arr = [...str];
arr[0] = "H";
str = arr.join("");
console.log(str);
_x000D_
var btn = document.querySelector('#twofuns');_x000D_
btn.addEventListener('click',method1);_x000D_
btn.addEventListener('click',method2);_x000D_
function method2(){_x000D_
console.log("Method 2");_x000D_
}_x000D_
function method1(){_x000D_
console.log("Method 1");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Pramod Kharade-Javascript</title>_x000D_
</head>_x000D_
<body>_x000D_
<button id="twofuns">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
You can achieve/call one event with one or more methods.
you can use the <pre>
tag to prevent multiple spaces and linebreaks from being collapsed into one. Or you could use
for a typical space (non-breaking space) and <br />
(or <br>
) for line breaks.
But don't do <br><br><br><br>
just use a <p>
tag and adjust the margins with CSS.
<p style="margin-top: 20px;">Some copy...</p>
Although, you should define the styles globally, and not inline as I have done in this example.
When you are outputting strings from PHP you can use "\n" for a new line, and "\t" for a tab.
<?php echo "This is one line\nThis is another line"; ?>
Although, flags like \n or \t only work in double quotes (") not single wuotes (').
System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms
echo "message" | git commit-tree HEAD^{tree}
This will create an orphaned commit with the tree of HEAD, and output its name (SHA-1) on stdout. Then just reset your branch there.
git reset SHA-1
To do the above in a single step:
git reset $(git commit-tree HEAD^{tree} -m "commit message")
I have created a directive in agularJS supported with ng-bootStrap components
https://angular-ui.github.io/bootstrap/#!#tabs
here I share the code that I implemented
[https://jsfiddle.net/k1r02/u6gpv4dc/][1]
[1]: https://jsfiddle.net/k1r02/u6gpv4dc/
I could do that following the steps:
axios.js
mock fileThe mock will happen automatically
Example of the mock module:
module.exports = {
get: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
}),
post: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
if (url === '/something2') {
return Promise.resolve({
data: 'data2'
});
}
}),
create: jest.fn(function () {
return this;
})
};
Yah I found
<base target="_parent" />
This useful for open all iframe links open in iframe.
And
$(window).load(function(){
$("a").click(function(){
top.window.location.href=$(this).attr("href");
return true;
})
})
This we can use for whole page or specific part of page.
Thanks all for your help.
You need to use the as.Date formats correctly.
Eg.
x = '2012/07/25'
xd = as.Date(x,'%Y/%m/%d')
xd # Prints "2012-07-25"
R date formats are similary to *nix ones.
Doing a typeof(xd) shows it as a double ie. days since 1970.
This URL return to player actual video_id
https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA
Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
you can use Https url to login
i guess you are trying to login with ssh url when you say git push if it as asking only password consider you are connecting through ssh.better you use http url.
If you came across this error while using the command line its because you must be using php 7 to execute whatever it is you are trying to execute. What happened is that the code is trying to use an operator thats only available in php7+ and is causing a syntax error.
If you already have php 7+ on your computer try pointing the command line to the higher version of php you want to use.
export PATH=/usr/local/[php-7-folder]/bin/:$PATH
Here is the exact location that worked based off of my setup for reference:
export PATH=/usr/local/php5-7.1.4-20170506-100436/bin/:$PATH
The operator thats actually caused the break is the "null coalesce operator" you can read more about it here:
This is my OK code in QT 4.7:
//add combobox list
QString val;
ui->startPage->clear();
val = "http://www.work4blue.com";
ui->startPage->addItem(tr("Navigation page"),QVariant::fromValue(val));
val = "https://www.google.com";
ui->startPage->addItem("www.google.com",QVariant::fromValue(val));
val = "www.twitter.com";
ui->startPage->addItem("www.twitter.com",QVariant::fromValue(val));
val = "https://www.youtube.com";
ui->startPage->addItem("www.youtube.com",QVariant::fromValue(val));
// get current value
qDebug() << "current value"<<
ui->startPage->itemData(ui->startPage->currentIndex()).toString();
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
Something that (surprisingly) hasn't been mentioned here is simple concatenation.
Example:
foo = "seven"
print("She lives with " + foo + " small men")
Result:
She lives with seven small men
Additionally, as of Python 3, the %
method is deprecated. Don't use that.
The simplest way is:
const { exec } = require("child_process")
exec('yourApp').unref()
unref is necessary to end your process without waiting for "yourApp"
Here are the exec docs
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
it working perfect.
cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.ftp", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.ftp_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.http", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.http_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.share_proxy_settings", true); >>prefs.js
echo user_pref("network.proxy.socks", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.socks_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.ssl", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.ssl_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.type", 1); >>prefs.js
set ffile=
cd %windir%
Think your should look around: datetime.astimezone()
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
Also see pytz module - it's quite easy to use -- as example:
eastern = timezone('US/Eastern')
Example:
from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal
utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00
Swift 4:
To add an overlay, or the popup view You can also use the Container View with which you get a free View Controller ( you get the Container View from the usual object palette/library)
Steps:
Have a View (ViewForContainer in the pic) that holds this Container View, to dim it when the contents of Container View are displayed. Connect the outlet inside the first View Controller
Hide this View when 1st VC loads
To dim this View when the Container View content is displayed, set the Views Background to Black and opacity to 30%
You can use like
My table is bellow like..
<table>
<thead>
<tr>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr th:each="user: ${staffList}">
<td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
</tr>
</tbody>
</table>
Here is my controller ..
@GetMapping(value = "/details-view/{userId}")
public String details(@PathVariable String userId) {
Logger.getLogger(getClass().getName()).info("userId-->" + userId);
return "user-details";
}
Depending on the library you are using the standard GNU C Predefined Mathematical Constants are here... https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html
You already have them so why redefine them? Your system desktop calculators probably have them and are even more accurate so you could but just be sure you're not conflicting with existing defined ones to save on compile warnings as they tend to get defaults for things like that. Enjoy!
I had already been running a local server at the same port the session wanted to run on, and this caused the error. Shutting down that local server fixed this for me.
Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:
Html.Hidden("Name", "Value")
Will result in:
<input id="Name" name="Name" type="hidden" value="Value">
In your controller, you might have an action like:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
}
And a model like:
public class MyModel
{
public string Name { get; set; }
}
The raw Html.Hidden
we used above will get correlated to the Name
property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name
property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor
, you get protected from that:
Html.HiddenFor(x => x.Name, "Value");
Now, if you rename the Name
property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x.
.
If you're using ASP.NET Core and wonder why you get this message in one of your async controller methods, make sure you return a Task
rather than void
- ASP.NET Core disposes injected contexts.
(I'm posting this answer as this question is high in the search results to that exception message and it's a subtle issue - maybe it's useful to people who Google for it.)
Textarea has no value attribute, its value comes between tags, i.e: <textarea>my text</textarea>
, it is not like the input field (<input value="my text" />
). That's why attr doesn't work :)
Had some issue syntactically. This worked for me
<Text style={[styles.textStyle,{color: 'red'}]}> Hello </Text>
const styles = StyleSheet.create({
textStyle :{
textAlign: 'center',
fontFamily: 'Arial',
fontSize: 16
}
});
Let uses a more immediate block level limited scope whereas var is function scope or global scope typically.
It seems let was chosen most likely because it is found in so many other languages to define variables, such as BASIC, and many others.
encode function can help you here, encode returns an encoded version of the string
In [44]: str = "ABCD"
In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']
or you can use array module
In [49]: import array
In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])
Here is a way to remove a specific commit id knowing only the commit id you would like to remove.
git rebase --onto commit-id^ commit-id
Note that this actually removes the change that was introduced by the commit.
include_once('simple_html_dom.php');
$url="http://stackoverflow.com/questions/ask";
$html = file_get_html($url);
You can get the whole HTML code as an array (parsed form) using this code Download the 'simple_html_dom.php' file here http://sourceforge.net/projects/simplehtmldom/files/simple_html_dom.php/download
Example for escaped string with variable:
@some-variable-height: 10px;
...
div {
height: ~"calc(100vh - "@some-variable-height~")";
}
compiles to
div {
height: calc(100vh - 10px );
}
Set autoplay=0
<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen>
As seen here: Autoplay=0 Test
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
// header is present and set to "true"
}
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
Solution using Java 8
features such as Stream API
and Method references
new BufferedReader(new StringReader(myString))
.lines().forEach(System.out::println);
or
public void someMethod(String myLongString) {
new BufferedReader(new StringReader(myLongString))
.lines().forEach(this::parseString);
}
private void parseString(String data) {
//do something
}
The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:
I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm
Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.
At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)
Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..
I have used this small snippet. Might be slower but works every time.
for i in 'find . -type f -name "*.jar"'; do
jar tvf $i | grep "com.foo.bar.MyClass.clss";
if [ $? -eq 0 ]; then echo $i; fi;
done
The content length is just a HTTP header. You cannot trust it. Just read everything you can from the stream.
Available is definitely wrong. It's just the number of bytes that can be read without blocking.
Another issue is your resource handling. Closing the stream has to happen in any case. try/catch/finally will do that.
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
Consider creating an index. A dictionary can do the trick. If you need the list semantics, subclass and keep the index as a private member...
none of these methods worked for me, so I just solved this with CSS:
.upvotes:before {
content:"";
float: left;
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
The answer of Mark Byers is the optimal in this situation. Though in more complex situations you can take the select query that returns rowids and calculated values and attach it to the update query like this:
with t as (
-- Any generic query which returns rowid and corresponding calculated values
select t1.id as rowid, f(t2, t2) as calculatedvalue
from table1 as t1
join table2 as t2 on t2.referenceid = t1.id
)
update table1
set value = t.calculatedvalue
from t
where id = t.rowid
This approach lets you develop and test your select query and in two steps convert it to the update query.
So in your case the result query will be:
with t as (
select v.id as rowid, s.price_per_vehicle as calculatedvalue
from vehicles_vehicle v
join shipments_shipment s on v.shipment_id = s.id
)
update vehicles_vehicle
set price = t.calculatedvalue
from t
where id = t.rowid
Note that column aliases are mandatory otherwise PostgreSQL will complain about the ambiguity of the column names.
Simple as pie:
if !params[:one].nil? and !params[:two].nil?
#do something...
elsif !params[:one].nil?
#do something else...
elsif !params[:two].nil?
#do something extraordinary...
end
Modern browsers has support for CSS "scroll-behavior: smooth" property. So, we even don't need any Javascript at all for this. Just add this to the body element, and use usual anchors and links. scroll-behavior MDN docs
COUNT(1) is not substantially different from COUNT(*), if at all. As to the question of COUNTing NULLable COLUMNs, this can be straightforward to demo the differences between COUNT(*) and COUNT(<some col>)--
USE tempdb;
GO
IF OBJECT_ID( N'dbo.Blitzen', N'U') IS NOT NULL DROP TABLE dbo.Blitzen;
GO
CREATE TABLE dbo.Blitzen (ID INT NULL, Somelala CHAR(1) NULL);
INSERT dbo.Blitzen SELECT 1, 'A';
INSERT dbo.Blitzen SELECT NULL, NULL;
INSERT dbo.Blitzen SELECT NULL, 'A';
INSERT dbo.Blitzen SELECT 1, NULL;
SELECT COUNT(*), COUNT(1), COUNT(ID), COUNT(Somelala) FROM dbo.Blitzen;
GO
DROP TABLE dbo.Blitzen;
GO
No need to debate, just use the source. Here, SE 6 for Linux, make your own conclusions:
jlong os::javaTimeMillis() {
timeval time;
int status = gettimeofday(&time, NULL);
assert(status != -1, "linux error");
return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
}
jlong os::javaTimeNanos() {
if (Linux::supports_monotonic_clock()) {
struct timespec tp;
int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
assert(status == 0, "gettime error");
jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
return result;
} else {
timeval time;
int status = gettimeofday(&time, NULL);
assert(status != -1, "linux error");
jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
return 1000 * usecs;
}
}
If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
In the root create a .env file with:
VUE_APP_ENV_VARIABLE=value
And, if it's running, you need to restart serve so that the new env vars can be loaded.
With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).
According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.
Some custom swtich can be created like this. Allows multiple case execution as well
public class ContainsSwitch
{
List<ContainsSwitch> actionList = new List<ContainsSwitch>();
public string Value { get; set; }
public Action Action { get; set; }
public bool SingleCaseExecution { get; set; }
public void Perform( string target)
{
foreach (ContainsSwitch act in actionList)
{
if (target.Contains(act.Value))
{
act.Action();
if(SingleCaseExecution)
break;
}
}
}
public void AddCase(string value, Action act)
{
actionList.Add(new ContainsSwitch() { Action = act, Value = value });
}
}
Call like this
string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.Perform(m);
In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
In your local system right,
go to this url : http://localhost/phpmyadmin/
In this click mysql default db, after that browser user table to get existing username and password.
Won't simply concatenating the part of your path accomplish what you want?
$ base="/home/user1/MyFolder/"
$ subdir="subFold1"
$ new_path=$base$subdir
$ echo $new_path
/home/user1/MyFolder/subFold1
You can then create the folders/directories as needed.
One convention is to end directory paths with /
(e.g. /home/
) because paths starting with a / could be confused with the root directory. If a double slash (//
) is used in a path, it is also still correct. But, if no slash is used on either variable, it would be incorrect (e.g. /home/user1/MyFoldersubFold1
).
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
Any user with a valid shell in /etc/passwd
can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys
file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.
To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.
To use base_url()
(shorthand), you have to load the URL Helper
first
$this->load->helper('url');
Or you can autoload it by changing application/config/autoload.php
Or just use
$this->config->base_url();
Same applies to site_url()
.
Also I can see you are missing echo
(though its not your current problem), use the code below to solve the problem
<link rel="stylesheet" href="<?php echo base_url(); ?>css/default.css" type="text/css" />
The canvas
element provides a toDataURL
method which returns a data:
URL that includes the base64-encoded image data in a given format. For example:
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.
The toDataURL
method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.
For more information see the MDN docs on the canvas
API, which includes details on toDataURL
, and the Wikipedia article on the data:
URI scheme, which includes details on the format of the URI you'll receive from this call.
Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.
<?php
$terms = get_the_terms($product->ID, 'product_cat');
foreach ($terms as $term) {
$product_cat = $term->name;
echo $product_cat;
break;
}
?>
If you open the directory which it is trying to delete then also you will face same error so first close the folder.
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar")
. For UTC specify ZoneOffset.UTC
.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310). header('Content-Type: application/json; charset=utf-8');