git rev-list --reverse b..f | xargs -n 1 git cherry-pick
For me only this one worked
git checkout -p filename
For eclipse i think EGIT is the best option. This guide http://rogerdudler.github.io/git-guide/index.html will help you understand git quick.
git revert
doesn't take a filename parameter. Do you want git checkout
?
Use git log
to find the revision you want to rollback to, and take note of the commit hash. After that, you have 2 options:
If you plan to commit anything after that revision, I recommend you to checkout to a new branch: git checkout -b <new_branch_name> <hash>
If you don't plan to commit anything after that revision, you can simply checkout without a branch: git checkout <hash>
- NOTE: This will put your repository in a 'detached HEAD' state, which means its currently not attached to any branch - then you'll have some extra work to merge new commits to an actual branch.
Example:
$ git log
commit 89915b4cc0810a9c9e67b3706a2850c58120cf75
Author: Jardel Weyrich <suppressed>
Date: Wed Aug 18 20:15:01 2010 -0300
Added a custom extension.
commit 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Author: Jardel Weyrich <suppressed>
Date: Wed Aug 18 20:13:48 2010 -0300
Missing constness.
$ git checkout 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Note: moving to '4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7'
which isn't a local branch
If you want to create a new branch from this checkout, 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 4553c14... Missing constness.
That way you don't lose any informations, thus you can move to a newer revision when it becomes stable.
If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.
For example:
$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master
Similarly you can clone as if this were a remote repo:
$ git clone ~/repos/myproject.git
$ git clone --bare https://github.com/example
This command will make the new "example
" directory itself the $GIT_DIR (instead of example/.git
). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
$ git clone --mirror https://github.com/example
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.
on mac terminal (at least in ZSH): open stackoverflow.com
(opens site in new tab in your chrome default browser)
if you've accidentally staged files that you would not like to commit, and want to be certain you keep the changes, you can also use:
git stash
git stash pop
this performs a reset to HEAD and re-applies your changes, allowing you to re-stage individual files for commit. this is also helpful if you've forgotten to create a feature branch for pull requests (git stash ; git checkout -b <feature> ; git stash pop
).
If by any chance git pull
prints Already up-to-date
then you might want to check the global git push.default
param (In ~/.gitconfig
). Set it to simple
if it was in matching
. The below answer explains why:
Git - What is the difference between push.default "matching" and "simple"
Also, it is worth checking if your local branch is out of date using git remote show origin
and do a pull if needed
The core thing you're going to want here is git add -p
(-p
is a synonym for --patch
). This provides an interactive way to check in content, letting you decide whether each hunk should go in, and even letting you manually edit the patch if necessary.
To use it in combination with cherry-pick:
git cherry-pick -n <commit> # get your patch, but don't commit (-n = --no-commit)
git reset # unstage the changes from the cherry-picked commit
git add -p # make all your choices (add the changes you do want)
git commit # make the commit!
(Thanks to Tim Henigan for reminding me that git-cherry-pick has a --no-commit option, and thanks to Felix Rabe for pointing out that you need to reset! If you only want to leave a few things out of the commit, you could use git reset <path>...
to unstage just those files.)
You can of course provide specific paths to add -p
if necessary. If you're starting with a patch you could replace the cherry-pick
with apply
.
If you really want a git cherry-pick -p <commit>
(that option does not exist), your can use
git checkout -p <commit>
That will diff the current commit against the commit you specify, and allow you to apply hunks from that diff individually. This option may be more useful if the commit you're pulling in has merge conflicts in part of the commit you're not interested in. (Note, however, that checkout
differs from cherry-pick
: checkout
tries to apply <commit>
's contents entirely, cherry-pick
applies the diff of the specified commit from it's parent. This means that checkout
can apply more than just that commit, which might be more than you want.)
First, check your git version by using this command
git version
Then follow the case according to your git version
Three cases:
If your git version is 2.14.1 or earlier:
Uninstall the git, download the latest git, and install it again.
And versions between 2.14.2 and 2.16.1:
Use command git update
If the version is equal to or greater than Git 2.16.1(2):
Use command git update-git-for-windows
You can do it for arbitrary refs. This is how to move a branch pointer:
git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>
where -m
adds a message to the reflog for the branch.
The general form is
git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>
You can pick nits about the reflog message if you like - I believe the branch -f
one is different from the reset --hard
one, and this isn't exactly either of them.
I don't know if this is right or wrong, but I pushed the "old name" of the branch to the "new name" of the branch, then deleted the old branch entirely with the following two lines:
git push origin old_branch:new_branch
git push origin :old_branch
You can simply do git pull origin branchname
. It will fetch the latest commit again.
Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out.
The value of core.autocrlf is set before commit and also before checkout.
The result is below.
commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF CRLF=>CRLF
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
UPDATE
Now it's available:
https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory
Until now it isn't supported, but you can follow the thread for it: GitHub
This should unstage a <file> for you (without removing or otherwise modifying the file):
git reset <file>
git push
can push all branches or a single one dependent on this configuration:
Push all branches
git config --global push.default matching
It will push all the branches to the remote branch and would merge them.
If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default
.
Push only the current branch if its named upstream is identical
git config --global push.default simple
So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.
A sample .gitignore file can look like one below for a Android Studio project
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
#Eclipse
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
YourProjetcName/.gradle/
YourProjetcName/app/build/
*/YourProjetcName/.gradle/
*/YourProjetcName/app/build/
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
# Proguard folder generated by Eclipse
proguard/
# Intellij project files
*.iml
*.ipr
*.iws
.idea/
/build
build/
*/build/
*/*/build/
*/*/*/build/
*.bin
*.lock
YourProjetcName/app/build/
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
.gradle/
app/build/
*app/build/
# Local configuration file (sdk path, etc)
local.properties
/YourProjetcName/build/intermediates/lint-cache/api-versions-6-23.1.bin
appcompat_v7_23_1_1.xml
projectFilesBackup
build.gradle
YourProjetcName.iml
YourProjetcName.iml
gradlew
gradlew.bat
local.properties
settings.gradle
.gradle
.idea
android
build
gradle
Addition to @hasen's answer. You might want to use git ls-files
instead of find
to list files to checkout like:
git ls-files -z *.txt | git checkout-index --prefix=/path-to/dest/ -f -z --stdin
git ls-files
ignores uncommitted files.
Related answer with this question.
Error - fatal: I don't handle protocol 'git clone https'
I was trying to clone git project to my newly installed VScode in my Linux system, i was copied the entire url from bit bucket, which was like
But actually it running command like
git clone git clone https://[email protected]/abcuser/myproject.git
in the bit bucket.
So Simply do the following steps :
1. Enter Ctr+p; this will open command box. Enter and open 'Clone'
2. Now only paste the url of your git reposiratory here. eg: https://[email protected]/abcuser/myproject.git
3. After that box for enter your git password will appear on screen. Enter your git password here.
4. Done.
git checkout master -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.
git show <your-branch>:path/to/<your-file>
Hope this will help you. Please let me know If you have any query.
Worked in LinuxMint/Ubuntu
Do the following steps
Step 1:
Goto file => /.ssh/config
Save the below lines into the file
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile /home/apple/myssh-privatekey
AddKeysToAgent yes
Don't forget to add this line AddKeysToAgent yes
Step 2:
Open the terminal and add the keyset to the ssh-add
$ ssh-add -k /home/apple/myssh-privatekey
provide the passphrase.
I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share
Syntax:
git diff <commit-ish>:./ -- <path>
Examples:
git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md
(Thanks Eric Boehs for a way to not have to type the filename twice)
Follow these steps:
Create a new branch:
git branch newfeature
Checkout new branch: (this will not reset your work.)
git checkout newfeature
Now commit your work on this new branch:
git commit -s
Using above steps will keep your original branch clean and you dont have to do any 'git reset --hard'.
This command will get you the last commit message:
git log -1 --oneline --format=%s | sed 's/^.*: //'
outputs something similar to:
Create FUNDING.yml
You can change the -1 to any negative number to increase the range of commit messages retrieved
I had this issue when after rebooted and the last copy of VSCode reopened. The above fix did not work, but when I closed and reopened VSCode via explorer it worked. Here are the steps I did:
//received fatal error_x000D_
git remote remove origin_x000D_
git init_x000D_
git remote add origin git@github:<yoursite>/<your project>.git_x000D_
// still received an err _x000D_
//restarted VSCode and folder via IE _x000D_
//updated one char and resaved the index.html _x000D_
git add ._x000D_
git commit -m "blah"_x000D_
git push origin master
_x000D_
I keep coming across this problem, so have written a script to download the self signed certificate from the server and install it to ~/.gitcerts, then update git-config to point to these certificates. It is stored in global config, so you only need to run it once per remote.
https://github.com/iwonbigbro/tools/blob/master/bin/git-remote-install-cert.sh
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
You can permanently set up your bash output to show your git-branch name. It is very handy when you work with different branches, no need to type $ git status
all the time.
Github repo git-aware-prompt
.
Open your terminal (ctrl-alt-t) and enter the commands
mkdir ~/.bash
cd ~/.bash
git clone git://github.com/jimeh/git-aware-prompt.git
Edit your .bashrc with sudo nano ~/.bashrc
command (for Ubuntu) and add the following to the top:
export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"
Then paste the code
export PS1="\${debian_chroot:+(\$debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[$txtcyn\]\$git_branch\[$txtred\]\$git_dirty\[$txtrst\]\$ "
at the end of the same file you pasted the installation code into earlier. This will give you the colorized output:
The .git/config
file in a particular clone of a repository is local to that clone. Any settings placed there will only affect actions for that particular project.
(By default, git config
modifies .git/config
, not ~/.gitconfig
- only with --global
does it modify the latter.)
I agree with the current answers, I just wanna add little more information, Here's a good functionality
if you want to require just zip file but the owner has not prepared a zip file,
To simply download a repository as a zip file: add the extra path /zipball/master/ to the end of the repository URL, This will give you a full ZIP file
For example, here is your repository
https://github.com/spring-projects/spring-data-graph-examples
Add zipball/master/ in your repository link
https://github.com/spring-projects/spring-data-graph-examples/zipball/master/
Paste the URL into your browser and it will give you a zip file to download
For the simple case of just copying the last commit from branch wss to v2.1, you can simply grab the commit id (git log --oneline | head -n 1
) and do:
git checkout v2.1
git merge <commit>
We got this error because we had a comma (,) in the branch name. We deleted the local branch, then re-checked it under a new name without the comma. We were able to merge it successfully.
None of these answers helped me because I still had untracked files even after reset and stash. I had to do:
git reset --hard HEAD
git clean -d -f
Follow these steps:
steps updated as on 13th July 2020 Thank You: Rahul Daksh
You need to adjust shell path , the path will be set in either .bashrc
or .bash_profile
in your home directory, more likely .bash_profile
.
So add into the path similar to the below and keep what you already have in the path, each segment is separated by a colon:
export PATH="/usr/local/bin:/usr/bin/git:/usr/bin:/usr/local/sbin:$PATH"
So easy:
git diff --name-only
Go forth and diff!
Apparently GitHub now offer git training courses to companies. Quoth their blog post about it:
I’ve been down to the Google campus a number of times in the last few weeks helping to train the Androids there in Git. I was asked by Shawn Pearce (you may know him from his Git and EGit/JGit glory – he is the hero that takes over maintanance when Junio is out of town) to come in to help him train the Google engineers working on Andriod in transitioning from Perforce to Git, so Android could be shared with the masses. I can tell you I was more than happy to do it.
[…]
Logical Awesome is now officially offering this type of custom training service to all companies, where we can help your organization with training and planning if you are thinking about switching to Git as well.
Emphasis mine.
List all variables set in the config file, along with their values.
git config --list
If you are new to git then use the following commands to set a user name and email address.
Set user name
git config --global user.name "your Name"
Set user email
git config --global user.email "[email protected]"
Check user name
git config user.name
Check user email
git config user.email
To remove untracked files / directories do:
git clean -fdx
-f - force
-d - directories too
-x - remove ignored files too ( don't use this if you don't want to remove ignored files)
Use with Caution!
These commands can permanently delete arbitrary files, that you havn't thought of at first. Please double check and read all the comments below this answer and the --help section, etc., so to know all details to fine-tune your commands and surely get the expected result.
Tags are not sent to the remote repository by the git push command. We need to explicitly send these tags to the remote server by using the following command:
git push origin <tagname>
We can push all the tags at once by using the below command:
git push origin --tags
Here are some resources for complete details on git tagging:
The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:
Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.
So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.
First I find out the number of commits between my feature branch and current master branch by
git checkout master
git rev-list master.. --count
Then, I create another branch based out my-feature branch, keep my-feature
branch untouched.
Lastly, I run
git checkout my-feature
git checkout -b my-rebased-feature
git checkout master
git checkout my-rebased-feature
git rebase master
git rebase head^x -i
// fixup/pick/rewrite
git push origin my-rebased-feature -f // force, if my-rebased-feature was ever pushed, otherwise no need for -f flag
// make a PR with clean history, delete both my-feature and my-rebased-feature after merge
Hope it helps, thanks.
status tell you what to do.
Unmerged paths:
(use "git reset HEAD <file>..." to unstage)
(use "git add <file>..." to mark resolution)
you probably applied a stash or something else that cause a conflict.
either add, reset, or rm.
CoolAJ86's answer sums up pretty much everything. In case you have changes in both branches in the same piece of code you will have to do a manual merge. Open the file in conflict in any text editor and you should see following structure.
(Code not in Conflict)
>>>>>>>>>>>
(first alternative for conflict starts here)
Multiple code lines here
===========
(second alternative for conflict starts here)
Multiple code lines here too
<<<<<<<<<<<
(Code not in conflict here)
Choose one of the alternatives or a combination of both in a way that you want new code to be, while removing equal signs and angle brackets.
git commit -a -m "commit message"
git push origin master
Simply push this branch to a different branch name
git push -u origin localBranch:remoteBranch
It's not "plumbing", but it'll do exactly what you want:
$ git log --format=%B -n 1 <commit>
If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list
:
$ git rev-list --format=%B --max-count=1 <commit>
Although rev-list
will also print out the commit sha (on the first line) in addition to the commit message.
Please try this steps in git bash, It may help you.
CTRL + C
:qa!
I tried experimenting with the answers given. My personal finding came out to be:
git rm -r --cached .
And then
git add .
This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.
It's simple and follow the small Steps to proceed:
$cd project and execute $git init --bare
Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git
, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, $cd
into the project folder which you want to push to git execute the below commands:
git init .
git remote add origin [email protected]:/home/ubuntu/workspace/project.git
git add .
git commit -m "Initial commit"
Below is an optional command but found it has been suggested as i was working to setup the same thing
git config --global remote.origin.receivepack "git receive-pack"
git pull origin master
git push origin master
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, cd project_folder/.git
and cat config
, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the project.git
folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
If you want to undo all files that was applied assume unchanged with any status, not only cached (git marks them by character in lower case), you can use the following command:
git ls-files -v | grep '^[a-z]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged
git ls-files -v
will print all files with their statusgrep '^[a-z]'
will filter files and select only assume unchangedcut -c 3-
will remove status and leave only paths, cutting from the 3-rd character to the endtr '\012' '\000'
will replace end of line character (\012) to zero character (\000)xargs -0 git update-index --no-assume-unchanged
will pass all paths separated by zero character to git update-index --no-assume-unchanged
to undoI had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.
Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.
There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/
But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin
You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.
Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools
Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.
Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.
The following command is needed to force git to send the credentials and authentication method to the proxy:
git config --global http.proxyAuthMethod 'basic'
Source: https://git-scm.com/docs/git-config#git-config-httpproxyAuthMethod
If the problem is with the index as the staging area for commits (i.e. .git/index
), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:
On OSX/Linux:
rm -f .git/index
git reset
On Windows:
del .git\index
git reset
(The reset
command above is the same as git reset --mixed HEAD
)
You can alternatively use lower level plumbing git read-tree
instead of git reset
.
If the problem is with index for packfile, you can recover it using git index-pack
.
c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll
If you use git LFS, git count-objects does not count your binaries, but only the pointers to them.
If your LFS files are managed by Artifactorys, you should use the REST API:
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
git pull --recurse-submodules --jobs=10
a feature git first learned in 1.8.5.
Until the bug is fixed, for the first time you do need to run
git submodule update --init --recursive
The thought process here is that you spend most of your time in development
. When in development, you create a feature
branch (off of development
), complete the feature, and then merge back into development
. This can then be added to the final production version by merging into production
.
See A Successful Git Branching Model for more detail on this approach.
It is cumbersome to type the complete code every time a repository is to be created
curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
git remote add origin [email protected]:USER/REPO.git
git push origin master
An easier approach is:
githubscript.sh
githubscript.sh
file
#!bin/bash
curl -u 'YOUR_GITHUB_USER_NAME' https://api.github.com/user/repos -d "{\"name\":\"$1\"}";
git init;
git remote add origin [email protected]:YOUR_GITHUB_USER_NAME/$1.git;
N.B. Here $1
is the repository name
that is passed as an argument
when invoking the script
Change YOUR_GITHUB_USER_NAME
before saving the script.
Set required permissions to the script
file
chmod 755 githubscript.sh
Include the scripts directory in the environment configuration file.
nano ~/.profile;
export PATH="$PATH:$HOME/Desktop/my_scripts"
Also set an alias to run the githubscript.sh file.
nano ~/.bashrc;
alias githubrepo="bash githubscript.sh"
Now reload the .bashrc
and .profile
files in the terminal.
source ~/.bashrc ~/.profile;
Now to create a new repository i.e. demo
:
githubrepo demo;
This is an answer targeting primarily developers using Windows, as the path syntax of the diff tool differs from other platforms.
I use Kdiff3 as the git mergetool, but to set up the git difftool as Meld, I first installed the latest version of Meld from Meldmerge.org then added the following to my global .gitconfig using:
git config --global -e
Note, if you rather want Sublime Text 3 instead of the default Vim as core ditor, you can add this to the .gitconfig file:
[core]
editor = 'c:/Program Files/Sublime Text 3/sublime_text.exe'
Then you add inn Meld as the difftool
[diff]
tool = meld
guitool = meld
[difftool "meld"]
cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" \"$LOCAL\" \"$REMOTE\" --label \"DIFF
(ORIGINAL MY)\"
prompt = false
path = C:\\Program Files (x86)\\Meld\\Meld.exe
Note the leading slash in the cmd above, on Windows it is necessary.
It is also possible to set up an alias to show the current git diff with a --dir-diff option. This will list the changed files inside Meld, which is handy when you have altered multiple files (a very common scenario indeed).
The alias looks like this inside the .gitconfig file, beneath [alias] section:
showchanges = difftool --dir-diff
To show the changes I have made to the code I then just enter the following command:
git showchanges
The following image shows how this --dir-diff option can show a listing of changed files (example):
Then it is possible to click on each file and show the changes inside Meld.
Fairly straightforward:
git remote rm origin
As for the filter-branch
question - just add --prune-empty
to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:
git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD
Disclaimer: this is an update to Cascabel's answer, which I'm writing to save the curious some time.
I tried in vain to replicate (in Git 2.0.1) the remote HEAD is ambiguous
message that Cascabel mentions in his answer; so I did a bit of digging (by cloning https://github.com/git/git and searching the log). It used to be that
Determining HEAD is ambiguous since it is done by comparing SHA1s. In the case of multiple matches we return refs/heads/master if it matches, else we return the first match we encounter. builtin-remote needs all matches returned to it, so add a flag for it to request such.
(Commit 4229f1fa325870d6b24fe2a4c7d2ed5f14c6f771
, dated Feb 27, 2009, found with git log --reverse --grep="HEAD is ambiguous"
)
However, the ambiguity in question has since been lifted:
One long-standing flaw in the pack transfer protocol used by "git clone" was that there was no way to tell the other end which branch "HEAD" points at, and the receiving end needed to guess. A new capability has been defined in the pack protocol to convey this information so that cloning from a repository with more than one branches pointing at the same commit where the HEAD is at now reliably sets the initial branch in the resulting repository.
(Commit 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
, dated Nov 8, 2013, found with git log --grep="ambiguous" --grep="HEAD" --all-match
)
Edit (thanks to torek):
$ git name-rev --name-only 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
tags/v1.8.4.3~3
This means that, if you're using Git v1.8.4.3 or later, you shouldn't run into any ambiguous-remote-HEAD problem.
This gives almost what you need:
git log --stat --oneline
Commit id + short one line still remains, followed by list of changed files by that commit.
git commit --amend
and press Enter.git push --force example-branch
command to force push over the old commit.Source: https://help.github.com/articles/changing-a-commit-message/
Try this command:
git ls-files
This lists all of the files in the repository, including those that are only staged but not yet committed.
http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html
That's how I do it:
Since your have free choise about DB type use a filebased DB like e.g. firebird.
Create a template DB which has the schema that fits your actual branch and store it in your repository.
When executing your application programmatically create a copy of your template DB, store it somewhere else and just work with that copy.
This way you can put your DB schema under version control without the data. And if you change your schema you just have to change the template DB
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
git ignore is a convention in git. Setting a file by the name of .gitignore
will ignore the files in that directory and deeper directories that match the
patterns that the file contains. The most common use is just to have one file
like this at the top level. But you can add others deeper in your directory
structure to ignore even more patterns or stop ignoring them for that directory
and subsequently deeper ones.
Likewise, you can "unignore" certain files in a deeper structure or a specific
subset (ie, you ignore *.log but want to still track important.log) by
specifying patterns beginning with !
. eg:
*.log !important.log
will ignore all log files but will track files named important.log
If you are tracking files you meant to ignore, delete them, add the pattern to you .gitignore file and add all the changes
# delete files that should be ignored, or untrack them with
# git rm --cached <file list or pattern>
# stage all the changes git commit
git add -A
from now on your repository will not have them tracked.
If you would like to clean up your history, you can
# if you want to correct the last 10 commits
git rebase -i --preserve-merges HEAD~10
then mark each commit with e
or edit
. Save the plan. Now git will replay
your history stopping at each commit you marked with e. Here you delete the
files you don't want, git add -A
and then git rebase --continue
until you
are done. Your history will be clean. Make sure you tell you coworkers as you
will have to force push and they will have to rebase what they didn't push yet.
Alternatively:
Save current changes to a temp stash:
$ git stash
Create a new branch based on this stash, and switch to the new branch:
$ git stash branch <new-branch> stash@{0}
Tip: use tab key to reduce typing the stash name.
If I understand right, you've made a commit to changed_branch
and you want to copy that commit to other_branch
? Easy:
git checkout other_branch
git cherry-pick changed_branch
Add --force to your command line if you are sure you want to push. E.g. use git push origin --force
(I recommend the command line as you will find much more support from other users with the command line. Also this may not be possible with SmartGit.) See this site for more information: http://help.github.com/remotes/
I'm doing a git repository statistics generator in ruby, it's called git_stats.
You can find examples generated for some repositories on project page.
Here is a list of what it can do:
If you have any idea what to add or improve please let me know, I would appreciate any feedback.
vim-fugitive is versatile for that kind of examining in Vim.
Use :Ggrep
to do that. For more information you can install vim-fugitive and look up the turorial by :help Grep
. And this episode: exploring-the-history-of-a-git-repository will guide you to do all that.
The following simple steps help me:
First, initialize the repository to work with Git
, so that any file changes are tracked:
git init
Then, check that the remote repository that you want to associate with the alias origin
exists, if not create it in git
first.
$ git ls-remote https://github.com/repo-owner/repo-name.git/
If it exists, associate it with the remote "origin":
git remote add origin https://github.com:/repo-owner/repo-name.git
and check to which URL, the remote "origin" belongs to by using git remote -v
:
$ git remote -v
origin https://github.com:/repo-owner/repo-name.git (fetch)
origin https://github.com:/repo-owner/repo-name.git (push)
Next, verify if your origin is properly aliased as follows:
$ cat ./.git/config
:
[remote "origin"]
url = https://github.com:/repo-owner/repo-name.git
fetch = +refs/heads/*:refs/remotes/origin/*
:
You need to see this section [remote "origin"]
. You can consider to use GitHub Desktop available for both Windows and MacOS, which help me to automatically populate the missing section/s in ~./git/config
file OR you can manually add it, not great, but hey it works!
[Optional]
You might also want to change the origin
alias to make it more intuitive, especially if you are working with multiple origin
:
git remote rename origin mynewalias
or even remove it:
git remote rm origin
Finally, on your first push, if you want master
in that repository to be your default upstream. you may want to add the -u
parameter
git add .
git commit -m 'First commit'
git push -u origin master
In my case the error was some old username and password was stored in cache.
So I removed it by going to sourceTree and delete the existing account.
Now for the new clone then it will ask you for the password for the repo.
I received this error after moving git across hard drives. Deleting and reinstalling in the new location fixed things
if you know the remote branch you want to check, you can find out the latest via:
git ls-tree -r <remote_branch> --name-only
Option 1: Discard tracked and untracked file changes
Discard changes made to both staged and unstaged files.
$ git reset --hard [HEAD]
Then discard (or remove) untracked files altogether.
$ git clean [-f]
Option 2: Stash
You can first stash your changes
$ git stash
And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.
Option 3: Manually restore files to original state
First we switch to the target branch
$ git checkout <branch-name>
List all files that have changes
$ git status
Restore each file to its original state manually
$ git restore <file-path>
This is a useful article which graphically shows the explanation of the reset command.
https://git-scm.com/docs/git-reset
Reset --hard can be quite dangerous as it overwrites your working copy without checking, so if you haven't commited the file at all, it is gone.
As for Source tree, there is no way I know of to undo commits. It would most likely use reset under the covers anyway
Suppose you made changes to multiple files, like:
But you want to commit only changes of File1 and File3.
There are two ways for doing this:
1.Stage only these two files, using:
git add file1 file2
then, commit
git commit -m "your message"
then push,
git push
2.Direct commit
git commit file1 file3 -m "my message"
then push,
git push
Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects
You used the egg files install procedure.
This procedure supports installing over git
, git+http
, git+https
, git+ssh
, git+git
and git+file
. Some of these are mentioned.
It's good you can use branches, tags, or hashes to install.
@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:
pip install https://github.com/user/repository/archive/branch.zip
Alternatively, I suggest you may install using the .whl
file if this exists.
pip install https://github.com/user/repository/archive/branch.whl
It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.
i also encounter that error once in a while, but when it does, it means that my branch is not up-to-date so i have to do git pull origin <current_branch>
@bsimmons
git fsck --lost-found | grep commit
Then create a branch for each one:
$ git fsck --lost-found | grep commit
Checking object directories: 100% (256/256), done.
dangling commit 2806a32af04d1bbd7803fb899071fcf247a2b9b0
dangling commit 6d0e49efd0c1a4b5bea1235c6286f0b64c4c8de1
dangling commit 91ca9b2482a96b20dc31d2af4818d69606a229d4
$ git branch branch_2806a3 2806a3
$ git branch branch_6d0e49 6d0e49
$ git branch branch_91ca9b 91ca9b
Now many tools will show you a graphical visualization of those lost commits.
git log --format="%h" | tail -1
gives you the commit hash (ie 0dd89fb
), which you can feed into other commands, by doing something like
git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD
to view all the commits in the last day.
There are three options shown in this tutorial. In case the link breaks I'll leave the main steps here.
1 Revert the full commit
git revert dd61ab23
2 Delete the last commit
git push <<remote>> +dd61ab23^:<<BRANCH_NAME_HERE>>
or, if the branch is available locally
git reset HEAD^ --hard
git push <<remote>> -f
where +dd61... is your commit hash and git interprets x^ as the parent of x, and + as a forced non-fastforwared push.
3 Delete the commit from a list
git rebase -i dd61ab23^
This will open and editor showing a list of all commits. Delete the one you want to get rid off. Finish the rebase and push force to repo.
git rebase --continue
git push <remote_repo> <remote_branch> -f
i had created new repo in github and i had the same problem, but it also had problem while pulling, so this worked for me.
but this is not advised in repos that already have many codes as this could mess up everything
git push origin master --force
Instructions here are a little complicated so I'm going to offer something more straightforward:
git reset HEAD --hard
Abandon all changes to the current branch
...
Perform intermediary work as necessary
git stash pop
Re-pop the stash again at a later date when you're ready
You can achieve this in 2 easy steps
List lost stashes --> run this command for a project where all stashes were trashed:
git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk
Send a lost stash back where it comes from --> Let’s use the commit hash of the second stash:
git update-ref refs/stash 4b3fc45c94caadcc87d783064624585c194f4be8 -m "My recovered stash"
To undo the last local commit, without throwing away its changes, I have this handy alias in ~/.gitconfig
[alias]
undo = reset --soft HEAD^
Then I simply use git undo
which is super-easy to remember.
I ran into this issue when I had cloned a repo on my NAS and then cloned that repo on to my machines.
The set up is something like this:
ORIGINAL (github):
DEVELOPMENT
DEVELOPMENT
When I tried to commit to the from the laptop to the NAS server the error which comes up is
! [remote rejected] development -> development (branch is currently checked out)
The root cause is that DEVELOPMENT
branch is checked out on the NAS server. My solution was on the NAS repository to switch to any other branch. This let me commit my changes.
You can use only git log --oneline
With the atom editor, you just need to install the git-plus package.
You can create a shell script which will remove all your files when run:
git status | grep deleted | awk '{print "git rm " $3;}' > ../remove.sh
The script that is created is remove.sh
and it contains the full list of git rm
commands.
In case you have a repository with few local checkedout branches /refs/heads/* and few remote branch branches remotes/origin/* AND if you want to convert this into a BARE repository with all branches in /refs/heads/*
you can do the following to save the history.
Just add a >NUL
at the end of the lines producing the messages.
For example,
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL
There's no Java collection in the standard library to do this. LinkedHashSet<E>
preserves ordering similarly to a List
, though, so if you wrap your set in a List
when you want to use it as a List
you'll get the semantics you want.
Alternatively, the Commons Collections (or commons-collections4
, for the generic version) has a List
which does what you want already: SetUniqueList
/ SetUniqueList<E>
.
select
{
-webkit-appearance: none;
}
If you need to you can also add an image that contains the arrow as part of the background.
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
If you want to use free version of font awesome - bootstrap, use this :
npm install --save @fortawesome/fontawesome-free
If you are building angular project, you also need to add these imports in your angular.json :
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/@fortawesome/fontawesome-free/css/fontawesome.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/@fortawesome/fontawesome-free/js/all.js"
]
Here are two solutions using Pandas to convert dates formatted as strings into datetime.date objects.
import pandas as pd
dates = ['2015-12-25', '2015-12-26']
# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
Timings
dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()
>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop
>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop
And here is how to convert the OP's original date-time examples:
datetimes = ['Jun 1 2005 1:33PM', 'Aug 28 1999 12:00AM']
>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33),
datetime.datetime(1999, 8, 28, 0, 0)]
There are many options for converting from the strings to Pandas Timestamps using to_datetime
, so check the docs if you need anything special.
Likewise, Timestamps have many properties and methods that can be accessed in addition to .date
Solved this problem by blocking/ blacklisting IP address that were trying to brute force user accounts. Check your SQL access logs for large numbers of failed login attempts (usually for the 'sa' account).
string apppath =
(new System.IO.FileInfo
(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;
Remove the characters ^
(start of string) and $
(end of string) from the regular expression.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
Note, do not use Chrome's built in Speed Tester (it will show you unthrottled speed). Instead use another site, like Fast.com. That will show you properly throttled speeds.
Also, the throttling settings might be hidden and can be accessed from the network bar by clicking the tiny down arrow.
Just call the activity again itself using the intent. For example to refresh the layout of MainActivity, do like this:
startActivity(new Intent(MainActivity.this, MainActivity.class));
For MongoDB 3.6 and newer:
The $expr
operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP
operator to check the length of the string as follows:
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] }
})
For MongoDB 3.4 and newer:
You can also use the aggregation framework with the $redact
pipeline operator that allows you to proccess the logical condition with the $cond
operator and uses the special operations $$KEEP
to "keep" the document where the logical condition is true or $$PRUNE
to "remove" the document where the condition was false.
This operation is similar to having a $project
pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match
, except that $redact
uses a single pipeline stage which is more efficient.
As for the logical condition, there are String Aggregation Operators that you can use $strLenCP
operator to check the length of the string. If the length is $gt
a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.
Consider running the following aggregate operation which demonstrates the above concept:
db.usercollection.aggregate([
{ "$match": { "name": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$gt": [ { "$strLenCP": "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$limit": 2 }
])
If using $where
, try your query without the enclosing brackets:
db.usercollection.find({$where: "this.name.length > 40"}).limit(2);
A better query would be to to check for the field's existence and then check the length:
db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2);
or:
db.usercollection.find({name: {$exists: true}, $where: "this.name.length >
40"}).limit(2);
MongoDB evaluates non-$where
query operations before $where
expressions and non-$where
query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where
will be much slower compared to that. It's recommended to use JavaScript expressions and the $where
operator as a last resort when you can't structure the data in any other way, or when you are dealing with a
small subset of data.
A different and faster approach that avoids the use of the $where
operator is the $regex
operator. Consider the following pattern which searches for
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
Note - From the docs:
If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret
(^)
or a left anchor(\A)
, followed by a string of simple symbols. For example, the regex/^abc.*/
will be optimized by matching only against the values from the index that start withabc
.Additionally, while
/^a/, /^a.*/,
and/^a.*$/
match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,/^a.*/
, and/^a.*$/
are slower./^a/
can stop scanning after matching the prefix.
You can use the visible selector:
You can use the shell for this purpose.
Set shl = CreateObject("WScript.Shell")
shl.Run "cmd mkdir YourDir" & copy "
If you don't mind using your mouse a little bit:
This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell
and exit).
try
$(document).ready(function () {
//$('#dialog').dialog();
$('#dialog_link').click(function () {
$('#dialog').dialog('open');
return false;
});
});
there is a open arg in the last part
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
It's a shortening for this:
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
And |
is a bit-wise OR.
np.unique works given a list of tuples:
>>> np.unique([(1, 1), (2, 2), (3, 3), (4, 4), (2, 2)])
Out[9]:
array([[1, 1],
[2, 2],
[3, 3],
[4, 4]])
With a list of lists it raises a TypeError: unhashable type: 'list'
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions that get called by array.filter() is messy and less maintainable than the alternative.
Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:
// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
db = fdb.db('myTestDatabase'),
coll;
// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});
// Insert our records into the collection
coll.insert([
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]);
// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
name: /my nam/i
});
console.log(searchResultArray);
/* Outputs
[
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]
*/
Disclaimer: I am the developer of ForerunnerDB.
Concept Solution:br.read() returns particular character's int value so loop continue's until we won't get -1 as int value and Hence up to there it prints br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4: It's an advance way to read file using collection and arrays concept How we iterate using for each loop. check it here http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
After Login
private void getFbInfo() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
Log.d(LOG_TAG, "fb json object: " + object);
Log.d(LOG_TAG, "fb graph response: " + response);
String id = object.getString("id");
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
String image_url = "http://graph.facebook.com/" + id + "/picture?type=large";
String email;
if (object.has("email")) {
email = object.getString("email");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender,birthday"); // id,first_name,last_name,email,gender,birthday,cover,picture.type(large)
request.setParameters(parameters);
request.executeAsync();
}
days + hours
. Minutes are not included.hh:mm
or x hours y minutes
, would require additional calculations and string formatting.timedelta
math, and is faster than using .astype('timedelta64[h]')
timedelta
objects: See supported operations.datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
.total_xx
methods.# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
dateutil
maintainer:
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
(df.from_date - df.to_date).dt.total_seconds() / 3600
dateutil
module provides powerful extensions to the standard datetime
module.%%timeit
testimport pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
scikit-learn's LinearRegression doesn't calculate this information but you can easily extend the class to do it:
from sklearn import linear_model
from scipy import stats
import numpy as np
class LinearRegression(linear_model.LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-statistics
and p-values for model coefficients (betas).
Additional attributes available after .fit()
are `t` and `p` which are of the shape (y.shape[1], X.shape[1])
which is (n_features, n_coefs)
This class sets the intercept to 0 by default, since usually we include it
in X.
"""
def __init__(self, *args, **kwargs):
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression, self)\
.__init__(*args, **kwargs)
def fit(self, X, y, n_jobs=1):
self = super(LinearRegression, self).fit(X, y, n_jobs)
sse = np.sum((self.predict(X) - y) ** 2, axis=0) / float(X.shape[0] - X.shape[1])
se = np.array([
np.sqrt(np.diagonal(sse[i] * np.linalg.inv(np.dot(X.T, X))))
for i in range(sse.shape[0])
])
self.t = self.coef_ / se
self.p = 2 * (1 - stats.t.cdf(np.abs(self.t), y.shape[0] - X.shape[1]))
return self
Stolen from here.
You should take a look at statsmodels for this kind of statistical analysis in Python.
If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.
For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.
I had a similar question, so I worked up a complete runnable answer below. What I needed to do is pass a class (C) to an object (O) of an unrelated class and have that object (O) emit new objects of class (C) back to me when I asked for them.
The example below shows how this is done. There is a MagicGun class that you load with any subtype of the Projectile class (Pebble, Bullet or NuclearMissle). The interesting is you load it with subtypes of Projectile, but not actual objects of that type. The MagicGun creates the actual object when it's time to shoot.
You've annoyed the target!
You've holed the target!
You've obliterated the target!
click
click
import java.util.ArrayList;
import java.util.List;
public class PassAClass {
public static void main(String[] args) {
MagicGun gun = new MagicGun();
gun.loadWith(Pebble.class);
gun.loadWith(Bullet.class);
gun.loadWith(NuclearMissle.class);
//gun.loadWith(Object.class); // Won't compile -- Object is not a Projectile
for(int i=0; i<5; i++){
try {
String effect = gun.shoot().effectOnTarget();
System.out.printf("You've %s the target!\n", effect);
} catch (GunIsEmptyException e) {
System.err.printf("click\n");
}
}
}
}
class MagicGun {
/**
* projectiles holds a list of classes that extend Projectile. Because of erasure, it
* can't hold be a List<? extends Projectile> so we need the SuppressWarning. However
* the only way to add to it is the "loadWith" method which makes it typesafe.
*/
private @SuppressWarnings("rawtypes") List<Class> projectiles = new ArrayList<Class>();
/**
* Load the MagicGun with a new Projectile class.
* @param projectileClass The class of the Projectile to create when it's time to shoot.
*/
public void loadWith(Class<? extends Projectile> projectileClass){
projectiles.add(projectileClass);
}
/**
* Shoot the MagicGun with the next Projectile. Projectiles are shot First In First Out.
* @return A newly created Projectile object.
* @throws GunIsEmptyException
*/
public Projectile shoot() throws GunIsEmptyException{
if (projectiles.isEmpty())
throw new GunIsEmptyException();
Projectile projectile = null;
// We know it must be a Projectile, so the SuppressWarnings is OK
@SuppressWarnings("unchecked") Class<? extends Projectile> projectileClass = projectiles.get(0);
projectiles.remove(0);
try{
// http://www.java2s.com/Code/Java/Language-Basics/ObjectReflectioncreatenewinstance.htm
projectile = projectileClass.newInstance();
} catch (InstantiationException e) {
System.err.println(e);
} catch (IllegalAccessException e) {
System.err.println(e);
}
return projectile;
}
}
abstract class Projectile {
public abstract String effectOnTarget();
}
class Pebble extends Projectile {
@Override public String effectOnTarget() {
return "annoyed";
}
}
class Bullet extends Projectile {
@Override public String effectOnTarget() {
return "holed";
}
}
class NuclearMissle extends Projectile {
@Override public String effectOnTarget() {
return "obliterated";
}
}
class GunIsEmptyException extends Exception {
private static final long serialVersionUID = 4574971294051632635L;
}
There are 2 different ways to open URL in android and iphone.
FOR IOS use following code.
window.open("http://google.com", '_system');
and for android OS use following code.
navigator.app.loadUrl("http://google.com", {openExternal : true});
I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).
I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.
Maybe the problem is not in the format
but in the JavaScript
implementation of the play/ pause
methods. May I suggest visiting the following link where Google developer explains it in a good way?
Additionally, you could choose to use the newer webp
format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.
On that note: I've created a small script
that easily converts all standard formats to webp
. You can easily configure it to fit your needs. Here's the Github repo of the same projects.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Personally (and therefore subjectively) I've found that using Lombok makes my code more expressive about what I'm trying to achieve when compared to IDE/own implementations of intricate methods such as hashcode & equals.
When using
@EqualsAndHashCode(callSuper = false, of = { "field1", "field2", "field3" })
it's much easier to keep Equals & HashCode consistent and keep track of which fields are evaluated, than any IDE/own implementation. This is especially true when you're still adding / removing fields regularly.
The same goes for the @ToString
annotation and its parameters which clearly communicate the desired behavior regarding included / excluded fields, usage of getters or field access and wether or not to call super.toString()
.
And again by annotating an entire class with @Getter
or @Setter(AccessLevel.NONE)
(and optionally overriding any divergent methods) it's immediately clear what methods will be available for the fields.
The benefits go on and on..
In my mind it's not about reducing code, but about clearly communicating what you desire to achieve, rather than having to figure it out from Javadoc or implementations. The reduced code just makes it easier to spot any divergent-method implementations.
select * from SomeTable where 1=1
In my case
Problem Solved
I had similar problems. I removed the property="og:image:secure_url" and now it will scrub with just og:image. Sometimes, less is more
You can filter all characters from the string that are not printable using string.printable, like this:
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
string.printable on my machine contains:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:
''.join(filter(lambda x: x in printable, s))
You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.
for other type of products it will automatically restore it.
Please read following text which will clear your concept about this :
Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.
Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.
If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices
If your project is Maven-based, remember to set scope to provided for such dependencies as servlet-api, jsp-api. Otherwise, these jars will be exported to WEB-INF/lib and hence contaminate with those in Tomcat server. That causes painful problems.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
LinqToSql will automatically convert a .Skip(N1).Take(N2) into the TSQL syntax for you. In fact, every "query" you do in Linq, is actually just creating a SQL query for you in the background. To test this, just run SQL Profiler while your application is running.
The skip/take methodology has worked very well for me, and others from what I read.
Out of curiosity, what type of self-paging query do you have, that you believe is more efficient than Linq's skip/take?
myString.toInt()
- convert the string value into int .
Swift 3.x
If you have an integer hiding inside a string, you can convertby using the integer's constructor, like this:
let myInt = Int(textField.text)
As with other data types (Float and Double) you can also convert by using NSString:
let myString = "556"
let myInt = (myString as NSString).integerValue
Span is completely non-semantic. It has no meaning, and serves merely as an element for cosmetic effects.
Paragraphs have semantic meaning - they tell a machine (like a browser or a screen reader) that the content they encapsulate is a block of text, and has the same meaning as a paragraph of text in a book.
In my MacOS case for some reason Cmd+Shift+L is not working while pressing the short cut on the keyboard (although it work just fine while clicking on this option in menu: Selection -> Select All Occurences). So for me pressing Cmd+FN+F2 did the trick (FN is for enabling "F2" obviously).
Btw, if you forget this shortcut just do right-click on the selection and see "Change All Occurrences" option
Use TextureLoader to load a image as texture and then simply apply that texture to scene background.
new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
Result:
https://codepen.io/hiteshsahu/pen/jpGLpq?editors=0011
See the Pen Flat Earth Three.JS by Hitesh Sahu (@hiteshsahu) on CodePen.You have to clear the cache like that (because your old configuration is in you cache file) :
php artisan cache:clear
The pdo error comes from the fact Laravel use the pdo driver to connect to mysql
This is the most common feature of Notepad++ that I use to update my code.
All you need to do is:
You can refer to this link for pictorial explanation.
http://www.downloadorinstall.com/best-notepad-tips-and-tricks-for-faster-work-and-development/
You can try the expand
option in Series.str.split('seperator', expand=True)
.
By default expand
is False
.
expand
: bool, defaultFalse
Expand the splitted strings into separate columns.
- If
True
, return DataFrame/MultiIndex expanding dimensionality.- If
False
, return Series/Index, containing lists of strings.
Select * from table where name like search_criteria
if you are expecting the user to add their own wildcards...
I'm using VS 2017 with projects hosted with Git on visualstudio.com hosting (msdn)
The link above worked for me with the "GITHUB FOR WINDOWS" instructions.
http://www.scootersoftware.com/support.php?zz=kb_vcs#githubwindows
The config file was located where it indicated at "c:\users\username\.gitconfig" and I just changed the BC4's to BC3's for my situation and used the appropriate path:
C:/Program Files (x86)/Beyond Compare 3/bcomp.exe
With Bootstrap 4, the responsible css configuration in bootstrap.css
for .table-striped
is:
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgba(0, 0, 0, 0.05);
}
For a very simple solution, I just copied it into my custom.css
file, and changed the values of background-color
, so that now I have a fancier light blue shade:
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgba(72, 113, 248, 0.068);
}
If you can stand to use sed
(possibly execute from within your program, it'd be as simple as:
sed 's/(.*)//g'
I solved this issue with the following code:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName myhost.com
ServerAlias ww.myhost.com
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
</VirtualHost>
I also used:
a2enmod proxy_http
As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.
You can generate your responsive Facebook likebox here
https://developers.facebook.com/docs/plugins/page-plugin
This is the best solution ever rather than hacking CSS.
find -E /path/to -regex ".*\.(jpg|gif|png|jpeg)" > log
The -E
saves you from having to escape the parens and pipes in your regex.
This is an updated solution for HTML 5 if anyone is interested & not fond of "floating".
Table works great in this case as you can set the fixed width to the table & table-cell.
.content-container{
display: table;
width: 300px;
}
.content .right{
display: table-cell;
background-color:green;
width: 100px;
}
http://jsfiddle.net/EAEKc/596/ original source code from @merkuro
select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;
That's the simplest one without doing sub queries
Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.
MySQL does however:
ALTER TABLE mytable
ADD COLUMN new_column <type>
AFTER existing_column
I've tried with
let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString
instead
let UUID = NSUUID().UUIDString
and it works.
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");
PropertyConfigurator.configure("log4j.xml");
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.error(message);
To understand the differences you can look at this 2 examples
Example with Delegates (in this case, an Action - that is a kind of delegate that doesn't return a value)
public class Animal
{
public Action Run {get; set;}
public void RaiseEvent()
{
if (Run != null)
{
Run();
}
}
}
To use the delegate, you should do something like this:
Animal animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();
This code works well but you could have some weak spots.
For example, if I write this:
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;
with the last line of code, I have overridden the previous behaviors just with one missing +
(I have used =
instead of +=
)
Another weak spot is that every class which uses your Animal
class can raise RaiseEvent
just calling it animal.RaiseEvent()
.
To avoid these weak spots you can use events
in c#.
Your Animal class will change in this way:
public class ArgsSpecial : EventArgs
{
public ArgsSpecial (string val)
{
Operation=val;
}
public string Operation {get; set;}
}
public class Animal
{
// Empty delegate. In this way you are sure that value is always != null
// because no one outside of the class can change it.
public event EventHandler<ArgsSpecial> Run = delegate{}
public void RaiseEvent()
{
Run(this, new ArgsSpecial("Run faster"));
}
}
to call events
Animal animal= new Animal();
animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
animal.RaiseEvent();
Differences:
Notes:
EventHandler is declared as the following delegate:
public delegate void EventHandler (object sender, EventArgs e)
it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.
This example, which uses EventHandler<ArgsSpecial>
, can also be written using EventHandler
instead.
Refer here for documentation about EventHandler
You can get it to display time. From that you will probably have to have two controls (one date, one time) the accomplish what you want.
You can't do that using open. use codecs.
when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:
import codecs
file = codecs.open('data.txt','w','utf-8')
This was how I added a tracking branch so I can pull from it into my new branch:
git branch --set-upstream-to origin/Development new-branch
Splash screen example :
public class MainActivity extends Activity {
private ImageView splashImageView;
boolean splashloading = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashImageView = new ImageView(this);
splashImageView.setScaleType(ScaleType.FIT_XY);
splashImageView.setImageResource(R.drawable.ic_launcher);
setContentView(splashImageView);
splashloading = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
splashloading = false;
setContentView(R.layout.activity_main);
}
}, 3000);
}
}
Thank you, this post was very helpful, not only to reload the page with the suggested answer, but also as well to give me the idea to place a jQuery UI icon to a button:
<button style="display:block; vertical-align:middle; height:2.82em;"
title="Cargar nuevamente el código fuente sin darle un [Enter] a la dirección en la barra de direcciones"
class="ui-state-active ui-corner-all ui-priority-primary"
onclick="javascript:window.location.reload(true);">
<span style="display:inline-block;" class="ui-icon ui-icon-refresh"></span>
[<b>CARGAR NUEVAMENTE</b>]
</button>
Another possible problem (which I ran into):
Be sure that the ProjectInstaller
class is public
. To be honest, I am not sure how exactly I did it, but I added event handlers to ProjectInstaller.Designer.cs
, like:
this.serviceProcessInstaller1.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_BeforeInstall);
I guess during the automatical process of creating the handler function in ProjectInstaller.cs
it changed the class definition from
public class ProjectInstaller : System.Configuration.Install.Installer
to
partial class ProjectInstaller : System.Configuration.Install.Installer
replacing the public
keyword with partial
. So, in order to fix it it must be
public partial class ProjectInstaller : System.Configuration.Install.Installer
I use Visual Studio 2013 Community edition.
webBrowser.NavigateToString(yourString);
Your best bet to start is to use ?str()
. To explore some examples, let's make some data:
set.seed(3221) # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
@Wilmer E Henao H's solution is very streamlined:
sapply(my.data, class)
y x1 x2 X3
"numeric" "integer" "logical" "factor"
Using str()
gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):
str(my.data)
'data.frame': 5 obs. of 4 variables:
$ y : num 1.03 1.599 -0.818 0.872 -2.682
$ x1: int 1 2 3 4 5
$ x2: logi TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
@Gavin Simpson's approach is also streamlined, but provides slightly different information than class()
:
sapply(my.data, typeof)
y x1 x2 X3
"double" "integer" "logical" "integer"
For more information about class
, typeof
, and the middle child, mode
, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.
Instead of Windows PowerShell
, find the item in the Start Menu called SharePoint 2013 Management Shell
:
Add the docker group if it doesn't already exist.
$ sudo groupadd docker
Add the connected user "${USER}" to the docker group.
Change the user name to match your preferred user.
You may have to logout and log back in again for this to take effect.
$ sudo gpasswd -a ${USER} docker
Restart the Docker daemon.
$ sudo service docker restart
php.net manual has a few solid explanation and examples contributed by users of what stdClass is, I especially like this one http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773.
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.
When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.
Just using the command list did not work for me.
if you have a tuple just iterate until you have the elements there are necessary and after that append to a list. And if you go to the element level you can change it easily.
input:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1_as_list=[]
for i in level1:
inside_list=[]
for j in i:
inside_list.append(j)
level1_as_list.append(inside_list)
print(level1_as_list)enter code here
output:
[[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1]]
[Taken from http://javarevisited.blogspot.com/2011/05/top-10-tips-on-logging-in-java.html]
DEBUG is the lowest restricted java logging level and we should write everything we need to debug an application, this java logging mode should only be used on Development and Testing environment and must not be used in production environment.
INFO is more restricted than DEBUG java logging level and we should log messages which are informative purpose like Server has been started, Incoming messages, outgoing messages etc in INFO level logging in java.
WARN is more restricted than INFO java logging level and used to log warning sort of messages e.g. Connection lost between client and server. Database connection lost, Socket reaching to its limit. These messages and java logging level are almost important because you can setup alert on these logging messages in java and let your support team monitor health of your java application and react on this warning messages. In Summary WARN level is used to log warning message for logging in Java.
ERROR is the more restricted java logging level than WARN and used to log Errors and Exception, you can also setup alert on this java logging level and alert monitoring team to react on this messages. ERROR is serious for logging in Java and you should always print it.
FATAL java logging level designates very severe error events that will presumably lead the application to abort. After this mostly your application crashes and stopped.
OFF java logging level has the highest possible rank and is intended to turn off logging in Java.
If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:
def smart_find(haystack, needle):
if haystack.startswith(needle+" "):
return True
if haystack.endswith(" "+needle):
return True
if haystack.find(" "+needle+" ") != -1:
return True
return False
This assumes that commas and other punctuations have already been stripped out.
Just try this out:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type =
"button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();
context.restore();
}
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt){
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt){
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt){
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function(){
$("#wrapper").mouseover(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!
Here is fiddle for this Fiddle
By default git revert
refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD
is in fact a merge commit.
If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.
Often this will be parent number one, for example if you were on master
and did git merge unwanted
and then decided to revert the merge of unwanted
. The first parent would be your pre-merge master
branch and the second parent would be the tip of unwanted
.
In this case you could do:
git revert -m 1 HEAD
All answers here seem to assume that items is an array. However, in AngularJS, it might as well be an object. In that case, neither filtering with limitTo nor array.slice will work. As one possible solution, you can convert your object to an array, if you don't mind losing the object keys. Here is an example of a filter to do just that:
myFilter.filter('obj2arr', function() {
return function(obj) {
if (typeof obj === 'object') {
var arr = [], i = 0, key;
for( key in obj ) {
arr[i] = obj[key];
i++;
}
return arr;
}
else {
return obj;
}
};
});
Once it is an array, use slice or limitTo, as stated in other answers.
Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"
Please note that npm install --save
will foster whatever dependency your app requires in production code.
As for "typings", it is only required by TypeScript, which is eventually transpiled in JavaScript. Therefore, you probably do not want to have them in production code. I suggest to put it in your project's devDependencies
instead, by using
npm install --save-dev @types/lodash
or
npm install -D @types/lodash
(see Akash post for example). By the way, it's the way it is done in ng2 tuto.
Alternatively, here is how your package.json could look like:
{
"name": "my-project-name",
"version": "my-project-version",
"scripts": {whatever scripts you need: start, lite, ...},
// here comes the interesting part
"dependencies": {
"lodash": "^4.17.2"
}
"devDependencies": {
"@types/lodash": "^4.14.40"
}
}
just a tip
The nice thing about npm
is that you can start by simply do an npm install --save
or --save-dev
if you are not sure about the latest available version of the dependency you are looking for, and it will automatically set it for you in your package.json
for further use.
In my case problem was compiled framework architecture.
I'm running Xcode 11 and using Swift 5.1
I was tried to run tests but MyAppFrameWork product was compiled for Generic iOS Devices and the Test target needed an arm x86-64, So I rebuilt Framework for iOS Simulators and test cases successfuly start running.
I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.
The steps are :
You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers
Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.
Edit : you have to repeat the steps every time you will go on the production site.
Enums have toRaw()
and fromRaw()
methods. So if your raw value is an Int
, you can iterate from the first to last enum
:
enum Suit: Int {
case Spades = 1
case Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
for i in Suit.Spades.toRaw()...Suit.Clubs.toRaw() {
if let covertedSuit = Suit.fromRaw(i) {
let description = covertedSuit.simpleDescription()
}
}
One gotcha is that you need to test for optional values before running the simpleDescription
method, so we set convertedSuit
to our value first and then set a constant to convertedSuit.simpleDescription()
Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization.
public class MyClass
{
public virtual MyClass DeepClone()
{
var returnObj = (MyClass)MemberwiseClone();
var type = returnObj.GetType();
var fieldInfoArray = type.GetRuntimeFields().ToArray();
foreach (var fieldInfo in fieldInfoArray)
{
object sourceFieldValue = fieldInfo.GetValue(this);
if (!(sourceFieldValue is MyClass))
{
continue;
}
var sourceObj = (MyClass)sourceFieldValue;
var clonedObj = sourceObj.DeepClone();
fieldInfo.SetValue(returnObj, clonedObj);
}
return returnObj;
}
}
EDIT: requires
using System.Linq;
using System.Reflection;
That's How I used it
public MyClass Clone(MyClass theObjectIneededToClone)
{
MyClass clonedObj = theObjectIneededToClone.DeepClone();
}
http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.
Also on my site, I have
.ics
over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful..ics
areas that need careful handling:
Using some of the other answers here I made a version that replaces all the pertinent characters in one pass irrespective of the number of distinct encoded characters (only one call to replace()
) so will be faster for larger strings.
It doesn't rely on the DOM API to exist or on other libraries.
window.encodeHTML = (function() {
function escapeRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var encodings = {
'&' : '&',
'"' : '"',
'\'' : ''',
'<' : '<',
'>' : '>',
'\\' : '/'
};
function encode(what) { return encodings[what]; };
var specialChars = new RegExp('[' +
escapeRegex(Object.keys(encodings).join('')) +
']', 'g');
return function(text) { return text.replace(specialChars, encode); };
})();
Having ran that once, you can now call
encodeHTML('<>&"\'')
To get <>&"'
What about that?
HTML
<div class="chart" id="graph" data-percent="88"></div>
Javascript
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
and CSS
div {
position:relative;
margin:80px;
width:220px; height:220px;
}
canvas {
display: block;
position:absolute;
top:0;
left:0;
}
span {
color:#555;
display:block;
line-height:220px;
text-align:center;
width:220px;
font-family:sans-serif;
font-size:40px;
font-weight:100;
margin-left:5px;
}
http://jsfiddle.net/Aapn8/3410/
Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/
Require Screen sizes for splash :
LDPI: Portrait: 200 X 320px
MDPI: Portrait: 320 X 480px
HDPI: Portrait: 480 X 800px
XHDPI: Portrait: 720 X 1280px
XXHDPI: Portrait: 960 X 1600px
XXXHDPI: Portrait: 1440 x 2560px
Require icon Sizes for App :
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
In .Net MVC5 core 2.2, I use HttpContext.User.Identity.Name . It worked for me.
Your code assumes the existence of something:
$user = $_POST["username"];
PHP is letting you know that there is no "username" in the $_POST
array. In this instance, you would be safer checking to see if the value isset()
before attempting to access it:
if ( isset( $_POST["username"] ) ) {
/* ... proceed ... */
}
Alternatively, you could hi-jack the ||
operator to assign a default:
$user = $_POST["username"] || "visitor" ;
As long as the user's name isn't a falsy value, you can consider this method pretty reliable. A much safer route to default-assignment would be to use the ternary operator:
$user = isset( $_POST["username"] ) ? $_POST["username"] : "visitor" ;
I found a fairly robust solution at https://gallery.technet.microsoft.com/scriptcenter/c0c57332-8624-48c0-b4c3-5b31fe641c58 , which I thought was worth pointing out. It searches columns of these types: varchar, char, nvarchar, nchar, text. It works great and supports specific table-searching as well as multiple search-terms.
A more un-obtrusive way (assuming you use jQuery):
HTML:
<a id="my-link" href="page.html">page link</a>
Javascript:
$('#my-link').click(function(e)
{
e.preventDefault();
});
The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.
Sometimes we need a code block where we need to perform some operation right after setState where we are sure the state is being updated. That is where setState callback comes into play
For example, there was a scenario where I needed to enable a modal for 2 customers out of 20 customers, for the customers where we enabled it, there was a set of time taking API calls, so it looked like this
async componentDidMount() {
const appConfig = getCustomerConfig();
this.setState({enableModal: appConfig?.enableFeatures?.paymentModal }, async
()=>{
if(this.state.enableModal){
//make some API call for data needed in poput
}
});
}
enableModal boolean was required in UI blocks in the render function as well, that's why I did setState here, otherwise, could've just checked condition once and either called API set or not.
There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:
declare @transid varchar(15)
if @transid != 0
will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.
I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.
In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm
PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
$('#id-submit').click(function () {
$("input").val(function(i,val) {
return val.toUpperCase();
});
});
Check "PASSWORD_LIFE_TIME" by
Sql > select * from dba_profiles;
Set to Never expire
Sql> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
Then reset the password of locked user.
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
Maybe this link will help you.
See: std::string documentation.
#include <string>
is the most widely accepted.
I do not believe there is a "per query" way to do this. (You can use the use
keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go
command afterward.)
Remember, in SQL server fully qualified table names are in the format:
[database].[schema].[table]
In SQL Server Management Studio you can configure all the defaults you're asking about.
You can set up the default database
on a per-user basis (or in your connection string):
Security > Logins > (right click) user > Properties > General
You can set up the default schema
on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo
that is always the default):
Security > Logins > (right click) user > Properties > User Mapping > Default Schema
In short, if you use dbo
for your schema, you'll likely have the least amount of headaches.
Just add the onclick-attribute:
<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>
It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script>
tags - maybe it does what you want.
While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener
(as pointed out by other answers), if you expect the code to grow and stay maintainable.
Nothing helped me. Then I saw that the name of the project on the computer is different from the name on the git repository.
So I solved the problem.
For some reasons above mentioned approaches did now work for me, before I followed the advice to add .default
like this:
<div>
<img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>
It seems like str_shuffle would be a good use for this. Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
Answer provided by @jAndy should work but in Firefox you may face problem, window.location.reload(1); might not work, that's my personal experience.
So i would like to suggest:
setTimeout(function() { window.location=window.location;},5000);
This is tested and works fine.
Contrary to just about every answer on this post, UITextView
does have a placeholder property. For reasons beyond my comprehension, it is only exposed in IB, as such:
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="placeholder" value="My Placeholder"/>
</userDefinedRuntimeAttributes>
So if you are using storyboards and a static placeholder will suffice, just set the property on the inspector.
You can also set this property in code like this:
textView.setValue("My Placeholder", forKeyPath: "placeholder")
Its cloudy as to weather this is accessed via private API, as the property is exposed.
I haven't tried submitting with this method. But I will be submitting this way shortly and will update this answer accordingly.
UPDATE:
I have shipped this code in multiple releases with no issues from Apple.
UPDATE: This will only work in Xcode pre 11.2
NumberFormat.getNumberInstance(java.util.Locale.US).format(num);
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
Should declare logger like this:
private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());
so if you refactor your class name it follows.
I wrote an article about java logger with examples here.
I thought I'd add my take on this since I'm only interested in the first integer I boiled it down to this:
let errorStringWithNumbers = "error: 404 (not found)";
let errorNumber = parseInt(errorStringWithNumbers.toString().match(/\d+/g)[0]);
.toString()
is added only if you get the "string" from an fetch error. If not, then you can remove it from the line.
While using string, the best possible way to print your message is:
#include <iostream>
#include <string>
using namespace std;
int main(){
string newInput;
getline(cin, newInput);
cout<<newInput;
return 0;
}
this can simply do the work instead of doing the method you adopted.
@ECHO OFF
REM GET DAY OF WEEK VIA DATE TO JULIAN DAY NUMBER CONVERSION
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES AND ELIMINATE LEFT ZEROS
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%DATE%") DO SET /A MM=10%%A %% 100, DD=10%%B %% 100, YY=%%C
REM CALCULATE JULIAN DAY NUMBER, THEN DAY OF WEEK
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
SET /A DOW=(JDN+1)%%7
DOW is 0 for Sunday, 1 for Monday, etc.
You can simply write :
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
For Cordova, if you want to add it into your ios.json, do the following:
"NSAppTransportSecurity": [
{
"xml": "<dict><key>NSAllowsArbitraryLoads</key><true /></dict>"
}
]
And it should be inside of:
"*-Info.plist": {
"parents": {
}
}
Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer
I was facing a problem like this, and had the idea of simply changing the innerHTML of the problematic object's children.
adiv.innerHTML = "<div...> the original html that js uses </div>";
Seems dirty, but it saved my life, as it works!
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
I think the documentation is reasonably helpful!
If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.
So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.
If you do use og, then set type to: blog
Finally: fb:admins
or fb:app_id
- A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.
So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.
I also had the same issue, trying to run a unit test calling code that uses readEntity
. Can't use getEntity
in production code because that just returns a ByteInputStream
and not the content of the body and there is no way I am adding production code that is hit only in unit tests.
My solution was to create a response and then use a Mockito spy to mock out the readEntity
method:
Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);
Note that you can't use the when(mockResponse.readEntity(String.class)
option because that throws the same IllegalStateException
.
Hope this helps!
Use a real python console alongside Sublime
Both Sublime's build system and SublimeREPL (the answers above) are limited in that you can't easily interact with the workspace variables after you run your file.
If you want to run a script, then work in a REPL-like fashion (like you would in an IDE), then I recommend having Sublime open alongside an IPython console. Using AutoHotKey (Windows) or AutoKey (Linux), you can set this up such that a single shortcut will copy the filename (or just the selected code) and then paste this in the console to run the file.
Version A is simpler and that's why I would use it.
And if you turn on all compiler warnings in Java you will get a warning on the second Version because it is unnecesarry and turns up code complexity.
In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.
I am not sure if this helps but I had the same problem.
You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
If you want to have a new data frame then:
import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new= old[['A', 'C', 'D']]
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
I propose a script for removing randomly picked up items off a list until it is empty:
Maintain a set
and remove randomly picked up element (with choice
) until list is empty.
s=set(range(1,6))
import random
while len(s)>0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
Use some preprocessor macro to check if it's in windows or linux. For example
#ifdef WIN32
LIB=
#elif __GNUC__
LIB=wsock32
#endif
include -l$(LIB) in you build command.
You can also specify some command line argument to differentiate both.
sudo apt-get install php-intl
then restart your server
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
You can use the following the get the difference between parent and the view you interested in:
private int getRelativeTop(View view) {
final View parent = (View) view.getParent();
int[] parentLocation = new int[2];
int[] viewLocation = new int[2];
view.getLocationOnScreen(viewLocation);
parent.getLocationOnScreen(parentLocation);
return viewLocation[1] - parentLocation[1];
}
Dont forget to call it after the view is drawn:
timeIndicator.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
final int relativeTop = getRelativeTop(timeIndicator);
});
This code reads the file line by line.
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can also set a delimiter as a line separator and then perform the same.
scanner.useDelimiter(System.getProperty("line.separator"));
You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place
UPDATED ANSWER for your comment:
I just tried to create an input file with the content as below
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
tried to read it with the below code.it just worked fine.
File file = new File("/home/keerthivasan/Desktop/input.txt");
Scanner scr = null;
try {
scr = new Scanner(file);
while(scr.hasNext()){
System.out.println("line : "+scr.next());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
}
Output:
line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait
so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably
scr = new Scanner(file);
scr.useDelimiter("\r\n");
and then do your looping to read lines. Hope this helps!
To fix this you can simply use the exclamation mark if you're sure that the object is not null when accessing its property:
list!.values
At first sight, some people might confuse this with the safe navigation operator from angular, this is not the case!
list?.values
The !
post-fix expression will tell the TS compiler that variable is not null, if that's not the case it will crash at runtime
for useRef
hook use like this
const value = inputRef?.current?.value
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
The server-side processing language in use (eg PHP, .net, etc) isn't specified, but if it's PHP, grab the required number (or all the records) and instead of randomising in the query use PHP's shuffle function. I don't know if .net has an equivalent function but if it does then use that if you're using .net
ORDER BY RAND() can have quite a performance penalty, depending on how many records are involved.
My simple solution:
private boolean checkIfInt(double value){
return value - Math.floor(value) == 0;
}
The root problem here seems that iOS8 safari won't hide the address bar when scrolling down if the content is equal or less than the viewport.
As you found out already, adding some padding at the bottom gets around this issue:
html {
/* enough space to scroll up to get fullscreen on iOS8 */
padding-bottom: 80px;
}
// sort of emulate safari's "bounce back to top" scroll
window.addEventListener('scroll', function(ev) {
// avoids scrolling when the focused element is e.g. an input
if (
!document.activeElement
|| document.activeElement === document.body
) {
document.body.scrollIntoViewIfNeeded(true);
}
});
The above css should be conditionally applied, for example with UA sniffing adding a gt-ios8
class to <html>
.
You don't have to load the whole product. Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
A grind solution with jQuery when you haven't the control of the options
html:
<select id="selector" ng-select="selector" data-ng-init=init() >
...
</select>
js:
$scope.init = function () {
jQuery('#selector option:first').remove();
$scope.selector=jQuery('#selector option:first').val();
}
You can change your project XML to add existing subfolders and structures automatically into your project like "node_modules" from NPM:
This is for older MSBuild / Visual Studio versions
<ItemGroup>
<Item Include="$([System.IO.Directory]::GetFiles("$(MSBuildProjectDirectory)\node_modules","*",SearchOption.AllDirectories))"></Item>
</ItemGroup>
For the current MSBuild / Visual Studio versions:
Just put it in the nodes of the xml:
<Project>
</Project>
In this case just change $(MSBuildProjectDirectory)\node_modules to your folder name.
It is possible but you should use EnumSet
instead
enum MyEnum {
ONE, TWO;
public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}
Based on your replies to everyone else, something like this is what you're looking for.
string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string line in lines)
{
writer.WriteLine(line + "@");
}
}
You could use a for
loop to print the []Project
as shown in @VonC excellent answer.
package main
import "fmt"
type Project struct{ name string }
func main() {
projects := []Project{{"p1"}, {"p2"}}
for i := range projects {
p := projects[i]
fmt.Println(p.name) //p1, p2
}
}
You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items
$('#mySelect2').val(null).trigger('change');
you could try using Pandas to retrieve information and get it as dataframe
import pyodbc as cnn
import pandas as pd
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
df=pd.DataFrame(argumento)
df.to_clipboard(index=False,header=True)
tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn)
# Copy to Clipboard
copia(tableResult)
# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')
I hope this helps! Cheers!
From memory, you call stringstream::str()
to get the std::string
value out.
Consider the case where the strings are columns and the result should be a new column:
df <- data.frame(a = letters[1:5], b = LETTERS[1:5], c = 1:5)
df$new_col <- do.call(paste, c(df[c("a", "b")], sep = ", "))
df
# a b c new_col
#1 a A 1 a, A
#2 b B 2 b, B
#3 c C 3 c, C
#4 d D 4 d, D
#5 e E 5 e, E
Optionally, skip the [c("a", "b")]
subsetting if all columns needs to be pasted.
# you can also try str_c from stringr package as mentioned by other users too!
do.call(str_c, c(df[c("a", "b")], sep = ", "))
Mod-rewrite based solution :
Using the following code in htaccess automatically forwards all http requests to https.
RewriteEngine on
RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This will redirect your non-www and www http requests to www version of https.
Another solution (Apache 2.4*)
RewriteEngine on
RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This doesn't work on lower versions of apache as %{REQUEST_SCHEME} variable was added to mod-rewrite since 2.4.
In addition to above differences following are few more:
RV separates view creation and binding of data to view. In LV, you need to check if convertView is null or not for creating view, before binding data to it. So, in case of RV, view will be created only when it is needed but in case of LV, one can miss the check for convertview and will create view everytime.
Switching between Grid and List is more easy now with LayoutManager.
No need to notify and update all items, even if only single item is changed.
One had to implement view caching in case of LV. It is provided in RV by default. (There is difference between view caching n recycling.)
Very easy item animations in case of RV.
Use pip show
to find the version!
# in order to get package version execute the below command
pip show YOUR_PACKAGE_NAME | grep Version
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
You should only be pushing to a bare repository. A bare repository is a repository that has no checked out branches. If you were to cd to a bare repository directory, you'd only see the contents of a .git directory.
import kotlinx.android.synthetic.main.MainActivity.*
class Mainactivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.MainActivity)
txt.setText("hello Kotlin")
}
}
This line in your app.php
, 'key' => env('APP_KEY', 'SomeRandomString'),
, is saying that the key for your application can be found in your .env
file on the line APP_KEY
.
Basically it tells Laravel to look for the key in the .env
file first and if there isn't one there then to use 'SomeRandomString'
.
When you use the php artisan key:generate
it will generate the new key to your .env
file and not the app.php
file.
As kotapeter said, your .env
will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog
Using optional function from UITextFieldDelegate
.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.endEditing(false)
}
false
means that field can be ask to resign. true
– force resign.
break
leaves a loop, continue
jumps to the next iteration.
You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.
var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);
Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.
The standard probably says something like:
"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."
That is the C way of looking at static functions. This is deprecated in C++ however.
In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.
I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.
None of the others worked for me. I had to add the following dependency, as explained here
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
because I was targeting API 23.
It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659
The monkey patch detailed on this issue has resolved the problem for me:
# monkeypatches.py
# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
libc.malloc_trim(0)
except (OSError, AttributeError):
libc = None
__old_del = getattr(pd.DataFrame, '__del__', None)
def __new_del(self):
if __old_del:
__old_del(self)
libc.malloc_trim(0)
if libc:
print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
pd.DataFrame.__del__ = __new_del
else:
print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)
TL;DR
The @Autowired
annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.
Full explanation
The @Autowired
annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies
you have to put this tag in your XML (application context file):
<context:component-scan base-package="com.mycompany.movies" />
This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component
(for simple bean) or @Controller
(for a servlet control) or @Repository
(for DAO
classes) and these classes are somewhere under the package com.mycompany.movies
, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration
class (or any combination of the three).
The @Autowired
annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder
it understands (by the prefix set
+ the @Autowired
annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder
, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception
. To avoid the Exception
, you can use the @Qualifier
annotation and tell it which of the two beans to inject in the following manner:
@Qualifier("redBean")
class Red implements Color {
// Class code here
}
@Qualifier("blueBean")
class Blue implements Color {
// Class code here
}
Or if you prefer to declare the beans in your XML, it would look something like this:
<bean id="redBean" class="com.mycompany.movies.Red"/>
<bean id="blueBean" class="com.mycompany.movies.Blue"/>
In the @Autowired
declaration, you need to also add the @Qualifier
to tell which of the two color beans to inject:
@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
this.color = color;
}
If you don't want to use two annotations (the @Autowired
and @Qualifier
) you can use @Resource
to combine these two:
@Resource(name="redBean")
public void setColor(Color color) {
this.color = color;
}
The @Resource
(you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.
I'll just add two more comments:
@Inject
instead of @Autowired
because it is not Spring-specific and is part of the JSR-330
standard.@Inject
/ @Autowired
on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException
when you need to actually use the bean.Update: To complete the picture, I created a new question about the @Configuration
class.
Use:
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
AppSettings has been deprecated and is now considered obsolete (link).
In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.
As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
Message is clear that 'Authorization' is not allowed in API. Set
Access-Control-Allow-Headers: "Content-Type, Authorization"
I just needed to set the size of one textbox on one page. Coding attributes on the model and creating custom editor templates were overkill, so I just wrapped the @Html.EditorFor call with a span tag that called a class which specifies the size of the textbox.
.SpaceAvailableSearch input
{
width:25px;
}
<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>
First see your code:
dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);
Here you set both visibility to same field so that's the problem. I give one sample for that sample demo
The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.
The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.
The code he wrote would better as:
func Exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
But I suggest this instead:
func Exists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
Yes, there is better. Check the stat
or the fstat
function
Look the answer to my previous question here
c:\> for %i in (java.exe) do @echo. %~$PATH:i
C:\WINDOWS\system32\java.exe
You can also specify the font size relative to the base_size
included in themes such as theme_bw()
(where base_size
is 11) using the rel()
function.
For example:
ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
geom_point() +
theme_bw() +
theme(legend.text=element_text(size=rel(0.5)))
Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.
now I'll show you a sample example that exaplain how can you update your model from server.
HTML Code:
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="updateData()">Refresh Data</button>
</div>
So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData()
that will be invoked when we are need to update and refresh our Model persons.
Javascript Code:
app.controller('adsController', function($log,$scope,...){
.....
$scope.updateData = function(){
$http.get('/persons').success(function(data) {
$scope.persons = data;// Update Model-- Line X
});
}
});
Now I explain for you how it work:
when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get()
and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.
Even though this is an older question, I had the same one myself recently, and came up with a more simple solution using regular expressions and the string replace function as another alternative (no need for external js libraries or reliance on the ECMAScript Internalization API):
var d = new Date();
var localeTime = d.toLocaleTimeString();
var localeTimeSansSeconds = localeTime.replace(/:(\d{2}) (?=[AP]M)/, " ");
This approach uses a regex look-ahead to grab the :ss AM/PM end of the string and replaces the :ss part with a space, returning the rest of the string untouched. (Literally says "Find a colon with two digits and a space that is followed by either AM or PM and replace the colon, two digits, and space portion with just a space).
This expression/approach only works for en-US and en-US-like Locales. If you also wanted a similar outcome with, say, British English (en-GB), which doesn't use AM/PM, a different regular expression is needed.
Based on the original questioner's sample output, I assume that they were primarily dealing with American audiences and the en-US time schema.
create or replace function `seconds_hh_mi_ss` (seconds in number)
return varchar2
is
hours_var number;
minutes_var number;
seconds_var number;
remeinder_var number;
output_var varchar2(32);
begin
select seconds - mod(seconds,3600) into hours_var from dual;
select seconds - hours_var into remeinder_var from dual;
select (remeinder_var - mod(remeinder_var,60)) into minutes_var from dual;
select seconds - (hours_var+minutes_var) into seconds_var from dual;
output_var := hours_var/3600||':'||minutes_var/60||':'||seconds_var;
return(output_var);
end;
/
Try to add continue;
where you want to skip 1 iteration.
Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.
http://www.javacoffeebreak.com/articles/loopyjava/index.html
Right Click on Project--> Add--> New Project-->click on Class Library.
Now your class library is created as class1.cs
Right Click on References(of your program/console app)
-->Add Reference-->classLibrary1(whatever you named) Now mention "using ClassLibrary1" in your program/console app
Now u can easily call the method/property in your console app
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
simpledb.execSQL("CREATE TABLE IF NOT EXISTS " + tablename + "(id INTEGER PRIMARY KEY AUTOINCREMENT,lat double,lng double,address varchar)");
simpledb.execSQL("insert into '" + tablename + "'(lat,lng,address)values('22.2891001','70.780154','craftbox');");
simpledb.execSQL("insert into '" + tablename + "'(lat,lng,address)values('22.2901396','70.7782428','kotecha');");//22.2904718 //70.7783906
simpledb.execSQL("insert into '" + tablename + "'(lat,lng,address)values('22.2863155','70.772108','kkv Hall');");
simpledb.execSQL("insert into '" + tablename + "'(lat,lng,address)values('22.275993','70.778076','nana mava');");
simpledb.execSQL("insert into '" + tablename + "'(lat,lng,address)values('22.2667148','70.7609386','Govani boys hostal');");
double curentlat=22.2667258; //22.2677258
double curentlong=70.76096826;//70.76096826
double curentlat1=curentlat+0.0010000;
double curentlat2=curentlat-0.0010000;
double curentlong1=curentlong+0.0010000;
double curentlong2=curentlong-0.0010000;
try{
Cursor c=simpledb.rawQuery("select * from '"+tablename+"' where (lat BETWEEN '"+curentlat2+"' and '"+curentlat1+"') or (lng BETWEEN '"+curentlong2+"' and '"+curentlong1+"')",null);
Log.d("SQL ", c.toString());
if(c.getCount()>0)
{
while (c.moveToNext())
{
double d=c.getDouble(1);
double d1=c.getDouble(2);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
The code below has the following features:
As others have said, no solution can be perfect (and certainly one can't easily differentiate between the various 8-bit extended ASCII encodings in use worldwide), but we can get 'good enough' especially if the developer also presents to the user a list of alternative encodings as shown here: What is the most common encoding of each language?
A full list of Encodings can be found using Encoding.GetEncodings();
// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little
// & big endian), and local default codepage, and potentially other codepages.
// 'taster' = number of bytes to check of the file (to save processing). Higher
// value is slower, but more reliable (especially UTF-8 with special characters
// later on may appear to be ASCII initially). If taster = 0, then taster
// becomes the length of the file (for maximum reliability). 'text' is simply
// the string with the discovered encoding applied to the file.
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000)
{
byte[] b = File.ReadAllBytes(filename);
//////////////// First check the low hanging fruit by checking if a
//////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4)
if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); } // UTF-32, big-endian
else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; } // UTF-32, little-endian
else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; } // UTF-16, big-endian
else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; } // UTF-16, little-endian
else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8
else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7
//////////// If the code reaches here, no BOM/signature was found, so now
//////////// we need to 'taste' the file to see if can manually discover
//////////// the encoding. A high taster value is desired for UTF-8
if (taster == 0 || taster > b.Length) taster = b.Length; // Taster size can't be bigger than the filesize obviously.
// Some text files are encoded in UTF8, but have no BOM/signature. Hence
// the below manually checks for a UTF8 pattern. This code is based off
// the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8
// For our purposes, an unnecessarily strict (and terser/slower)
// implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
// For the below, false positives should be exceedingly rare (and would
// be either slightly malformed UTF-8 (which would suit our purposes
// anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot).
int i = 0;
bool utf8 = false;
while (i < taster - 4)
{
if (b[i] <= 0x7F) { i += 1; continue; } // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks.
if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; }
if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; }
if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; }
utf8 = false; break;
}
if (utf8 == true) {
text = Encoding.UTF8.GetString(b);
return Encoding.UTF8;
}
// The next check is a heuristic attempt to detect UTF-16 without a BOM.
// We simply look for zeroes in odd or even byte places, and if a certain
// threshold is reached, the code is 'probably' UF-16.
double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10%
int count = 0;
for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++;
if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; }
count = 0;
for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++;
if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian)
// Finally, a long shot - let's see if we can find "charset=xyz" or
// "encoding=xyz" to identify the encoding:
for (int n = 0; n < taster-9; n++)
{
if (
((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) ||
((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '='))
)
{
if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9;
if (b[n] == '"' || b[n] == '\'') n++;
int oldn = n;
while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z')))
{ n++; }
byte[] nb = new byte[n-oldn];
Array.Copy(b, oldn, nb, 0, n-oldn);
try {
string internalEnc = Encoding.ASCII.GetString(nb);
text = Encoding.GetEncoding(internalEnc).GetString(b);
return Encoding.GetEncoding(internalEnc);
}
catch { break; } // If C# doesn't recognize the name of the encoding, break.
}
}
// If all else fails, the encoding is probably (though certainly not
// definitely) the user's local codepage! One might present to the user a
// list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language
// A full list can be found using Encoding.GetEncodings();
text = Encoding.Default.GetString(b);
return Encoding.Default;
}
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
they are two different things..
[]
is declaring an Array:
given, a list of elements held by numeric index.
{}
is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more @ This Article
Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:
PathToContainingFolder =
"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])
so that
\Users\me\Desktop\New folder\file.txt
becomes
\Users\me\Desktop\New folder
Late to the game, but you can also use a localisation file
DataTable provides a .json
localized file, which contains the key sEmptyTable
and the corresponding localized message.
For example, just download the localized json file on the above link, then initialize your Datatable
like that :
$('#example').dataTable( {
"language": {
"url": "path/to/your/json/file.json"
}
});
IMHO, that's a lot cleaner, because your localized content is located in an external file.
This syntax works for DataTables 1.10.16, I didn't test on previous versions.
You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.
Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.
The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.
With CentOS, you can do it using a combination of fastcgi for one version of PHP, and php-fpm for the other, as described here:
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm
CentOS/RHEL 5.x series have php-5.1 in box, simply install it with yum, eg:
sudo yum install php php-mysql php-mbstring php-mcrypt
For php 5.2 and 5.3, we can find many rpm packages on the Internet. However, they all conflict with the php which comes with CentOS, so, we’d better build and install them from soure, this is not difficult, the point is to install php at different location.
However, when install php as an apache module, we can only use one version of php at the same time. If we need to run different version of php on the same server, at the same time, for example, different virtual host may need different version of php. Fortunately, the cool FastCGI and PHP-FPM can help.
Build and install php-5.2 with fastcgi enabled
yum install gcc libxml2-devel bzip2-devel zlib-devel \
curl-devel libmcrypt-devel libjpeg-devel \
libpng-devel gd-devel mysql-devel
wget http://cn.php.net/get/php-5.2.17.tar.bz2/from/this/mirror
tar -xjf php-5.2.17.tar.bz2
cd php-5.2.17
./configure --prefix=/usr/local/php52 \
--with-config-file-path=/etc/php52 \
--with-config-file-scan-dir=/etc/php52/php.d \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-fastcgi \
--enable-force-cgi-redirect \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 > /dev/null
sudo make install
sudo mkdir /etc/php52
sudo cp php.ini-recommended /etc/php52/php.ini
create file /usr/local/php52/bin/fcgiwrapper.sh
#!/bin/bash
PHP_FCGI_MAX_REQUESTS=10000
export PHP_FCGI_MAX_REQUESTS
exec /usr/local/php52/bin/php-cgi
chmod a+x /usr/local/php52/bin/fcgiwrapper.sh
Build and install php-5.3 with fpm enabled
wget http://cn.php.net/get/php-5.3.6.tar.bz2/from/this/mirror
tar -xjf php-5.3.6.tar.bz2
cd php-5.3.6
./configure --prefix=/usr/local/php53 \
--with-config-file-path=/etc/php53 \
--with-config-file-scan-dir=/etc/php53/php.d \
--enable-fpm \
--with-fpm-user=apache \
--with-fpm-group=apache \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 && sudo make install
sudo mkdir /etc/php53
sudo cp php.ini-production /etc/php53/php.ini
sed -i -e 's#php_fpm_CONF=\${prefix}/etc/php-fpm.conf#php_fpm_CONF=/etc/php53/php-fpm.conf#' \
sapi/fpm/init.d.php-fpm
sudo cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
sudo chmod a+x /etc/init.d/php-fpm
sudo /sbin/chkconfig --add php-fpm
sudo /sbin/chkconfig php-fpm on
sudo cp sapi/fpm/php-fpm.conf /etc/php53/
Configue php-fpm
Edit /etc/php53/php-fpm.conf, change some settings. This step is mainly to uncomment some settings, you can adjust the value if you like.
pid = run/php-fpm.pid
listen = 127.0.0.1:9000
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
Then, start fpm
sudo /etc/init.d/php-fpm start
Install and setup mod_fastcgi, mod_fcgid
sudo yum install libtool httpd-devel apr-devel
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
tar -xzf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6
cp Makefile.AP2 Makefile
sudo make top_dir=/usr/lib64/httpd/ install
sudo sh -c "echo 'LoadModule fastcgi_module modules/mod_fastcgi.so' > /etc/httpd/conf.d/mod_fastcgi.conf"
yum install mod_fcgid
Setup and test virtual hosts
1) Add the following line to /etc/hosts
127.0.0.1 web1.example.com web2.example.com web3.example.com
2) Create web document root and drop an index.php under it to show phpinfo switch to user root, run
mkdir /var/www/fcgi-bin
for i in {1..3}; do
web_root=/var/www/web$i
mkdir $web_root
echo "<?php phpinfo(); ?>" > $web_root/index.php
done
Note: The empty /var/www/fcgi-bin directory is required, DO NOT REMOVE IT LATER
3) Create Apache config file(append to httpd.conf)
NameVirtualHost *:80
# module settings
# mod_fcgid
<IfModule mod_fcgid.c>
idletimeout 3600
processlifetime 7200
maxprocesscount 17
maxrequestsperprocess 16
ipcconnecttimeout 60
ipccommtimeout 90
</IfModule>
# mod_fastcgi with php-fpm
<IfModule mod_fastcgi.c>
FastCgiExternalServer /var/www/fcgi-bin/php-fpm -host 127.0.0.1:9000
</IfModule>
# virtual hosts...
#################################################################
#1st virtual host, use mod_php, run php-5.1
#################################################################
<VirtualHost *:80>
ServerName web1.example.com
DocumentRoot "/var/www/web1"
<ifmodule mod_php5.c>
<FilesMatch \.php$>
AddHandler php5-script .php
</FilesMatch>
</IfModule>
<Directory "/var/www/web1">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#2nd virtual host, use mod_fcgid, run php-5.2
#################################################################
<VirtualHost *:80>
ServerName web2.example.com
DocumentRoot "/var/www/web2"
<IfModule mod_fcgid.c>
AddHandler fcgid-script .php
FCGIWrapper /usr/local/php52/bin/fcgiwrapper.sh
</IfModule>
<Directory "/var/www/web2">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#3rd virtual host, use mod_fastcgi + php-fpm, run php-5.3
#################################################################
<VirtualHost *:80>
ServerName web3.example.com
DocumentRoot "/var/www/web3"
<IfModule mod_fastcgi.c>
ScriptAlias /fcgi-bin/ /var/www/fcgi-bin/
AddHandler php5-fastcgi .php
Action php5-fastcgi /fcgi-bin/php-fpm
</IfModule>
<Directory "/var/www/web3">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
4) restart apache. visit the 3 sites respectly to view phpinfo and validate the result. ie:
http://web1.example.com
http://web2.example.com
http://web3.example.com
If all OK, you can use one of the 3 virtual host as template to create new virtual host, with the desired php version.
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/
Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:
SELECT t.owner,
t.table_name,
t.num_rows,
Count(*)
FROM all_tables t
LEFT JOIN all_tab_columns c
ON t.table_name = c.table_name
WHERE num_rows IS NOT NULL
GROUP BY t.owner,
t.table_name,
t.num_rows
ORDER BY t.num_rows DESC;
I am using Linux Mint : After installing LAMP along with PhpMyAdmin, I linked both the configuration files of Apache and PhpMyAdmin. It did the trick. Following are the commands.
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
sudo /etc/init.d/apache2 reload
If you need to get quantity of selected checkboxes:
var selected = []; // initialize array
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this));
}
});
var selectedQuantity = selected.length;