Programs & Examples On #Git

Git is an open-source distributed version control system (DVCS). Use this tag for questions related to Git usage and workflows. Do not use this tag for general programming questions that happen to involve a Git repository.

How to cherry-pick multiple commits

git rev-list --reverse b..f | xargs -n 1 git cherry-pick

Undo working copy modifications of one file in Git?

For me only this one worked

git checkout -p filename

enter image description here

How Do I Upload Eclipse Projects to GitHub?

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.

What does "fatal: bad revision" mean?

git revert doesn't take a filename parameter. Do you want git checkout?

Git clone particular version of remote repository

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:

  1. 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>

  2. 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.

How to add a local repo and treat it as a remote repo

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

What's the difference between git clone --mirror and git clone --bare

$ 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.

How to open google chrome from terminal?

on mac terminal (at least in ZSH): open stackoverflow.com (opens site in new tab in your chrome default browser)

Why are there two ways to unstage a file in Git?

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).

Cannot push to GitHub - keeps saying need merge

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

Partly cherry-picking a commit with Git

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.)

How to upgrade Git on Windows to the latest version?

First, check your git version by using this command

git version

Then follow the case according to your git version

Three cases:

  1. If your git version is 2.14.1 or earlier:

    Uninstall the git, download the latest git, and install it again.

  2. And versions between 2.14.2 and 2.16.1:

    Use command git update

  3. If the version is equal to or greater than Git 2.16.1(2):

    Use command git update-git-for-windows

Move branch pointer to different commit without checkout

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.

Renaming branches remotely in Git

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

How to get back to the latest commit after checking out a previous commit?

You can simply do git pull origin branchname. It will fetch the latest commit again.

How line ending conversions work with git core.autocrlf between different operating systems

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  

How to compare different branches in Visual Studio Code

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

How to remove a file from the index in git?

This should unstage a <file> for you (without removing or otherwise modifying the file):

git reset <file>

Git - What is the difference between push.default "matching" and "simple"

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.

How do I ignore files in a directory in Git?

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

GIT: Checkout to a specific folder

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.

git: fatal: I don't handle protocol '??http'

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

git clone https://[email protected]/abcuser/myproject.git


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.

How to get just one file from another branch

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.

SSH Key - Still asking for password and passphrase

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.

How to Diff between local uncommitted changes and origin

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)

Create Git branch with current changes

Follow these steps:

  1. Create a new branch:

    git branch newfeature
    
  2. Checkout new branch: (this will not reset your work.)

    git checkout newfeature
    
  3. 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'.

Display last git commit comment

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

git pull remote branch cannot find remote ref

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:

_x000D_
_x000D_
//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_
_x000D_
_x000D_

How can I make git accept a self signed certificate?

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

git remote prune – didn't show as many pruned branches as I expected

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:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including 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)

How to get the current branch name in Git?

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:enter image description here

Is it possible to have different Git configuration for different projects?

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.)

Fastest way to download a GitHub project

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

How to copy commits from one branch to another?

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>

How to resolve git's "not something we can merge" error

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.

git: Switch branch and ignore any changes without committing

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

Bitbucket git credentials if signed up with Google

Follow these steps:

  1. login to bitbucket
  2. Click on Personal Settings
  3. Click on Create App Password, here give permission to read and write and the login to GitHub desktop using the same password. Note: Take a screenshot of the password as you won't retrieve it again.

steps updated as on 13th July 2020 Thank You: Rahul Daksh

How to upgrade Git to latest version on macOS?

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"

Can I make 'git diff' only the line numbers AND changed file names?

So easy:

git diff --name-only

Go forth and diff!

GIT vs. Perforce- Two VCS will enter... one will leave

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.

How to know the git username and email saved during configuration?

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

how to remove untracked files in Git?

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.

How do you push a tag to a remote repository using Git?

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:

http://www.cubearticle.com/articles/more/git/git-tag

http://wptheming.com/2011/04/add-remove-github-tags

Should I use past or present tense in git commit messages?

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.

Squash my last X commits together using Git

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.

Cannot checkout, file is unmerged

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.

How to resolve merge conflicts in Git repository?

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

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

Print commit message of a given commit in git

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.

How to exit a 'git status' list in a terminal?

Please try this steps in git bash, It may help you.

  1. CTRL + C
  2. :qa!

