This answer improves on a couple above (please vote them up), assuming that in addition to creating the one commit (no-parents no-history), you also want to retain all of the commit-data of that commit:
Of course the commit-SHA of the new/single commit will change, because it represents a new (non-)history, becoming a parentless/root-commit.
This can be done by reading git log
and setting some variables for git commit-tree
. Assuming that you want to create a single commit from master
in a new branch one-commit
, retaining the commit-data above:
git checkout -b one-commit master ## create new branch to reset
git reset --hard \
$(eval "$(git log master -n1 --format='\
COMMIT_MESSAGE="%B" \
GIT_AUTHOR_NAME="%an" \
GIT_AUTHOR_EMAIL="%ae" \
GIT_AUTHOR_DATE="%ad" \
GIT_COMMITTER_NAME="%cn" \
GIT_COMMITTER_EMAIL="%ce" \
GIT_COMMITTER_DATE="%cd"')" 'git commit-tree master^{tree} <<COMMITMESSAGE
$COMMIT_MESSAGE
COMMITMESSAGE
')
Nice that you brought this subject up.
This is an important thing/concept in git that a lof of git users would benefit from knowing. git rebase is a very powerful tool and enables you to squash commits together, remove commits etc. But as with any powerful tool, you basically need to know what you're doing or something might go really wrong.
When you are working locally and messing around with your local branches, you can do whatever you like as long as you haven't pushed the changes to the central repository. This means you can rewrite your own history, but not others history. By only messing around with your local stuff, nothing will have any impact on other repositories.
This is why it's important to remember that once you have pushed commits, you should not rebase them later on. The reason why this is important, is that other people might pull in your commits and base their work on your contributions to the code base, and if you later on decide to move that content from one place to another (rebase it) and push those changes, then other people will get problems and have to rebase their code. Now imagine you have 1000 developers :) It just causes a lot of unnecessary rework.
I removed the bin and obj folders from old C# projects using git on windows. Be careful with
git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD
It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.
git pull origin <branch> --allow-unrelated-histories
You will be routed to a Vim edit window:
git push --set-upstream origin <branch>
It looks like what you want to do is remove your first merge. You could follow the following procedure:
git checkout master # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull # or git merge remote/master
git merge topic
That would give you what you want.
If you don't care about the commit messages of the in-between commits, you can use
git reset --mixed <commit-hash-into-which-you-want-to-squash>
git commit -a --amend
You want to git rebase -i
to perform an interactive rebase.
If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2
, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.
Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f
and anybody sharing your code will have to jump through some hoops to pull your changes.
Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head
command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.
To query the remote (in this case origin
) for its HEAD
(typically master
), and set that as the default branch:
$ git remote set-head origin --auto
If you want to use a different default remote branch locally, you can specify that branch:
$ git remote set-head origin new-default
Once the default branch is set, you can use just the remote name in git rebase <remote>
and any other commands instead of explicit <remote>/<branch>
.
Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD
.
$ cat .git/refs/remotes/origin/HEAD
ref: refs/remotes/origin/master
See the git-remote man page for further details.
You can use git filter-branch for that. e.g.
git filter-branch --parent-filter \
'if test $GIT_COMMIT != <sha1ofB>; then cat; fi'
This results in AB-C throwing away the commit log of A.
Both git merge --squash
and git rebase --interactive
can produce a "squashed" commit.
But they serve different purposes.
will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch"
)
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):
git checkout stable
X stable
/
a---b---c---d---e---f---g tmp
to:
git merge --squash tmp
git commit -m "squash tmp"
X-------------------G stable
/
a---b---c---d---e---f---g tmp
and then deleting tmp
branch.
Note: git merge
has a --commit
option, but it cannot be used with --squash
. It was never possible to use --commit
and --squash
together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:
See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain
).
(Merged by Junio C Hamano -- gitster
-- in commit 33f2790, 25 Jul 2019)
merge
: refuse--commit
with--squash
Previously, when
--squash
was supplied, 'option_commit
' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using--commit
explicitly.
git/git
builtin/merge.c#cmd_merge()
now includes:
if (option_commit > 0)
die(_("You cannot combine --squash with --commit."));
replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:
git checkout tmp
git rebase -i stable
stable
X-------------------G tmp
/
a---b
If you choose to squash all commits of tmp
(but, contrary to merge --squash
, you can choose to replay some, and squashing others).
So the differences are:
squash
does not touch your source branch (tmp
here) and creates a single commit where you want.rebase
allows you to go on on the same source branch (still tmp
) with:
A simpler solution is git rebase <SHA1 of B> topic
. This works irrespective of where your HEAD
is.
We can confirm this behaviour from git rebase doc
<upstream>
Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch.
topic
too in the above command ?
git rebase <SHA1 of B> <SHA1 of topic>
This will also work but rebase then won't make Topic
point to new branch so created and HEAD
will be in detached state. So from here you have to manually delete old Topic
and create a new branch reference on new branch created by rebase.
-m
means the parent number.
From the git doc:
Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.
For example, if your commit tree is like below:
- A - D - E - F - master
\ /
B - C branch one
then git cherry-pick E
will produce the issue you faced.
git cherry-pick E -m 1
means using D-E
, while git cherry-pick E -m 2
means using B-C-E
.
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.
So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
I found one really interesting article on git rebase vs merge, thought of sharing it here
Here is another solution to resolve this issue
>git pull
>git commit -m "any meaning full message"
>git push
If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?
And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History
Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.
Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.
So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.
From latest master:
git checkout -b new-branch
Then
git merge --squash problem-branch
git commit -m "new message"
Resetting the branch to the dangling commit object of its old tip is of course the best solution, because it restores the previous state without expending any effort. But if you happen to have lost those commits (f.ex. because you garbage-collected your repository in the meantime, or this is a fresh clone), you can always rebase the branch again. The key to this is the --onto
switch.
Let’s say you had a topic branch imaginatively called topic
, that you branched off master
when the tip of master
was the 0deadbeef
commit. At some point while on the topic
branch, you did git rebase master
. Now you want to undo this. Here’s how:
git rebase --onto 0deadbeef master topic
This will take all commits on topic
that aren’t on master
and replay them on top of 0deadbeef
.
With --onto
, you can rearrange your history into pretty much any shape whatsoever.
Have fun. :-)
select * from employee_list order by salary desc limit 2;
Call the materialize css jquery code only after the html has rendered. So you can have a controller and then fire a service which calls the jquery code in the controller. This will render the select button alright. How ever if you try to use ngChange or ngSubmit it may not work due to the dynamic styling of the select tag.
Just do select date(timestamp_column)
and you would get the only the date part.
Sometimes doing select timestamp_column::date
may return date 00:00:00
where it doesn't remove the 00:00:00
part. But I have seen date(timestamp_column)
to work perfectly in all the cases. Hope this helps.
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(@"\", @"\\");
Include the content in {! <content> !}
.
Or just mydict.keys()
That's a builtin method call for dictionaries. Also explore mydict.values()
and mydict.items()
.
//Ah, OP post confused me.
Set MaximizeBox
and MinimizeBox
form properties to False
SELECT DISTINCT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name LIKE 'employee%'
AND TABLE_SCHEMA='YourDatabase'
Rails 4 (other Rails 4 answers have problems):
def change
change_column_null(:users, :admin, false, <put a default value here> )
# change_column(:users, :admin, :string, :default => "")
end
Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null
does exactly that. See documentation for more details.
Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.
As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':
So, in my case, ended like this:
if __name__ == '__main__':
import librosa
import os
import pandas as pd
run_my_program()
The .values()
method will return you a result of type ValuesQuerySet
which is typically what you need in most cases.
But if you wish, you could turn ValuesQuerySet
into a native Python list using Python list comprehension as illustrated in the example below.
result = Blog.objects.values() # return ValuesQuerySet object
list_result = [entry for entry in result] # converts ValuesQuerySet into Python list
return list_result
I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result
and actual_result
must be of the same type (e.g. dictionary).
actual_result = some_function()
expected_result = {
# dictionary content here ...
}
assert expected_result == actual_result
Bootstrap 3.0 version is tricky they will add fix for this issue and probably return container-fluid in Bootstrap 3.1. But until then here is a fix that I'm using:
First of, you would need custom container and set it to 100% width, and then you will need to fix row margin disposition, and navbar too if you have it:
/* Custom container */
.container-full {
margin: 0 auto;
width: 100%;
}
/*fix row -15px margin*/
.container-fluid {
padding: 0 15px;
}
/*fix navbar margin*/
.navbar{
margin: 0 -15px;
}
/*fix navbar-right margin*/
.navbar-nav.navbar-right:last-child {
margin-right: 0px;
}
You can stack container-full and container-fluid classes on root div, and you can use container-fluid later on.
Hope it helps, if you need more info let me know.
From MSDN:
1.At compile time, attributes of partial-type definitions are merged. For example, consider the following declarations:
[SerializableAttribute]
partial class Moon { }
[ObsoleteAttribute]
partial class Moon { }
They are equivalent to the following declarations:
[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }
The following are merged from all the partial-type definitions:
XML comments
interfaces
generic-type parameter attributes
class attributes
members
2.Another thing, nested partial classes can be also partial:
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.
Then try the following:
@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody Representation authenticate(@PathVariable("email") String anEmailAddress, MultiValueMap paramMap) throws Exception {
if(paramMap == null && paramMap.get("password") == null) {
throw new IllegalArgumentException("Password not provided");
}
return null;
}
Note that removed the annotation @RequestBody
answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring
Polymorphism
1. Static binding/Compile-Time binding/Early binding/Method overloading.(in same class)
2. Dynamic binding/Run-Time binding/Late binding/Method overriding.(in different classes)
class Calculation {
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]) {
Calculation obj=new Calculation();
obj.sum(10,10,10); // 30
obj.sum(20,20); //40
}
}
class Animal {
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();//output: Animals can move
b.move();//output:Dogs can walk and run
}
}
To extract without conversion I use a context menu entry - as file manager custom action in Linux - to run the following (after having checked what audio type the video contains; example for video containing ogg
audio):
bash -c 'ffmpeg -i "$0" -map 0:a -c:a copy "${0%%.*}".ogg' %f
which is based on the ffmpeg command ffmpeg -i INPUT -map 0:a -c:a copy OUTPUT
.
I have used -map 0:1
in that without problems, but, as said in a comment by @LordNeckbeard, "Stream 0:1
is not guaranteed to always be audio. Using -map 0:a
instead of -map 0:1
will avoid ambiguity."
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
beforeShow: function(el) {
if ( el.getAttribute("readonly") !== null ) {
if ( (el.value == null) || (el.value == '') ) {
$(el).datepicker( "option", "minDate", +1 );
$(el).datepicker( "option", "maxDate", -1 );
} else {
$(el).datepicker( "option", "minDate", el.value );
$(el).datepicker( "option", "maxDate", el.value );
}
}
},
There is no more plugin in netbeans 12. In case someone comes to this page. Tools->Options->Appearance->Look and feel->Flatlaf Dark
Start with root user or with sudo, it works fine, here is sample output:
[ec2-user@ip-172-31-12-164 ~]$ service httpd start
Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:80
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
**[FAILED]**
[ec2-user@ip-172-31-12-164 ~]$ sudo service httpd start
Starting httpd: [ OK ]
[ec2-user@ip-172-31-12-164 ~]$ sudo service httpd status
httpd (pid 3077) is running...
<a href="url" target="_blank"> <input type="button" value="fake button" /> </a>
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
To add an extension to serve in IIS follow -
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
I don't know why anyone told you that catching runtime exceptions was bad.
Use valueOf
and catching IllegalArgumentException
is fine for converting/checking a string to an enum.
We can use git svn clone
commands as below.
svn log -q <SVN_URL> | awk -F '|' '/^r/ {sub("^ ", "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > authors.txt
Above command will create authors file from SVN commits.
svn log --stop-on-copy <SVN_URL>
Above command will give you first revision number when your SVN project got created.
git svn clone -r<SVN_REV_NO>:HEAD --no-minimize-url --stdlayout --no-metadata --authors-file authors.txt <SVN_URL>
Above command will create the Git repository in local.
Problem is that it won't convert branches and tags to push. You will have to do them manually. For example below for branches:
$ git remote add origin https://github.com/pankaj0323/JDProjects.git
$ git branch -a
* master
remotes/origin/MyDevBranch
remotes/origin/tags/MyDevBranch-1.0
remotes/origin/trunk
$$ git checkout -b MyDevBranch origin/MyDevBranch
Branch MyDevBranch set up to track remote branch MyDevBranch from origin.
Switched to a new branch 'MyDevBranch'
$ git branch -a
* MyDevBranch
master
remotes/origin/MyDevBranch
remotes/origin/tags/MyDevBranch-1.0
remotes/origin/trunk
$
For tags:
$git checkout origin/tags/MyDevBranch-1.0
Note: checking out 'origin/tags/MyDevBranch-1.0'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at 3041d81... Creating a tag
$ git branch -a
* (detached from origin/tags/MyDevBranch-1.0)
MyDevBranch
master
remotes/origin/MyDevBranch
remotes/origin/tags/MyDevBranch-1.0
remotes/origin/trunk
$ git tag -a MyDevBranch-1.0 -m "creating tag"
$git tag
MyDevBranch-1.0
$
Now push master, branches and tags to remote git repository.
$ git push origin master MyDevBranch MyDevBranch-1.0
Counting objects: 14, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (14/14), 2.28 KiB | 0 bytes/s, done.
Total 14 (delta 3), reused 0 (delta 0)
To https://github.com/pankaj0323/JDProjects.git
* [new branch] master -> master
* [new branch] MyDevBranch -> MyDevBranch
* [new tag] MyDevBranch-1.0 -> MyDevBranch-1.0
$
svn2git utility removes manual efforts with branches and tags.
Install it using command sudo gem install svn2git
. After that run below command.
$ svn2git <SVN_URL> --authors authors.txt --revision <SVN_REV_NO>
Now you can list the branches, tags and push them easily.
$ git remote add origin https://github.com/pankaj0323/JDProjects.git
$ git branch -a
MyDevBranch
* master
remotes/svn/MyDevBranch
remotes/svn/trunk
$ git tag
MyDevBranch-1.0
$ git push origin master MyDevBranch MyDevBranch-1.0
Imagine you have 20 branches and tags, obviously svn2git will save you a lot of time and that's why I like it better than native commands. It's a nice wrapper around native git svn clone
command.
For a complete example, refer my blog entry.
An important feature of a linked list (which I didn't read in another answer) is the concatenation of two lists. With an array this is O(n) (+ overhead of some reallocations) with a linked list this is only O(1) or O(2) ;-)
Important: For Java its LinkedList
this is not true! See Is there a fast concat method for linked list in Java?
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/
extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
if indexPath.item == 0 {
return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
}
return UIEdgeInsets.zero
}
}
I got a better option to get the duplicate records in a table
SELECT x.studid, y.stdname, y.dupecount
FROM student AS x INNER JOIN
(SELECT a.stdname, COUNT(*) AS dupecount
FROM student AS a INNER JOIN
studmisc AS b ON a.studid = b.studid
WHERE (a.studid LIKE '2018%') AND (b.studstatus = 4)
GROUP BY a.stdname
HAVING (COUNT(*) > 1)) AS y ON x.stdname = y.stdname INNER JOIN
studmisc AS z ON x.studid = z.studid
WHERE (x.studid LIKE '2018%') AND (z.studstatus = 4)
ORDER BY x.stdname
Result of the above query shows all the duplicate names with unique student ids and number of duplicate occurances
All of this assumes core.autocrlf=true
Original error:
warning: LF will be replaced by CRLF
The file will have its original line endings in your working directory.
What the error SHOULD read:
warning: LF will be replaced by CRLF in your working directory
The file will have its original LF line endings in the git repository
Explanation here:
The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.
Basically, a local file that was previously LF will now have CRLF locally
Another method to try out.
Also select
could be replaced when you set the initial column into a Range object. Performance wise it helps.
Dim rng as Range
Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.
'-- here is your loop
i = 1
Do
'-- do something: e.g. show the address of the column that you are currently in
Msgbox rng.offset(0,i).Address
i = i + 1
Loop Until i > 10
** Two methods to get the column name using column number**
code
colName = Split(Range.Offset(0,i).Address, "$")(1)
code
Function myColName(colNum as Long) as String
myColName = Left(Range(0, colNum).Address(False, False), _
1 - (colNum > 10))
End Function
As Bokan has mentioned, you can up the memory if available, and he is right on how counter productive setting TTL to 0 is.
NotE: This is how I fixed this error for my particular problem. Its a generic issue that can be caused by allot of things so only follow the below if you get the error and you think its caused by duplicate PHP files being loaded into APC.
The issue I was having was when I released a new version of my PHP application. Ie replaced all my .php files with new ones APC would load both versions into cache.
Because I didnt have enough memory for two versions of the php files APC would run out of memory.
There is a option called apc.stat to tell APC to check if a particular file has changed and if so replace it, this is typically ok for development because you are constantly making changes however on production its usually turned off as it was with in my case - http://www.php.net/manual/en/apc.configuration.php#ini.apc.stat
Turning apc.stat on would fix this issue if you are ok with the performance hit.
The solution I came up with for my problem is check if the the project version has changed and if so empty the cache and reload the page.
define('PROJECT_VERSION', '0.28');
if(apc_exists('MY_APP_VERSION') ){
if(apc_fetch('MY_APP_VERSION') != PROJECT_VERSION){
apc_clear_cache();
apc_store ('MY_APP_VERSION', PROJECT_VERSION);
header('Location: ' . 'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
exit;
}
}else{
apc_store ('MY_APP_VERSION', PROJECT_VERSION);
}
Say the hierarchy is C->B->A
with A being the base class.
I think there's more to fixing this than renaming a method. That will work but is that a fix?
One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A
Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.
char c = '5'
A char
(1 byte) is allocated on stack at address 0x12345678
.
char *d = &c;
You obtain the address of c
and store it in d
, so d = 0x12345678
.
int *e = (int*)d;
You force the compiler to assume that 0x12345678
points to an int
, but an int is not just one byte (sizeof(char) != sizeof(int)
). It may be 4 or 8 bytes according to the architecture or even other values.
So when you print the value of the pointer, the integer is considered by taking the first byte (that was c
) and other consecutive bytes which are on stack and that are just garbage for your intent.
Modern Solution
The result is that the circle never gets distorted and the text stays exactly in the middle of the circle - vertically and horizontally.
.circle {
background: gold;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex; /* or inline-flex */
align-items: center;
justify-content: center;
}
_x000D_
<div class="circle">text</div>
_x000D_
Simple and easy to use. Enjoy!
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
This works:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
obj= "foo"
is correct; obj="foo"
is not.i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
Is the snippet you posted just a sample to show what you are trying to do?
The reason I ask is that you've named a method increment
, but you seem to be using that to set the value of a text label, rather than incrementing a value.
If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g
You declare a property count
and your increment
action sets this value to whatever, and then in IB, you bind the label's text to the value of count
. As long as you follow Key Value Coding (KVC) with count
, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.
To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example
insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);
now, select the inserted record.
select ename, hiredate from emp where ename='Mac';
the result is
ENAME HIREDATE
Mac 06-JAN-13
voila, now your actual date format is found.
It's not that 0 = true
and 1 = false
. It is: zero means no failure (success) and non-zero means failure (of type N).
While the selected answer is technically "true" please do not put return 1
** in your code for false. It will have several unfortunate side effects.
The bash manual says (emphasis mine)
return [n]
Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function.
Therefore, we don't have to EVER use 0 and 1 to indicate True and False. The fact that they do so is essentially trivial knowledge useful only for debugging code, interview questions, and blowing the minds of newbies.
The bash manual also says
otherwise the function’s return status is the exit status of the last command executed
The bash manual also says
($?) Expands to the exit status of the most recently executed foreground pipeline.
Whoa, wait. Pipeline? Let's turn to the bash manual one more time.
A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.
Yes. They said 1 command is a pipeline. Therefore, all 3 of those quotes are saying the same thing.
$?
tells you what happened last.So, while @Kambus demonstrated that with such a simple function, no return
is needed at all. I think
was unrealistically simple compared to the needs of most people who will read this.
return
?If a function is going to return its last command's exit status, why use return
at all? Because it causes a function to stop executing.
01 function i_should(){
02 uname="$(uname -a)"
03
04 [[ "$uname" =~ Darwin ]] && return
05
06 if [[ "$uname" =~ Ubuntu ]]; then
07 release="$(lsb_release -a)"
08 [[ "$release" =~ LTS ]]
09 return
10 fi
11
12 false
13 }
14
15 function do_it(){
16 echo "Hello, old friend."
17 }
18
19 if i_should; then
20 do_it
21 fi
Line 04
is an explicit[-ish] return true because the RHS of &&
only gets executed if the LHS was true
Line 09
returns either true or false matching the status of line 08
Line 13
returns false because of line 12
(Yes, this can be golfed down, but the entire example is contrived.)
# Instead of doing this...
some_command
if [[ $? -eq 1 ]]; then
echo "some_command failed"
fi
# Do this...
some_command
status=$?
if ! $(exit $status); then
echo "some_command failed"
fi
Notice how setting a status
variable demystifies the meaning of $?
. (Of course you know what $?
means, but someone less knowledgeable than you will have to Google it some day. Unless your code is doing high frequency trading, show some love, set the variable.) But the real take-away is that "if not exist status" or conversely "if exit status" can be read out loud and explain their meaning. However, that last one may be a bit too ambitious because seeing the word exit
might make you think it is exiting the script, when in reality it is exiting the $(...)
subshell.
** If you absolutely insist on using return 1
for false, I suggest you at least use return 255
instead. This will cause your future self, or any other developer who must maintain your code to question "why is that 255?" Then they will at least be paying attention and have a better chance of avoiding a mistake.
Using Node.removeChild() does the job for you, simply use something like this:
var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);
In DOM 4, the remove method applied, but there is a poor browser support according to W3C:
The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.
But you can use remove method if you using jQuery...
$('#left-section').remove(); //using remove method in jQuery
Also in new frameworks like you can use conditions to remove an element, for example *ngIf
in Angular and in React, rendering different views, depends on the conditions...
Visual Studio Test Edition 2010 (2008 good too). This is a really easy and powerful tool to create web/load tests with.
The bonus with this tool when using against Windows servers is that you get integrated access to all the perfmon server stats in your report. Really useful.
The other bonus is that with Visual Studio project you can integrate a "Performance Session" that will profile the code execution of your website.
If you are serving webpages from a windows server, this is the best tool out there.
There is a separate and expensive licence required to use several machines to load test the application however.
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?
No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:
var someVar = options.filters.firstName; //Returns 'abc'
Or by iterating over them using the for ... in
loop:
for(var p in options.filters) {
var someVar = options.filters[p]; //Returns the property being iterated
}
@echo off
Setlocal enabledelayedexpansion
Set 1=%1
Set 1=!1:"=!
Echo !1!
Echo "!1!"
Set 1=
Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.
With numpy :
im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])
Give RGB vector of the pixel in position (0,0)
The easiest way would be to specify
SELECT productid FROM product where purchase_date > sysdate-30;
Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.
If you want to remove the time conponent when comparing..
SELECT productid FROM product where purchase_date > trunc(sysdate-30);
And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.
SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')
And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.
I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:
select Detail.ReceiptDate AS 'DATE',
SUM(TotalMailed),
SUM(TotalReturnMail),
SUM(TraceReturnedMail)
from
(
select SentDate AS 'ReceiptDate',
count('TotalMailed') AS TotalMailed,
0 as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
count(TotalReturnMail) as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY MDE.ReturnMailDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
0 as TotalReturnMail,
count(TraceReturnedMail) as TraceReturnedMail
from MailDataExtract MDE
inner join DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate
) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
Typo: java -cp .:sqlitejdbc-v056.jar Test
should be: java -cp .:sqlitejdbc-v056.jar; Test
notice the semicolon after ".jar" i hope that helps people, could cause a lot of hassle
On Debug
Copy Paste This code inside OnCreate method
try {
PackageInfo info = getPackageManager().getPackageInfo(
getApplication().getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
Log.d("KeyHash e1",e.getLocalizedMessage() +"");
} catch (NoSuchAlgorithmException e) {
Log.d("KeyHash e2", e.getLocalizedMessage() +"");
}
Open Logcat and Filter/find 'D/KeyHash:'
D/KeyHash: D5uFR+65hafzotdih/dOfp14FpE=
Then Open https://developers.facebook.com/ and Open YourApp/Setting/Basic
Scroll down to Android Section Then Paste the Key Hashes and Save
sudo npm install npm@latest -g
I think the best and safest way to read strings entered by the user is using getline()
Here's an example how to do this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *buffer = NULL;
int read;
unsigned int len;
read = getline(&buffer, &len, stdin);
if (-1 != read)
puts(buffer);
else
printf("No line read...\n");
printf("Size read: %d\n Len: %d\n", read, len);
free(buffer);
return 0;
}
It is a file ext that some folks used for a while to denote that it was PHP generated HTML. As servers like Apache don't care what you use as a file ext as long as it is mapped to something, you could go ahead and call all your PHP files .jimyBobSmith and it would happily run them. PHTML just happened to be a trend that caught on for a while.
As of July 2016:
Short Answer:
If your game is released for iOS 9.0 or newer, you can have maximum app size of 400 MB for the size of the Mach-O binary file (for example, app_name.app/app_name).
Your app’s total uncompressed size must be less than 4 Gb.
Long Answer:
Your app’s total uncompressed size must be less than 4 billion bytes. Each Mach-O executable file (for example, app_name.app/app_name) must not exceed these limits:
For apps whose MinimumOSVersion is less than 7.0: maximum of 80 MB for the total of all __TEXT sections in the binary.
For apps whose MinimumOSVersion is 7.x through 8.x: maximum of 60 MB per slice for the __TEXT section of each architecture slice in the binary.
For apps whose MinimumOSVersion is 9.0 or greater: maximum of 400 MB for the size of the Mach-O binary file.
However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads. Abnormally large build files are usually the result of storing data, such as images, inside the compiled binary itself instead of as a resource inside your app bundle. If you are compiling an image or large dataset into your binary, it would be best to split this data out into a resource that is loaded dynamically by your app.
Here is the link to Apple Developer Guide that contains the info I posted above:
You can go to the section "Submitting the App for App Review" on the link above to read more on the info I posted above.
As a beginner who stumbled across this thread, I'd like to add a python-for-dummies adaptation of abevieiramota's very neat answer (because I'm at the level that I had to look up 'ravel' to work out what their code was doing):
import numpy as np
import matplotlib.pyplot as plt
fig, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plt.subplots(2,3)
axlist = [ax1,ax2,ax3,ax4,ax5,ax6]
first = ax1.imshow(np.random.random((10,10)), vmin=0, vmax=1)
third = ax3.imshow(np.random.random((12,12)), vmin=0, vmax=1)
fig.colorbar(first, ax=axlist)
plt.show()
Much less pythonic, much easier for noobs like me to see what's actually happening here.
Note I provided a more in-depth answer here
It's the most idiomatic way.
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = () => <div>Hello</div>;
const WrappedApp = () => (
<Wrapper>
<App/>
</Wrapper>
);
Note that children
is a "special prop" in React, and the example above is syntactic sugar and is (almost) equivalent to <Wrapper children={<App/>}/>
You can use an Higher Order Component (HOC). They have been added to the official doc recently.
// Signature may look fancy but it's just
// a function that takes a component and returns a new component
const wrapHOC = (WrappedComponent) => (props) => (
<div>
<div>header</div>
<div><WrappedComponent {...props}/></div>
<div>footer</div>
</div>
)
const App = () => <div>Hello</div>;
const WrappedApp = wrapHOC(App);
This can lead to (little) better performances because the wrapper component can short-circuit the rendering one step ahead with shouldComponentUpdate, while in the case of a runtime wrapper, the children prop is likely to always be a different ReactElement and cause re-renders even if your components extend PureComponent.
Notice that connect
of Redux used to be a runtime wrapper but was changed to an HOC because it permits to avoid useless re-renders if you use the pure
option (which is true by default)
You should never call an HOC during the render phase because creating React components can be expensive. You should rather call these wrappers at initialization.
Note that when using functional components like above, the HOC version do not provide any useful optimisation because stateless functional components do not implement shouldComponentUpdate
More explanations here: https://stackoverflow.com/a/31564812/82609
There is already a good solution to the problem you are having. Everyone has been forgetting the CSS property font-size
: the last but not least solution. One can decrease the font size by 2 to 3 pixels. It may still be visible to the user and for somewhat you can decrease the width of the table. This worked for me. My table has 5 columns with 4 showing perfectly, but the fifth column went out of the viewport. To fix the problem, I decreased the font size and all five columns were fitted onto the screen.
table th td {
font-size: 14px;
}
For your information, if your table has too many columns and you are not able to decrease, then make the font size small. It will get rid of the horizontal scroll. There are two advantages: your style for mobile web will remain the same (good without horizontal scroll) and when user sees small sizes, most users will zoom into the table to their comfort level.
Javascript to be placed in header:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
Here goes iframe html code:
<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>
Css stylesheet
>
.spec_iframe {
width: 100%;
overflow: hidden;
}
It would be difficult to say if there's any issue with your code without checking it out, however this happens to me quite a lot in (Version 6.0 (6A216f)). I usually have to reset the simulator's Content and Settings and/or restart xCode to get it working again. Try those and see if that solves the problem.
refer here: https://nathanhoad.net/how-to-colours-in-git/
steps:
Open ~/.gitconfig for editing
vi ~/.gitconfig
Paste following code:
[color]
ui = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
Save the file.
Just change any file in your local repo and do
git status
Update: In Python 2.6 and onwards, consider whether the namedtuple
data structure suits your needs:
>>> from collections import namedtuple
>>> MyStruct = namedtuple('MyStruct', 'a b d')
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s
MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s.a
1
>>> s.b
{'c': 2}
>>> s.c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyStruct' object has no attribute 'c'
>>> s.d
['hi']
The alternative (original answer contents) is:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
Then, you can use:
>>> args = {'a': 1, 'b': 2}
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s.a
1
>>> s.b
2
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
Your Delivery
class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery
class. You need to either make Delivery
public, or restrict the visibility of the thelivery
property.
You can't override a static method, so making it abstract would be meaningless. Moreover, a static method in an abstract class would belong to that class, and not the overriding class, so couldn't be used anyway.
The first screenshot in your question is not a public widget. The support SearchView (android.support.v7.widget.SearchView
) mimics Android 5.0 Lollipop's SearchView (android.widget.SearchView
). Your second screenshot is used by other material designed apps like Google Play.
The SearchView in your first screenshot is used in Drive, YouTube and other closed source Google Apps. Fortunately, it is also used in the Android 5.0 Dialer. You can try to backport the view, but it uses some 5.0 APIs.
The classes which you will want to look at are:
SearchEditTextLayout, AnimUtils, and DialtactsActivity to understand how to use the View. You will also need resources from ContactsCommon.
Best of luck.
Yes, you need to make getInstance()
synchronized. If it's not there might arise a situation where multiple instances of the class can be made.
Consider the case where you have two threads that call getInstance()
at the same time. Now imagine T1 executes just past the instance == null
check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance()
synchronized prevents this problem.
There a few ways to make singletons thread-safe, but making getInstance()
synchronized is probably the simplest.
I encountered this problem in Laravel 5.8, what I did was to do composer require
for each library and all where installed correctly.
Like so:
instead of adding it to the composer.json file or specifying a version:
composer require msurguy/honeypot: dev-master
I instead did without specifying any version:
composer require msurguy/honeypot
I hope it helps, thanks
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
There are a few places you can do versioning in a REST API:
As noted, in the URI. This can be tractable and even esthetically pleasing if redirects and the like are used well.
In the Accepts: header, so the version is in the filetype. Like 'mp3' vs 'mp4'. This will also work, though IMO it works a bit less nicely than...
In the resource itself. Many file formats have their version numbers embedded in them, typically in the header; this allows newer software to 'just work' by understanding all existing versions of the filetype while older software can punt if an unsupported (newer) version is specified. In the context of a REST API, it means that your URIs never have to change, just your response to the particular version of data you were handed.
I can see reasons to use all three approaches:
As of python 3.5.2, you can use:
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c+=1
set OUTPUT_FILE_NAME=output_%c%.txt
echo Output file is %OUTPUT_FILE_NAME%
echo %%i, %c%
)
Put a global statement at the top of your function and you should be good:
def onLoadFinished(result):
global feed
...
To demonstrate what I mean, look at this little test:
x = 0
def t():
x += 1
t()
this blows up with your exact same error where as:
x = 0
def t():
global x
x += 1
t()
does not.
The reason for this is that, inside t
, Python thinks that x
is a local variable. Furthermore, unless you explicitly tell it that x
is global, it will try to use a local variable named x
in x += 1
. But, since there is no x
defined in the local scope of t
, it throws an error.
function my_simple_crypt( $string, $action = 'e' ) {
// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
The strncpy()
function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy()
function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits
Also for POSIX API functions like read()
which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy()
.
In your example code, index
is actually not an index, but a count
- it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated
You can use a conditional expression:
x if x is not None else some_value
Example:
In [22]: x = None
In [23]: print x if x is not None else "foo"
foo
In [24]: x = "bar"
In [25]: print x if x is not None else "foo"
bar
Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}
x y
matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.
The asterisk *
matches any element.
Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors
If you have a unique column in your table (e.g. tableid) then try this.
SELECT EMAIL FROM TABLE WHERE TABLEID IN
(SELECT MAX(TABLEID), EMAIL FROM TABLE GROUP BY EMAIL)
This code puts the above all together and restarts the current wpf app with admin privs:
if (IsAdministrator() == false)
{
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)
Update: The app manifest way is preferred:
Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.
A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.
Yes.
Add DisableCacheViewer Registry Key
Create a new dword key under HKLM\Software\Microsoft\Fusion\ with the name DisableCacheViewer and set it’s [DWORD] value to 1.
Go back to Windows Explorer to the assembly folder and it will be the normal file system view.
If you use Google Guava (and if you don't, you should), you can call: ByteStreams.toByteArray(InputStream)
or Files.toByteArray(File)
To obtain all the rows that contains an empty cell in in a particular column.
DF_new_row=DF_raw.loc[DF_raw['columnname']=='']
This will give the subset of DF_raw, which satisfy the checking condition.
i had the same problem i had linked jquery twice . The later version was overwriting my plugin.
I just removed the later jquery it started working.
As of PowerShell 6.0, Split-Path
has an -Extenstion
parameter. This means you can do:
$path | Split-Path -Extension
or
Split-Path -Path $path -Extension
For $path = "test.txt"
both versions will return .txt
, inluding the full stop.
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK) Array.Resize(ref youur_array_name, your_array_name.Length + 1);
your_array_name[your_array_name.Length - 1] = "new item";
If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.
You could just use glob
with recursive = true
, the pattern **
will match any files and zero or more directories, subdirectories and symbolic links to directories.
import glob, os
os.chdir("C:\\Users\\username\\Desktop\\MAIN_DIRECTORY")
for file in glob.glob("*/.csv", recursive = true):
print(file)
To get the entire contents of a file:
$content = [IO.File]::ReadAllText(".\test.txt")
Number of lines:
([IO.File]::ReadAllLines(".\test.txt")).length
or
(gc .\test.ps1).length
Sort of hackish to include trailing empty line:
[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count
wrap a <span>
around those words and style with the appropriate color
now is the time for <span style='color:orange'>all good men</span> to come to the
I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.
I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL
int iSizeOfArray(int* &piArray) {
piArray = new int[iNumberOfElements];
...
return iNumberOfElements;
}
It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.
Explicit Merge: Creates a new merge commit. (This is what you will get if you used --no-ff
.)
Fast Forward Merge: Forward rapidly, without creating a new commit:
Rebase: Establish a new base level:
Squash: Crush or squeeze (something) with force so that it becomes flat:
I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:
SELECT COUNT(id)
FROM stats
WHERE YEAR(record_date) = 2009
GROUP BY MONTH(record_date)
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
On Excel 2010 try this:
There are a variety of accurate answers here, but here is the most concise code for several different variations. For each variation, the top line shows the full syntax and the bottom shows terse syntax.
Item (2) is a more concise form of the answers from Jon Z and manojlds, while item (1) is equivalent to the answers from vikas368 and buygrush.
List FileInfo objects for all files containing pattern:
Get-ChildItem -Recurse filespec | Where-Object { Select-String pattern $_ -Quiet }
ls -r filespec | ? { sls pattern $_ -q }
List file names for all files containing pattern:
Get-ChildItem -Recurse filespec | Select-String pattern | Select-Object -Unique Path
ls -r filespec | sls pattern | select -u Path
List FileInfo objects for all files not containing pattern:
Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) }
ls -r filespec | ? { !(sls pattern $_ -q) }
List file names for all files not containing pattern:
(Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) }).FullName
(ls -r filespec | ? { !(sls pattern $_ -q) }).FullName
You can apply click
on body
of document and cancel click
processing if the click
event is generated by div with id menu_content
, This will bind event to single element and saving binding of click
with every element except menu_content
$('body').click(function(evt){
if(evt.target.id == "menu_content")
return;
//For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
if($(evt.target).closest('#menu_content').length)
return;
//Do processing of click event here for every element except with id menu_content
});
Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.
Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.
For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0)
So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.
Thanks again!! :)
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
With c++11, there actually is an alternative: writing a simple templatized custom iterator.
let's assume your enum is
enum class foo {
one,
two,
three
};
This generic code will do the trick, quite efficiently - place in a generic header, it'll serve you for any enum you may need to iterate over:
#include <type_traits>
template < typename C, C beginVal, C endVal>
class Iterator {
typedef typename std::underlying_type<C>::type val_t;
int val;
public:
Iterator(const C & f) : val(static_cast<val_t>(f)) {}
Iterator() : val(static_cast<val_t>(beginVal)) {}
Iterator operator++() {
++val;
return *this;
}
C operator*() { return static_cast<C>(val); }
Iterator begin() { return *this; } //default ctor is good
Iterator end() {
static const Iterator endIter=++Iterator(endVal); // cache it
return endIter;
}
bool operator!=(const Iterator& i) { return val != i.val; }
};
You'll need to specialize it
typedef Iterator<foo, foo::one, foo::three> fooIterator;
And then you can iterate using range-for
for (foo i : fooIterator() ) { //notice the parentheses!
do_stuff(i);
}
The assumption that you don't have gaps in your enum is still true; there is no assumption on the number of bits actually needed to store the enum value (thanks to std::underlying_type)
I prefer to use length
on the vertical-align. This aligns the baseline of the element at the given length above the baseline of its parent.
sup {
font-size: .83em;
vertical-align: 0.25em;
line-height: 0;
}
By chance: Default error pages often contain detailed information, e.g.
Apache/{Version} ({OS}) {Modules} PHP/{Version} {Modules} Server at {Domain}
Not so easy: Find out which versions of PHP applications run on the server and which version of PHP they require.
Another approach, only mentioned for the sake of completeness; please forget after reading: You could (but you won't!) detect the PHP version by trying known exploits.
There is also an easy way for copying via the clipboard:
Give KineticJS a try - you can define a Spline with an array of points. Here's an example:
Old url: http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-spline-tutorial/
See archive url: https://web.archive.org/web/20141204030628/http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-spline-tutorial/
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.
Look into composite formatting:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
You could also write (although it's not really recommended):
Console.WriteLine(mon + "." + da + "." + yer);
And, with the release of C# 6.0, you have string interpolation expressions:
Console.WriteLine($"{mon}.{da}.{yer}"); // note the $ prefix.
Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.
How many types do you plan to deal with?
UPDATE:
If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):
package generics;
public interface XmlGenerator<T>
{
String getXml(T value);
}
And the concrete implementation XmlGeneratorImpl:
package generics;
public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
private Class<T> valueType;
private static final int DEFAULT_CAPACITY = 1024;
public static void main(String [] args)
{
Integer x = 42;
String y = "foobar";
XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);
System.out.println("integer: " + intXmlGenerator.getXml(x));
System.out.println("string : " + stringXmlGenerator.getXml(y));
}
public XmlGeneratorImpl(Class<T> clazz)
{
this.valueType = clazz;
}
public String getXml(T value)
{
StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);
appendTag(builder);
builder.append(value);
appendTag(builder, false);
return builder.toString();
}
private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }
private void appendTag(StringBuilder builder, boolean isClosing)
{
String valueTypeName = valueType.getName();
builder.append("<").append(valueTypeName);
if (isClosing)
{
builder.append("/");
}
builder.append(">");
}
}
If I run this, I get the following result:
integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>
I don't know if this is what you had in mind.
You will need to change the configure port of either Apache or Nginx. After you do this you will need to restart the reconfigured servers, using the 'service' command you used.
Apache
Edit
sudo subl /etc/apache2/ports.conf
and change the 80 on the following line to something different :
Listen 80
If you just change the port or add more ports here, you will likely also have to change the VirtualHost statement in
sudo subl /etc/apache2/sites-enabled/000-default.conf
and change the 80 on the following line to something different :
<VirtualHost *:80>
then restart by :
sudo service apache2 restart
Nginx
Edit
/etc/nginx/sites-enabled/default
and change the 80 on the following line :
listen 80;
then restart by :
sudo service nginx restart
On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR
make variable, so you can often do:
make install DESTDIR=/tmp/myinst/
sudo cp -va /tmp/myinst/ /
The advantage of this approach is that make install
don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
When a process needs to fetch data from a disk, it effectively stops running on the CPU to let other processes run because the operation might take a long time to complete – at least 5ms seek time for a disk is common, and 5ms is 10 million CPU cycles, an eternity from the point of view of the program!
From the programmer point of view (also said "in userspace"), this is called a blocking system call. If you call write(2)
(which is a thin libc wrapper around the system call of the same name), your process does not exactly stop at that boundary; it continues, in the kernel, running the system call code. Most of the time it goes all the way up to a specific disk controller driver (filename ? filesystem/VFS ? block device ? device driver), where a command to fetch a block on disk is submitted to the proper hardware, which is a very fast operation most of the time.
THEN the process is put in sleep state (in kernel space, blocking is called sleeping – nothing is ever 'blocked' from the kernel point of view). It will be awakened once the hardware has finally fetched the proper data, then the process will be marked as runnable and will be scheduled. Eventually, the scheduler will run the process.
Finally, in userspace, the blocking system call returns with proper status and data, and the program flow goes on.
It is possible to invoke most I/O system calls in non-blocking mode (see O_NONBLOCK
in open(2)
and fcntl(2)
). In this case, the system calls return immediately and only report submitting the disk operation. The programmer will have to explicitly check at a later time whether the operation completed, successfully or not, and fetch its result (e.g., with select(2)
). This is called asynchronous or event-based programming.
Most answers here mentioning the D state (which is called TASK_UNINTERRUPTIBLE
in the Linux state names) are incorrect. The D state is a special sleep mode which is only triggered in a kernel space code path, when that code path can't be interrupted (because it would be too complex to program), with the expectation that it would block only for a very short time. I believe that most "D states" are actually invisible; they are very short lived and can't be observed by sampling tools such as 'top'.
You can encounter unkillable processes in the D state in a few situations. NFS is famous for that, and I've encountered it many times. I think there's a semantic clash between some VFS code paths, which assume to always reach local disks and fast error detection (on SATA, an error timeout would be around a few 100 ms), and NFS, which actually fetches data from the network which is more resilient and has slow recovery (a TCP timeout of 300 seconds is common). Read this article for the cool solution introduced in Linux 2.6.25 with the TASK_KILLABLE
state. Before this era there was a hack where you could actually send signals to NFS process clients by sending a SIGKILL to the kernel thread rpciod
, but forget about that ugly trick.…
Expected an assignment or function call and instead saw an expression.
I had this similar error with this code:
const mapStateToProps = (state) => {
players: state
}
To correct all I needed to do was add parenthesis around the curved brackets
const mapStateToProps = (state) => ({
players: state
});
If you write this yourself these are some of the points to keep in mind
Proper authentication between the device and the Sync Server
A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)
Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.
Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.
Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless
A way to replicate data changes across multiple devices
And last but not the least, a way to detect and handle conflicts
Hope this helps as a good starting point.
(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).
My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert()
changed names to create()
so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!
The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.
Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload
class. This snippet assumes your auth code works where your service endpoint is DRIVE
with a minimum auth scope of https://www.googleapis.com/auth/drive.file
.
# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'
# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))
Better yet, rather than uploading to My Drive
, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA
. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.
If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.
It does this by default, you just need to look into the project's /dist
folder.
For those interested, here's an alternative to invoking Array.join:
var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);
The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply() for more information.
One way to get unbuffered output would be to use sys.stderr
instead of sys.stdout
or to simply call sys.stdout.flush()
to explicitly force a write to occur.
You could easily redirect everything printed by doing:
import sys; sys.stdout = sys.stderr
print "Hello World!"
Or to redirect just for a particular print
statement:
print >>sys.stderr, "Hello World!"
To reset stdout you can just do:
sys.stdout = sys.__stdout__
ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
// do your standard per row stuff
}
Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod_wsgi). One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv's activate, django-admin.py, easy_install, and pip scripts. This means your virtualenv won't entirely work if you want to use a different path, perhaps to run multiple virtual hosts on the same server. I think the website may actually work with the paths wrong in those files, but you would have problems the next time you tried to run pip.
The solution, already given, is to store enough information in git so that during the deploy you can create the virtualenv and do the necessary pip installs. Typically people run pip freeze
to get the list then store it in a file named requirements.txt. It can be loaded with pip install -r requirements.txt
. RyanBrady already showed how you can string the deploy statements in a single line:
# before 15.1.0
virtualenv --no-site-packages --distribute .env &&\
source .env/bin/activate &&\
pip install -r requirements.txt
# after deprecation of some arguments in 15.1.0
virtualenv .env && source .env/bin/activate && pip install -r requirements.txt
Personally, I just put these in a shell script that I run after doing the git clone or git pull.
Storing the virtualenv directory also makes it a bit trickier to handle pip upgrades, as you'll have to manually add/remove and commit the files resulting from the upgrade. With a requirements.txt file, you just change the appropriate lines in requirements.txt and re-run pip install -r requirements.txt
. As already noted, this also reduces "commit spam".
Use the system
function.
system("myfile.sh"); // myfile.sh should be chmod +x
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.
Ctrl+Z
(suspend the process)
bg
(restart the process in the background
disown %1
(assuming this is job #1, use jobs
to determine)
The most simple way in my opinion would be to use the PyCharm IDE and install the 'multirun' plugin. I tried alot of the solutions here but this one worked for me in the end!
foreach my $arg (@ARGV) {
print $arg, "\n";
}
will print each argument.
To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
You may have a table called 'test'
COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER
Another way :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
var_dump(json_decode('{"0":0}')); // output: object(0=>0)
var_dump(json_decode('[0]')); //output: [0]
var_dump(json_decode('{"0":0}', true));//output: [0]
var_dump(json_decode('[0]', true)); //output: [0]
If you decode the json into array, information will be lost in this situation.
In build.gradle
change minSdkVersion 13
to minSdkVersion 8
Thats all you need to do. I solved my problem by only doing this.
defaultConfig {
applicationId "com.example.sabrim.sbrtest"
minSdkVersion 8
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
char *hexstring = "deadbeef10203040b00b1e50", *pos = hexstring;
unsigned char val[12];
while( *pos )
{
if( !((pos-hexstring)&1) )
sscanf(pos,"%02x",&val[(pos-hexstring)>>1]);
++pos;
}
sizeof(val)/sizeof(val[0]) is redundant!
I will put a small comparison table here (just to have it somewhere):
Servlet is mapped as /test%3F/*
and the application is deployed under /app
.
http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a
Method URL-Decoded Result
----------------------------------------------------
getContextPath() no /app
getLocalAddr() 127.0.0.1
getLocalName() 30thh.loc
getLocalPort() 8480
getMethod() GET
getPathInfo() yes /a?+b
getProtocol() HTTP/1.1
getQueryString() no p+1=c+d&p+2=e+f
getRequestedSessionId() no S%3F+ID
getRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme() http
getServerName() 30thh.loc
getServerPort() 8480
getServletPath() yes /test?
getParameterNames() yes [p 2, p 1]
getParameter("p 1") yes c d
In the example above the server is running on the localhost:8480
and the name 30thh.loc
was put into OS hosts
file.
Comments
"+" is handled as space only in the query string
Anchor "#a" is not transferred to the server. Only the browser can work with it.
If the url-pattern
in the servlet mapping does not end with *
(for example /test
or *.jsp
), getPathInfo()
returns null
.
If Spring MVC is used
Method getPathInfo()
returns null
.
Method getServletPath()
returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b
Be careful with URL encoded parts of @RequestMapping
and @RequestParam
in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.
There are a lot of good answers on the post, but I wanted the format to come out exactly as it does with JavaScript. This is what I'm using and it works well.
In [1]: import datetime
In [1]: now = datetime.datetime.utcnow()
In [1]: now.strftime('%Y-%m-%dT%H:%M:%S') + now.strftime('.%f')[:4] + 'Z'
Out[3]: '2018-10-16T13:18:34.856Z'
<div id="hassaan">
<div class="label">My Label:</div>
<div class="text">My text</div>
</div>
CSS:
#hassaan{ margin:auto; width:960px;}
#hassaan:nth-child(n){ clear:both;}
.label, .text{ width:480px; float:left;}
$this->db->or_where('end_date IS', 'NULL', false);
urlparse is fine to use if you want to (say, to get rid of any query string parameters).
import urllib.parse
urls = [
'http://www.test.com/TEST1',
'http://www.test.com/page/TEST2',
'http://www.test.com/page/page/12345',
'http://www.test.com/page/page/12345?abc=123'
]
for i in urls:
url_parts = urllib.parse.urlparse(i)
path_parts = url_parts[2].rpartition('/')
print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))
Output:
URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
URL: http://www.test.com/page/page/12345?abc=123
returns: 12345
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
The problem is that your ngView retains the scroll position when it loads a new view. You can instruct $anchorScroll
to "scroll the viewport after the view is updated" (the docs are a bit vague, but scrolling here means scrolling to the top of the new view).
The solution is to add autoscroll="true"
to your ngView element:
<div class="ng-view" autoscroll="true"></div>
Use this, it works fine.
<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>
and under options
,
responsive:true,
Please try this one..
create table client (
val_cli integer
,status varchar2(10)
);
---------------------
begin
insert into client
select 1, 'void' from dual
union all
select 4, 'void' from dual
union all
select 1, 'void' from dual
union all
select 6, 'void' from dual
union all
select 10, 'void' from dual;
end;
---------------------
select * from client;
---------------------
declare
counter integer := 0;
begin
for val in 1..10
loop
update client set status = 'updated' where val_cli = val;
if sql%rowcount = 0 then
dbms_output.put_line('no client with '||val||' val_cli.');
else
dbms_output.put_line(sql%rowcount||' client updated for '||val);
counter := counter + sql%rowcount;
end if;
end loop;
dbms_output.put_line('Number of total lines affected update operation: '||counter);
end;
---------------------
select * from client;
--------------------------------------------------------
Result will be like below:
2 client updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10
Number of total lines affected update operation: 5
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
I found a workaround a week ago. You can use direct commands with "ExecuteCommand
":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand
statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.
You can also use window.setInterval() to run some code repeatedly at a regular interval.
I had the same problem and my first <p>
element which was at the top of the page and also had a browser webkit default margin. This was pushing my entire div down which had the same effect you were talking about so watch out for any text-based elements that are at the very top of the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Website</title>
</head>
<body style="margin:0;">
<div id="image" style="background: url(pixabay-cleaning-kids-720.jpg)
no-repeat; width: 100%; background-size: 100%;height:100vh">
<p>Text in Paragraph</p>
</div>
</div>
</body>
</html>
So just remember to check all child elements not only the html and body tags.
If UAC is enabled on the computer, something like this should work:
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
WScript.Quit
End If
'actual code
One of:
In html
<!-- map.size here because -->
<%= map.size() %>
theoretically the following should work, but i never used it this way.
<%= map.size() // map.size here because %>
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
Go to cmd and type: node "C:\Path\To\File\Sample.js"
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
I make it simple, if the layout is same i just put the intent it.
My code like this:
public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCertificate, btnSeminarKit;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_menu);
initClick();
}
private void initClick() {
btnCertificate = (Button) findViewById(R.id.btn_Certificate);
btnCertificate.setOnClickListener(this);
btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
btnSeminarKit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_Certificate:
break;
case R.id.btn_SeminarKit:
break;
}
Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
startActivity(intent);
}
}
I tried everything but nothing worked.
eventually came up with following solution.
1- in manifest add for the activity android:launchMode="singleTop"
2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()
Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);
Bundle bundle = new Bundle();
bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
new Random().nextInt(), notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2);
will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.
What you seek is a simple javascript function known as .concat. Which would work like:
var finalObj = json1.concat(json2);
While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
}
});
}
})(jQuery);
And then recall it as desired like:
var finalObj = $.concat(json1, json2);
You can also use it for multiple array objects of this type with a like:
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
And if you really want it jQuery style and very short and sweet (aka minified)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);_x000D_
_x000D_
$(function() {_x000D_
var json1 = [{id:1, name: 'xxx'}],_x000D_
json2 = [{id:2, name: 'xyz'}],_x000D_
json3 = [{id:3, name: 'xyy'}],_x000D_
json4 = [{id:4, name: 'xzy'}],_x000D_
json5 = [{id:5, name: 'zxy'}];_x000D_
_x000D_
console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));_x000D_
console.log($.concat(json1, json2, json3));_x000D_
console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));_x000D_
console.log($.concat(json1, json2, json3, json4, json5));_x000D_
console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));_x000D_
console.log($.concat(json4, json1, json2, json5));_x000D_
});
_x000D_
center { padding: 3em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<center>See Console Log</center>
_x000D_
When you use ANNs, you rarely know about the internals of the systems you want to learn. Some things cannot be learned without a bias. E.g., have a look at the following data: (0, 1), (1, 1), (2, 1), basically a function that maps any x to 1.
If you have a one layered network (or a linear mapping), you cannot find a solution. However, if you have a bias it's trivial!
In an ideal setting, a bias could also map all points to the mean of the target points and let the hidden neurons model the differences from that point.
To implement you need use Typeface go through with sample below
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
if (view instanceof TextView)
{
TextView textView = (TextView) view;
textView.setTypeface(typeface);
}
}
}
I use both windows and linux, but the solution core.autocrlf true
didn't help me. I even got nothing changed after git checkout <filename>
.
So I use workaround to substitute git status
- gitstatus.sh
#!/bin/bash
git status | grep modified | cut -d' ' -f 4 | while read x; do
x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
x2="$(cat $x | md5sum | cut -d' ' -f 1 )"
if [ "$x1" != "$x2" ]; then
echo "$x NOT IDENTICAL"
fi
done
I just compare md5sum
of a file and its brother at repository.
Example output:
$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL
In my case I had a new repository, pushed a branch ('UCA-46', not 'master'), rebased it, forcely pushed again and got the error. No web-hooks existed. I executed git pull --rebase
as @ThiefMaster advised, had to rebase again and was able to push the branch. But that was a strange and difficult way.
Then I saw Git push error pre-receive hook declined. I found that my branch became protected. I removed protection and could forcely push again.
If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.
Delete completely:
right mouse click ? Menu ? Delete
Delete & Keep local:
Shift + right mouse click ? Menu ? Delete
Ctrl+H is very handy here. I mostly search in the current project, not the whole workspace. To find all occurences in the whole project of a string that is in your current buffer, just select the string press Ctrl+H and hit enter. Easy as that!
Use Resource Filters! Eclipse will restrict the search result using the Resource Filters defined for your project (eg. right click on you project name and select Properties -> Resource -> Resource Filters). So if you keep getting search hits from parts of your project that your not interested in you could make Eclipse skip those by adding a Resource Filter for them. This is especially useful if you have build files or logs or other temporary files that are part of your projects directory structure, but you only want to search amongst the source code. You should also be aware of that files/directories matched for exclusion in the Resource Filters will not show up in the Package Explorer either, so you might not always want this.
version: '2'
services:
bot:
build: .
volumes:
- '.:/home/node'
- /home/node/node_modules
networks:
- my-rede
mem_limit: 100m
memswap_limit: 100m
cpu_quota: 25000
container_name: 236948199393329152_585042339404185600_bot
command: node index.js
environment:
NODE_ENV: production
networks:
my-rede:
external:
name: name_rede_externa
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
I have solved same issue with following:
export M2_HOME=/usr/share/maven
It supports lists, but not as a separate data structure (ignoring arrays for the moment).
The for
loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:
for i in 1 2 3; do
echo "$i"
done
or via parameter expansion:
listVar="1 2 3"
for i in $listVar; do
echo "$i"
done
or command substitution:
for i in $(echo 1; echo 2; echo 3); do
echo "$i"
done
An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:
array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do # The quotes are necessary here
echo "$i"
done
list='"item 1" "item 2" "item 3"'
for i in $list; do
echo $i
done
for i in "$list"; do
echo $i
done
for i in ${array[@]}; do
echo $i
done
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
You can also use the ignore syntax instead of using (or better the 'as any') notation:
// @ts-ignore
$("div.printArea").printArea();
Use pkill -f
, which matches the pattern for any part of the command line
pkill -f my_pattern
Reload the current document:
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>
For me it was due to insufficient disk space , and it was resolved after I freed up some disk space on my local drive.
To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
I was having the same issue and tried all of the solutions on this page but none of them did the trick.
What finally worked was adding the universe
repo to my repo list. To do that run the following command
sudo add-apt-repository universe
After running the above command I was able to run
sudo apt install openjdk-8-jre
without an issue and the package was installed.
Hope this helps someone.
For those using OpenSSL you can retrieve the SHA1 fingerprint this way:
OpenSSL> dgst -sha1 my-release-key.keystore
Which would result in the following output:
I do it the following way:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
if you have more than one classes in your classifier, you might want to use pandas-ml at that part. Confusion Matrix of pandas-ml give more detailed information. check that
You can accomplish this by setting this on the container:
ul {
display: flex;
flex-wrap: wrap;
}
And on the child you set this:
li:nth-child(2n) {
flex-basis: 100%;
}
ul {
display: flex;
flex-wrap: wrap;
list-style: none;
}
li:nth-child(4n) {
flex-basis: 100%;
}
_x000D_
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
_x000D_
This causes the child to make up 100% of the container width before any other calculation. Since the container is set to break in case there is not enough space it does so before and after this child. So you could use an empty div element to force the wrap between the element before and after it.
class CurrentValue:
def __init__(self, value):
self.value = value
def set_val(self, k):
self.value = k
def get_val(self):
return self.value
class AddValue:
def av(self, ocv):
print('Before:', ocv.get_val())
num = int(input('Enter number to add : '))
nnum = num + ocv.get_val()
ocv.set_val(nnum)
print('After add :', ocv.get_val())
cvo = CurrentValue(5)
avo = AddValue()
avo.av(cvo)
We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.
I am sorry for any inconvenience. This will not happen again.
Before: 5
Enter number to add : 14
After add : 19
<div class="row">
<div class="col-sm-6">
<div class="card">
Content one
</div>
</div>
<div class="col-sm-6">
<div class="card">
Content two
</div>
</div>
</div>
Have you thinked about using instanceof
?
Like, say
if(myObject instanceof Collection) {
Collection myCollection = (Collection) myObject;
Although not that pure OOP style, it is however largely used for so-called "type escalation".
You just need to put your war file in webapps and then start your server.
it will get deployed.
otherwise you can also use tomcat manager a webfront to upload & deploy your war remotely.
.length = number of rows / column length
[0].length = number of columns / row length
I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.
In Powershell 5.1, you want to use continue
to move onto the next item in your loop. I tested with 6 items in an array, had a foreach
loop through, but put an if statement with:
foreach($i in $array){
write-host -fore green "hello $i"
if($i -like "something"){
write-host -fore red "$i is bad"
continue
write-host -fore red "should not see this"
}
}
Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i
matched, I saw something is bad
and then it went on to the next item in the array without saying should not see this
. I tested with return
and it exited the loop altogether.
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
If you don't want to pass any arguments to the onclick function, just use event.target
to get the clicked element:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
// event.target is the element that is clicked (button in this case).
console.log(event.target.id);
}
Note: I had this problem while Generating Database Sql from Model. It had created all the tables fine but wouldn't export the changes. What you need to notice is that this error is generated when you try to export the sql using the DDL Generation Template as SSDLtoSQL10. It is expecting MySQL connection here so make sure you select from the drop down DDL Generation Template SSDLtoMySQL on the Model properties. Spent a whole day on this !
Also, StringBuffer
is thread-safe, which StringBuilder
is not.
So in a real-time situation when different threads are accessing it, StringBuilder
could have an undeterministic result.
New Direction on VS 2017 (x64 systems)
"C:\Program Files (x86)\Microsoft Visual Studio\2017\*your lic type*\Common7\IDE\WcfTestClient.exe"
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
Using Swift 3 or 4 you can access these http request for sever communication.
// For POST data to request
func postAction() {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume() }
// For get the data from request
func GetRequest() {
let urlString = URL(string: "http://www.requestURL.php") //change the url
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error ?? "")
} else {
if let responceData = data {
print(responceData) //JSONSerialization
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
}
}
}
task.resume()
}
}
// For get the download content like image or video from request
func downloadTask() {
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
}
}
task.resume()
}
var x = 1234567;
x.toString().length;
This process will also work forFloat Number
and for Exponential number
also.
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.
Tell me which backend technology are you using? I can give more suggestions based on that.
git rev-parse --short HEAD
To close ajax fancybox window, use this:
onclick event -> $.fancybox.close();
return false;
Using Console.WriteLine( "Test" );
is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" );
was working. I restarted Visual Studio and Console.WriteLine()
started working again. Seems to be a Visual Studio bug.