How do I git rm a file without deleting it from disk?

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.

gitx How do I get my 'Detached HEAD' commits back into master

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.

How do I delete a local repository in git?

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.

How to connect to a remote Git repository?

It's simple and follow the small Steps to proceed:

  • Install git on the remote server say some ec2 instance
  • Now create a project folder `$mkdir project.git
  • $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.

Undo git update-index --assume-unchanged <file>

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
  1. git ls-files -v will print all files with their status
  2. grep '^[a-z]' will filter files and select only assume unchanged
  3. cut -c 3- will remove status and leave only paths, cutting from the 3-rd character to the end
  4. tr '\012' '\000' will replace end of line character (\012) to zero character (\000)
  5. xargs -0 git update-index --no-assume-unchanged will pass all paths separated by zero character to git update-index --no-assume-unchanged to undo

How do I work with a git repository within another repository?

I 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.

git returns http error 407 from proxy after CONNECT

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

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

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.

Find size of Git repository

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:

  • Get the www.jfrog.com API from any search engine
  • Look at Get Storage Summary Info

How to undo last commit

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~

git push >> fatal: no configured push destination

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

Easy way to pull latest of all git submodules

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

git with development, staging and production branches

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.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

To Quickly Create the Remote Repository by Using a Bash Shell

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:

  1. create a shell script in a directory i.e. /home/USER_NAME/Desktop/my_scripts named githubscript.sh
  2. Modify and save the following code to the 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.

  1. Set required permissions to the script file chmod 755 githubscript.sh

  2. Include the scripts directory in the environment configuration file. nano ~/.profile; export PATH="$PATH:$HOME/Desktop/my_scripts"

  3. Also set an alias to run the githubscript.sh file. nano ~/.bashrc; alias githubrepo="bash githubscript.sh"

  4. Now reload the .bashrc and .profile files in the terminal. source ~/.bashrc ~/.profile;

  5. Now to create a new repository i.e. demo: githubrepo demo;

Setting up and using Meld as your git difftool and mergetool

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): Meld showing list of files with changes between the $LOCAL and $REMOTE

Then it is possible to click on each file and show the changes inside Meld.

How to remove origin from git repository

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

How does origin/HEAD get set?

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.

How to show changed file name only with git log?

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.

Editing the git commit message in GitHub

GitHub's instructions for doing this:

  1. On the command line, navigate to the repository that contains the commit you want to amend.
  2. Type git commit --amend and press Enter.
  3. In your text editor, edit the commit message and save the commit.
  4. Use the git push --force example-branch command to force push over the old commit.

Source: https://help.github.com/articles/changing-a-commit-message/

List files in local git repo?

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

How can I put a database under git (version control)?

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

How to add a file to the last commit in git?

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.

How to use gitignore command in git

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.

Move existing, uncommitted work to a new branch in Git

Alternatively:

  1. Save current changes to a temp stash:

    $ git stash

  2. 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.

How to commit changes to a new branch

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

Git push failed, "Non-fast forward updates were rejected"

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/

Generating statistics from Git repository

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:

  • General statistics
    • Total files (text and binary)
    • Total lines (added and deleted)
    • Total commits
    • Authors
  • Activity (total and per author)
    • Commits by date
    • Commits by hour of day
    • Commits by day of week
    • Commits by hour of week
    • Commits by month of year
    • Commits by year
    • Commits by year and month
  • Authors
    • Commits by author
    • Lines added by author
    • Lines deleted by author
    • Lines changed by author
  • Files and lines
    • By date
    • By extension

If you have any idea what to add or improve please let me know, I would appreciate any feedback.

How to grep Git commit diffs or contents for a certain word?

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.

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

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

git clone: Authentication failed for <URL>

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. enter image description here

Github: error cloning my private repository

I received this error after moving git across hard drives. Deleting and reinstalling in the new location fixed things

Browse and display files in a git repo without cloning

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

Various ways to remove local Git changes

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>

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

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

How do I commit only some files?

Suppose you made changes to multiple files, like:

  • File1
  • File2
  • File3
  • File4
  • File5

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

pip install from git repo branch

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.

Git Remote: Error: fatal: protocol error: bad line length character: Unab

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>

Get a list of all git commits, including the 'lost' ones

@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.

How to show first commit by 'git log'?

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.

How to permanently remove few commits from remote branch

Important: Make sure you specify which branches on "git push -f" or you might inadvertently modify other branches![*]

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
  2. Delete the last commit
  3. Delete commit from a list

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

rejected master -> master (non-fast-forward)

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

Undo git stash pop that results in merge conflict

Instructions here are a little complicated so I'm going to offer something more straightforward:

  1. git reset HEAD --hard Abandon all changes to the current branch

  2. ... Perform intermediary work as necessary

  3. git stash pop Re-pop the stash again at a later date when you're ready

How to recover a dropped stash in Git?

You can achieve this in 2 easy steps

  1. 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

  2. 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"

How do I undo the most recent local commits in Git?

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.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

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):

  • cloned to network storage in my private home network (my home network)
    • branch checked out: DEVELOPMENT
  • cloned to other machines (laptops, small data center server in my office, etc)
    • branch checked out: 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.

How to get commit history for just one branch?

You can use only git log --oneline

How to save a git commit message from windows cmd?

With the atom editor, you just need to install the git-plus package.

How to remove multiple deleted files in Git repository

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.

How to convert a normal Git repository to a bare one?

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.

  1. create a bare repository
  2. cd into the local repository which has local checkedout branches and remote branches
  3. git push /path/to/bare/repo +refs/remotes/origin/:refs/heads/

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

Is there a no-duplicate List implementation out there?

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>.

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

Check if decimal value is null

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

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

How to add font-awesome to Angular 2 + CLI project

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"
        ]

Converting string into datetime

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

Connection to SQL Server Works Sometimes

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).

Get path to execution directory of Windows Forms application

string apppath = 
    (new System.IO.FileInfo
    (System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;

Check for special characters in string

Remove the characters ^ (start of string) and $ (end of string) from the regular expression.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;

syntax error, unexpected T_VARIABLE

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.

Simulate limited bandwidth from within Chrome?

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.

How to force an entire layout View refresh?

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));

String field value length in mongoDB

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 with abc.

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.

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

How to temporarily exit Vim and go back

If you don't mind using your mouse a little bit:

  • Start your terminal,
  • select a file,
  • select Open Tab.

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).

Open Jquery modal dialog on click event

try

$(document).ready(function () {
    //$('#dialog').dialog(); 
    $('#dialog_link').click(function () {
        $('#dialog').dialog('open');
        return false;
    });
});

there is a open arg in the last part

How to vertical align an inline-block in a line of text?

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:

Working Example

(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>

javascript pushing element at the beginning of an array

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

What does "|=" mean? (pipe equal operator)

It's a shortening for this:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

And | is a bit-wise OR.

Find unique rows in numpy.array

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'

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

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 .

Javascript search inside a JSON object

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.

Using BufferedReader.readLine() in a while loop properly

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

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

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();
}

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

  • How do I convert my results to only hours and minutes
    • The accepted answer only returns days + hours. Minutes are not included.
  • To provide a column that has hours and minutes, as hh:mm or x hours y minutes, would require additional calculations and string formatting.
  • This answer shows how to get either total hours or total minutes as a float, using timedelta math, and is faster than using .astype('timedelta64[h]')
  • Pandas Time Deltas User Guide
  • Pandas Time series / date functionality User Guide
  • python timedelta objects: See supported operations.
  • The following sample data is already a 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

Other methods

  • An item of note from the podcast in Other Resources, .total_seconds() was added and merged when the core developer was on vacation, and would not have been approved.
    • This is also why there aren't other .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

Other Resources

%%timeit test

import 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)

Find p-value (significance) in scikit-learn LinearRegression

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.

Android Pop-up message

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.

How to pass a type as a method parameter in Java

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.

The Output

You've annoyed the target!
You've holed the target!
You've obliterated the target!
click
click

The Code

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;
}

phonegap open link in browser

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});

.mp4 file not playing in chrome

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.

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

Is it safe to use Project Lombok?

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.

SQL Server - boolean literal?

select * from SomeTable where 1=1

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

In my case

  1. Select your project (In my case i have 2 targets)
  2. Go to Build Phases
  3. Compile Sources
  4. Check if the number of items on each targets is the same (mine was different)
  5. Add the missing file / Remove the duplicated file

Problem Solved

FB OpenGraph og:image not pulling images (possibly https?)

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

How can I remove non-ASCII characters but leave periods and spaces using Python?

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))

What does "restore purchases" in In-App purchases mean?

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

Why did Servlet.service() for servlet jsp throw this exception?

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>

efficient way to implement paging

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?

Converting String to Int with Swift

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

When to use <span> instead <p>?

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.

Select all occurrences of selected word in VSCode

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

Using textures in THREE.js

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.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

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

How do I delete specific lines in Notepad++?

This is the most common feature of Notepad++ that I use to update my code.

All you need to do is:

  • Select common string that is present in all lines.
  • Press Ctrl + F
  • In the Mark tab, paste the recurring string and check the Bookmark line checkbox.
  • Click on Mark All
  • Now go to menu SearchBookmarkRemove Bookmarked Lines

You can refer to this link for pictorial explanation.

http://www.downloadorinstall.com/best-notepad-tips-and-tricks-for-faster-work-and-development/

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

You can try the expand option in Series.str.split('seperator', expand=True).
By default expand is False.

expand : bool, default False
Expand the splitted strings into separate columns.

  • If True, return DataFrame/MultiIndex expanding dimensionality.
  • If False, return Series/Index, containing lists of strings.

SQL 'LIKE' query using '%' where the search criteria contains '%'

Select * from table where name like search_criteria

if you are expecting the user to add their own wildcards...

How to configure Visual Studio to use Beyond Compare

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

Bootstrap table striped: How do I change the stripe background colour?

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);
}

How can I remove text within parentheses with a regex?

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

Apache redirect to another port

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

How to make the Facebook Like Box responsive?

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.

How to use find command to find all files with extensions from list?

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.

Expand div to max width when float:left is set

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

How to get the last row of an Oracle a table

select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;

That's the simplest one without doing sub queries

SQL Query to add a new column after an existing column in SQL Server 2005

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

How to get a unique device ID in Swift?

I've tried with

let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString

instead

let UUID = NSUUID().UUIDString

and it works.

Plot size and resolution with R markdown, knitr, pandoc, beamer

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 using maven, usually you put log4j.properties under java or resources?

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);

What are the differences between delegates and events?

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:

  1. You aren't using a public property but a public field (using events, the compiler protects your fields from unwanted access)
  2. Events can't be assigned directly. In this case, it won't give rise to the previous error that I have showed with overriding the behavior.
  3. No one outside of your class can raise the event.
  4. Events can be included in an interface declaration, whereas a field cannot

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

DateTimePicker: pick both date and time

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.

Python reading from a file and saving to utf-8

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')

What is a tracking branch?

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

How do I make a splash screen?

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);

    }

}

How to reload a page using JavaScript

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>
    &nbsp;[<b>CARGAR NUEVAMENTE</b>]&nbsp;
</button>

Edited to show how this looks like when included in a project

2016-07-02

My apologies as this is a personal project that implies using jQuery UI, Themeroller, Icons framework, methods like jQuery tabs, but it's in Spanish ;)

Install Windows Service created in Visual Studio

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.

Determine the data types of a data frame's columns

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.

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Docker command can't connect to Docker daemon

Giving non-root access - from docker

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

What is stdClass in PHP?

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.

Convert tuple to list and back

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]]

log4j logging hierarchy order

[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.

Python - Check If Word Is In A String

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.

HTML5 Canvas: Zooming

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

Why does git revert complain about a missing -m option?

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

Iteration ng-repeat only X times in AngularJs

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.

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

Importing lodash into angular2 + typescript application

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.

Xcode build failure "Undefined symbols for architecture x86_64"

In my case problem was compiled framework architecture.
I'm running Xcode 11 and using Swift 5.1

  • I had 3 target like:
    • MyApp
    • MyAppTests
    • MyAppFrameWork

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.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

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 :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

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.

How to enumerate an enum with String type?

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()

Deep cloning objects

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();
}

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

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

  1. Some lists of useful resources (see sidebar bottom right) on
    • ical Spec RFC 5545
    • ical Testing Resources
  2. Some notes recorded on my journey working with .ics over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful.

.ics areas that need careful handling:

  • 'all day' events
  • types of dates (timezone, UTC, or local 'floating') - nb to understand distinction
  • interoperability of recurrence rules

HTML-encoding lost when attribute read from input field

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 = {
        '&'  : '&amp;',
        '"'  : '&quot;',
        '\'' : '&#39;',
        '<'  : '&lt;',
        '>'  : '&gt;',
        '\\' : '&#x2F;'
    };
    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 &lt;&gt;&amp;&quot;&#39;

CSS Progress Circle

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/

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

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 :

http://iconhandbook.co.uk/reference/chart/android/

comparing strings in vb

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

How to get current user, and how to use User class in MVC5?

In .Net MVC5 core 2.2, I use HttpContext.User.Identity.Name . It worked for me.

Undefined index with $_POST

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" ;

Search for one value in any column of any table inside a database

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.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

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.

When to use React setState callback

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.

Use '=' or LIKE to compare strings in SQL?

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.

How to read all rows from huge table?

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

How can I change all input values to uppercase using Jquery?

$('#id-submit').click(function () {
    $("input").val(function(i,val) {
        return val.toUpperCase();
    });
});

FIDDLE

ORA-28001: The password has expired

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.

What is the 'instanceof' operator used for in Java?

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

How do I include the string header?

Maybe this link will help you.

See: std::string documentation.

#include <string> is the most widely accepted.

set default schema for a sql query

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.

Add click event on div tag using javascript

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.

git with IntelliJ IDEA: Could not read from remote repository

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.

How to display svg icons(.svg files) in UI using React Component?

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>

Generate random 5 characters string

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);

How to reload page every 5 seconds?

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.

Add placeholder text inside UITextView in Swift?

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

HTML Code for text checkbox '?'

Use the Unicode Character

&#10004;   =   ✔


Using BigDecimal to work with currencies

NumberFormat.getNumberInstance(java.util.Locale.US).format(num);

How to upgrade R in ubuntu?

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

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. 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/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. 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).

Good examples using java.util.logging

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.

How to find a number in a string using JavaScript?

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.

How to print a string in C++

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.

Setting a windows batch file variable to the day of the week

@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.

Chain-calling parent initialisers in python

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"

Transport security has blocked a cleartext HTTP

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": {
   }
}

How to run function of parent window when child window closes?

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

How to destroy a JavaScript object?

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!

Javascript setInterval not working

Try this:

function funcName() {
    alert("test");
}

var run = setInterval(funcName, 10000)

When do I need a fb:app_id or fb:admins?

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.

Read response body in JAX-RS client from a post request

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!

How do I run Python code from Sublime Text 2?

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.

Detailed instructions for Linux or Windows

It is more efficient to use if-return-return or if-else-return?

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.

Image.open() cannot identify image file - Python?

In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

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}"/>

Creating a timer in python

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

Extracting specific selected columns to new DataFrame as a copy

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']]

Maven error: Not authorized, ReasonPhrase:Unauthorized

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.

How to randomly select an item from a list?

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([])

OS specific instructions in CMAKE: How to?

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.

How to install PHP intl extension in Ubuntu 14.04

sudo apt-get install php-intl

then restart your server

Multiple input in JOptionPane.showInputDialog

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());
      }
   }
}

Getting View's coordinates relative to the root layout

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);
    });

Read line with Scanner

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!

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

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

useRef

for useRef hook use like this

const value = inputRef?.current?.value

Android - how to replace part of a string by another string?

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.

Select n random rows from SQL Server table

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.

How to test if a double is an integer

My simple solution:

private boolean checkIfInt(double value){
 return value - Math.floor(value) == 0;
 }

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

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>.

Magento Product Attribute Get Value

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
    )

Why does AngularJS include an empty option in select?

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();
}

How do I "Add Existing Item" an entire directory structure in Visual Studio?

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(&quot;$(MSBuildProjectDirectory)\node_modules&quot;,&quot;*&quot;,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.

List of enum values in java

It is possible but you should use EnumSet instead

enum MyEnum {
    ONE, TWO;
    public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}

Adding a newline into a string in C#

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 + "@");
    }
}

How to print the values of slices

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
    }
}

Clear dropdown using jQuery Select2

You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items

$('#mySelect2').val(null).trigger('change');

Retrieving Data from SQL Using pyodbc

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!

How do I convert from stringstream to string in C++?

From memory, you call stringstream::str() to get the std::string value out.

How can two strings be concatenated?

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 = ", ")) 

Force SSL/https using .htaccess and mod_rewrite

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.

RecyclerView vs. ListView

In addition to above differences following are few more:

  1. 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.

  2. Switching between Grid and List is more easy now with LayoutManager.

  3. No need to notify and update all items, even if only single item is changed.

  4. 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.)

  5. Very easy item animations in case of RV.

How to check version of python modules?

Use pip show to find the version!

# in order to get package version execute the below command
pip show YOUR_PACKAGE_NAME | grep Version

How to solve the memory error in Python

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.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

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.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

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")

    }

}

Laravel 5 Application Key

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

How to hide keyboard in swift on pressing return key?

Swift

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.

Difference between break and continue statement

break leaves a loop, continue jumps to the next iteration.

Javascript Regexp dynamic generation from variables?

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);

What is a "static" function in C?

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.

Apache HttpClient Android (Gradle)

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.

How do I release memory used by a pandas dataframe?

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)

Understanding Spring @Autowired usage

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:

  1. Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard.
  2. Another good practice would be to put the @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.

Simplest way to have a configuration file in a Windows Forms C# application

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.

Overloading operators in typedef structs (c++)

  1. bool operator==(pos a) const{ - this method doesn't change object's elements.
  2. bool operator==(pos a) { - it may change object's elements.

Fatal error: iostream: No such file or directory in compiling C program using GCC

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)

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

Message is clear that 'Authorization' is not allowed in API. Set
Access-Control-Allow-Headers: "Content-Type, Authorization"

ASP.NET MVC 3 Razor - Adding class to EditorFor

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.

CSS class declaration:

.SpaceAvailableSearch input
{
    width:25px;
}

View code:

<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

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

How to check if a file exists in Go?

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
}

Checking if a file is a directory or just a file

Yes, there is better. Check the stat or the fstat function

JRE installation directory in Windows

Look the answer to my previous question here

c:\> for %i in (java.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\java.exe

increase legend font size ggplot2

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)))

How to reload / refresh model data from the server programmatically?

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.

How do I use .toLocaleTimeString() without displaying seconds?

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.

Oracle Convert Seconds to Hours:Minutes:Seconds

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;
/

How to skip a iteration/loop in while-loop

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

How do I use a C# Class Library in a project?

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

Spring cron expression for every after 30 minutes

If someone is using @Sceduled this might work for you.

@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")

This worked for me.

Find nearest latitude/longitude with an SQL query

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();
    }

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

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')

enter image description here

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)

enter image description here

Determine a string's encoding in C#

The code below has the following features:

  1. Detection or attempted detection of UTF-7, UTF-8/16/32 (bom, no bom, little & big endian)
  2. Falls back to the local default codepage if no Unicode encoding was found.
  3. Detects (with high probability) unicode files with the BOM/signature missing
  4. Searches for charset=xyz and encoding=xyz inside file to help determine encoding.
  5. To save processing, you can 'taste' the file (definable number of bytes).
  6. The encoding and decoded text file is returned.
  7. Purely byte-based solution for efficiency

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;
}

Using Python Requests: Sessions, Cookies, and POST

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

DataColumn Name from DataRow (not DataTable)

use DataTable object instead:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

How to add lines to end of file on Linux

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

How to write data with FileOutputStream without losing old data?

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);

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

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

How can I extract the folder path from file path in Python?

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

How to show empty data message in Datatables

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.

When should we use Observer and Observable?

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.

How can one run multiple versions of PHP 5.x on a development LAMP server?

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:

https://web.archive.org/web/20130707085630/http://linuxplayer.org/2011/05/intall-multiple-version-of-php-on-one-server

Based on CentOS 5.6, for Apache only

1. Enable rpmforge and epel yum repository

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

2. Install php-5.1

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

3. Compile and install php 5.2 and 5.3 from source

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

1) Install required dev packages

yum install gcc libxml2-devel bzip2-devel zlib-devel \
    curl-devel libmcrypt-devel libjpeg-devel \
    libpng-devel gd-devel mysql-devel

2) Compile and install

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

3) create a fastcgi wrapper script

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.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

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. */
    }

grid controls for ASP.NET MVC?

I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/

How to count the number of columns in a table using SQL?

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 can't access http://localhost/phpmyadmin/

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

Get a list of checked checkboxes in a div using jQuery

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;