Programs & Examples On #Gitignore

.gitignore is a file which lists files, directories and/or path patterns that Git should not include as part of a repository.

Why doesn't Git ignore my specified file?

I had the same problem. Files defined in .gitingore where listed as untracked files when running git status.

The reason was that the .gitignore file was saved in UTF-16LE encoding, and not in UTF8 encoding.

After changing the encoding of the .gitignore file to UTF8 it worked for me.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How can I stop .gitignore from appearing in the list of untracked files?

It is quite possible that an end user wants to have Git ignore the ".gitignore" file simply because the IDE specific folders created by Eclipse are probably not the same as NetBeans or another IDE. So to keep the source code IDE antagonistic it makes life easy to have a custom git ignore that isn't shared with the entire team as individual developers might be using different IDE's.

How do I ignore files in a directory in Git?

A leading slash indicates that the ignore entry is only to be valid with respect to the directory in which the .gitignore file resides. Specifying *.o would ignore all .o files in this directory and all subdirs, while /*.o would just ignore them in that dir, while again, /foo/*.o would only ignore them in /foo/*.o.

.gitignore and "The following untracked working tree files would be overwritten by checkout"

In order to save the modified files and to use the modified content later. I found this error while i try checking out a branch and when trying to rebase. Try Git stash

git stash

ignoring any 'bin' directory on a git project

for 2.13.3 and onwards,writing just bin in your .gitignore file should ignore the bin and all its subdirectories and files

bin

How to make Git "forget" about a file that was tracked but is now in .gitignore?

  1. Update your .gitignore file – for instance, add a folder you don't want to track to .gitignore.

  2. git rm -r --cached . – Remove all tracked files, including wanted and unwanted. Your code will be safe as long as you have saved locally.

  3. git add . – All files will be added back in, except those in .gitignore.


Hat tip to @AkiraYamamoto for pointing us in the right direction.

How to create a .gitignore file

To add any file in Xcode, go to the menu and navigate to menu FileNewFile...

For a .gitignore file choose OtherEmpty and click on Next. Type in the name (.gitignore) into the Save As field and click Create.

For files starting with a dot (".") a warning message will pop up, telling you that the file will be hidden. Just click on Use "." to proceed...

That's all.

To fill your brand new .gitignore you can find an example for ignoring Xcode file here: Git ignore file for Xcode projects

Is there an ignore command for git like there is for svn?

Create a file named .gitignore on the root of your repository. In this file you put the relative path to each file you wish to ignore in a single line. You can use the * wildcard.

Git Ignores and Maven targets

I ignore all classes residing in target folder from git. add following line in open .gitignore file:

/.class

OR

*/target/**

It is working perfectly for me. try it.

Apply .gitignore on an existing repository already tracking large number of files

  1. Create a .gitignore file, so to do that, you just create any blank .txt file.

  2. Then you have to change its name writing the following line on the cmd (where git.txt is the name of the file you've just created):

    rename git.txt .gitignore

  3. Then you can open the file and write all the untracked files you want to ignore for good. For example, mine looks like this:

```

OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

There's a whole collection of useful .gitignore files by GitHub

  1. Once you have this, you need to add it to your git repository just like any other file, only it has to be in the root of the repository.

  2. Then in your terminal you have to write the following line:

    git config --global core.excludesfile ~/.gitignore_global

From oficial doc:

You can also create a global .gitignore file, which is a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at ~/.gitignore_global and add some rules to it.

Open Terminal. Run the following command in your terminal: git config --global core.excludesfile ~/.gitignore_global

If the respository already exists then you have to run these commands:

git rm -r --cached .
git add .
git commit -m ".gitignore is now working"

If the step 2 doesn´t work then you should write the hole route of the files that you would like to add.

.gitignore all the .DS_Store files in every folder and subfolder

You should add following lines while creating a project. It will always ignore .DS_Store to be pushed to the repository.

*.DS_Store this will ignore .DS_Store while code commit.
git rm --cached .DS_Store this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.

## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store

gitignore all files of extension in directory

I have tried opening the .gitignore file in my vscode, windows 10. There you can see, some previously added ignore files (if any).

To create a new rule to ignore a file with (.js) extension, append the extension of the file like this:

*.js

This will ignore all .js files in your git repository.

To exclude certain type of file from a particular directory, you can add this:

**/foo/*.js

This will ignore all .js files inside only /foo/ directory.

For a detailed learning you can visit: about git-ignore

How to remove files that are listed in the .gitignore but still on the repository?

You can remove them from the repository manually:

git rm --cached file1 file2 dir/file3

Or, if you have a lot of files:

git rm --cached `git ls-files -i --exclude-from=.gitignore`

But this doesn't seem to work in Git Bash on Windows. It produces an error message. The following works better:

git ls-files -i --exclude-from=.gitignore | xargs git rm --cached  

Regarding rewriting the whole history without these files, I highly doubt there's an automatic way to do it.
And we all know that rewriting the history is bad, don't we? :)

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.

This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.

If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.

Gitignore not working

I solved my problem doing the following:

First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.

There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.

Here is a quick fix for that

Edit > EOL Conversion > Windows Format > Save

You can blame your text editor settings for that.

For example:

As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.

So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore


# See https://help.github.com/ignore-files/ for more about ignoring files.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

If i open the same file using the default Notepad, this is what i get

## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from  https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache 

So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.

The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following

Edit > EOL Conversion > Windows Format > Save

The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.

git: How to ignore all present untracked files?

If you want to permanently ignore these files, a simple way to add them to .gitignore is:

  1. Change to the root of the git tree.
  2. git ls-files --others --exclude-standard >> .gitignore

This will enumerate all files inside untracked directories, which may or may not be what you want.

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

Commit empty folder structure (with git)

Consider also just doing mkdir -p data/images in your Makefile, if the directory needs to be there during build.

If that's not good enough, just create an empty file in data/images and ignore data.

touch data/images/.gitignore
git add data/images/.gitignore
git commit -m "Add empty .gitignore to keep data/images around"
echo data >> .gitignore
git add .gitignore
git commit -m "Add data to .gitignore"

Add newly created specific folder to .gitignore in Git

Try /public_html/stats/* ?

But since the files in git status reported as to be commited that means you've already added them manually. In which case, of course, it's a bit too late to ignore. You can git rm --cache them (IIRC).

Make .gitignore ignore everything except a few files

I had a problem with subfolder.

Does not work:

/custom/*
!/custom/config/foo.yml.dist

Works:

/custom/config/*
!/custom/config/foo.yml.dist

.gitignore exclude folder but include specific subfolder

There are a bunch of similar questions about this, so I'll post what I wrote before:

The only way I got this to work on my machine was to do it this way:

# Ignore all directories, and all sub-directories, and it's contents:
*/*

#Now ignore all files in the current directory 
#(This fails to ignore files without a ".", for example 
#'file.txt' works, but 
#'file' doesn't):
*.*

#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*

Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.

This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153

These were useful topics:

I also tried

*
*/*
**/**

and **/wp-content/themes/**

or /wp-content/themes/**/*

None of that worked for me, either. Lots of trial and error!

What are the differences between .gitignore and .gitkeep?

This is not an answer to the original question "What are the differences between .gitignore and .gitkeep?" but posting here to help people to keep track of empty dir in a simple fashion. To track empty directory and knowling that .gitkeep is not official part of git,

enter image description here

just add a empty (with no content) .gitignore file in it.

So for e.g. if you have /project/content/posts and sometimes posts directory might be empty then create empty file /project/content/posts/.gitignore with no content to track that directory and its future files in git.

Ignoring directories in Git repositories on Windows

I had some issues creating a file in Windows Explorer with a . at the beginning.

A workaround was to go into the commandshell and create a new file using "edit".

Can't ignore UserInterfaceState.xcuserstate

All Answer is great but here is the one will remove for every user if you work in different Mac (Home and office)

git rm --cache */UserInterfaceState.xcuserstate
git commit -m "Never see you again, UserInterfaceState"

What to gitignore from the .idea folder?

Github uses the following .gitignore for their programs

https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

Global Git ignore

If you're using VSCODE, you can get this extension to handle the task for you. It watches your workspace each time you save your work and helps you to automatically ignore the files and folders you specified in your vscode settings.json ignoreit (vscode extension)

How to ignore certain files in Git

git reset filename
git rm --cached filename

then add your file which you want to ignore it,

then commit and push to your repository

git add only modified changes and ignore untracked files

Ideally your .gitignore should prevent the untracked ( and ignored )files from being shown in status, added using git add etc. So I would ask you to correct your .gitignore

You can do git add -u so that it will stage the modified and deleted files.

You can also do git commit -a to commit only the modified and deleted files.

Note that if you have Git of version before 2.0 and used git add ., then you would need to use git add -u . (See "Difference of “git add -A” and “git add .").

How to exclude file only from root folder in Git

Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]

/config.php
!/*/config.php

Later versions only require the following [tested on version 2.2.1]

/config.php

How do I ignore all files in a folder with a Git repository in Sourcetree?

Right click on a file → IgnoreIgnore everything beneath.

If the Ignore option is grayed out then:

  1. Stage a file first
  2. Right click → Stop Tracking
  3. That file will appear in the pane below with a question mark → Right click on it→ Ignore

Enter image description here

git ignore exception

This is how I do it, with a README.md file in each directory:

/data/*
!/data/README.md

!/data/input/
/data/input/*
!/data/input/README.md

!/data/output/
/data/output/*
!/data/output/README.md

.gitignore after commit

If you have not pushed the changes already:

git rm -r --cached .
git add .
git commit -m 'clear git cache'
git push

.gitignore is ignored by Git

There's some great answers already, but my situation was tedious. I'd edited source of an installed PLM (product lifecycle management) software on Win10 and afterward decided, "I probably should have made this a git repo."

So, the cache option won't work for me, directly. Posting for others who may have added source control AFTER doing a bunch of initial work AND .gitignore isn't working BUT, you might be scared to lose a bunch of work so git rm --cached isn't for you.

!IMPORTANT: This is really because I added git too late to a "project" that is too big and seems to ignore my .gitignore. I've NO commits, ever. I can git away with this :)

First, I just did:

rm -rf .git
rm -rf .gitignore

Then, I had to have a picture of my changes. Again, this is an install product that I've done changes on. Too late for a first commit of pure master branch. So, I needed a list of what I changed since I'd installed the program by adding > changed.log to either of the following:

PowerShell

# Get files modified since date.
Get-ChildItem -Path path\to\installed\software\ -Recurse -File | Where-Object -FilterScript {($_.LastWriteTime -gt '2020-02-25')} | Select-Object FullName

Bash

# Get files modified in the last 10 days...
find ./ -type f -mtime -10

Now, I have my list of what I changed in the last ten days (let's not get into best practices here other than to say, yes, I did this to myself).

For a fresh start, now:

git init .
# Create and edit .gitignore

I had to compare my changed list to my growing .gitignore, running git status as I improved it, but my edits in .gitignore are read-in as I go.

Finally, I've the list of desired changes! In my case it's boilerplate - some theme work along with sever xml configs specific to running a dev system against this software that I want to put in a repo for other devs to grab and contribute on... This will be our master branch, so committing, pushing, and, finally BRANCHING for new work!

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

How do I configure git to ignore some files locally?

You have several options:

  • Leave a dirty (or uncommitted) .gitignore file in your working dir (or apply it automatically using topgit or some other such patch tool).
  • Put the excludes in your $GIT_DIR/info/exclude file, if this is specific to one tree.
  • Run git config --global core.excludesfile ~/.gitignore and add patterns to your ~/.gitignore. This option applies if you want to ignore certain patterns across all trees. I use this for .pyc and .pyo files, for example.

Also, make sure you are using patterns and not explicitly enumerating files, when applicable.

git still shows files as modified after adding to .gitignore

Using git rm --cached *file* is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.

I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.

Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.

Anyway, all it requires is git update-index --assume-unchanged *path/to/file*.

As far as I understand, this is the most notable thing to keep in mind:

Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

Remove directory from remote repository after adding them to .gitignore

If you're working from PowerShell, try the following as a single command.

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

Then, git push --force --all.

Documentation: https://git-scm.com/docs/git-filter-branch

.gitignore for Visual Studio Projects and Solutions

As mentioned by another poster, Visual Studio generates this as a part of its .gitignore (at least for MVC 4):

# SQL Server files
App_Data/*.mdf
App_Data/*.ldf

Since your project may be a subfolder of your solution, and the .gitignore file is stored in the solution root, this actually won't touch the local database files (Git sees them at projectfolder/App_Data/*.mdf). To account for this, I changed those lines like so:

# SQL Server files
*App_Data/*.mdf
*App_Data/*.ldf

Best practices for adding .gitignore file for Python projects?

One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)

Git ignore file for Xcode projects

You should checkout gitignore.io for Objective-C and Swift.

Here is the .gitignore file I'm using:

# Xcode
.DS_Store
*/build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
*.hmap
*.xccheckout
*.xcworkspace
!default.xcworkspace

#CocoaPods
Pods

Should you commit .gitignore into the Git repos?

You typically do commit .gitignore. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status should show nothing.)

There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~ backup files, or another example would be the .DS_Store files created by OS X.

I'd say, if others are complaining about those rules cluttering up your .gitignore, leave them out and instead put them in a global excludes file.

By default this file resides in $XDG_CONFIG_HOME/git/ignore (defaults to ~/.config/git/ignore), but this location can be changed by setting the core.excludesfile option. For example:

git config --global core.excludesfile ~/.gitignore

Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

How can I Remove .DS_Store files from a Git repository?

create a .gitignore file using command touch .gitignore

and add the following lines in it

.DS_Store

save the .gitignore file and then push it in to your git repo.

Ignore .classpath and .project from Git

Add the below lines in .gitignore and place the file inside ur project folder

/target/
/.classpath
/*.project
/.settings
/*.springBeans

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

What should be in my .gitignore for an Android Studio project?

.gitignore from AndroidRate library

# Copyright 2017 - 2018 Vorlonsoft LLC
#
# Licensed under The MIT License (MIT)

# Built application files
*.ap_
*.apk

# Built library files
*.aar
*.jar

# Built native files
*.o
*.so

# Files for the Dalvik/Android Runtime (ART)
*.dex
*.odex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk/ndk path, etc)
local.properties

# Windows thumbnail cache
Thumbs.db

# macOS
.DS_Store/

# Log Files
*.log

# Android Studio
.navigation/
captures/
output.json

# NDK
.externalNativeBuild/
obj/

# IntelliJ
## User-specific stuff
.idea/**/tasks.xml
.idea/**/workspace.xml
.idea/dictionaries
## Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/dynamic.xml
.idea/**/sqlDataSources.xml
.idea/**/uiDesigner.xml
## Gradle
.idea/**/gradle.xml
.idea/**/libraries
## VCS
.idea/vcs.xml
## Module files
*.iml
## File-based project format
*.iws

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Where does the .gitignore file belong?

You can place .gitignore in any directory in git.

It's commonly used as a placeholder file in folders, since folders aren't usually tracked by git.

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

How to git ignore subfolders / subdirectories?

To ignore all subdirectories you can simply use:

**/

This works as of version 1.8.2 of git.

Ignore files that have already been committed to a Git repository

Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached from .gitignore:

cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached

Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files. That's just for the files which haven't been modified.

Accurate way to measure execution times of php scripts

Here is very simple and short method

<?php
$time_start = microtime(true);
//the loop begin
//some code
//the loop end
$time_end = microtime(true);
$total_time = $time_end - $time_start;
echo $total_time; // or whatever u want to do with the time
?>

Angular 2 Checkbox Two Way Data Binding

I'm working with Angular5 and I had to add the "name" attribute to get the binding to work... The "id" is not required for binding.

<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">

python: create list of tuples from lists

Use the builtin function zip():

In Python 3:

z = list(zip(x,y))

In Python 2:

z = zip(x,y)

Convert String (UTF-16) to UTF-8 in C#

does this example help ?

using System;
using System.IO;
using System.Text;

class Test
{
   public static void Main() 
   {        
    using (StreamWriter output = new StreamWriter("practice.txt")) 
    {
        // Create and write a string containing the symbol for Pi.
        string srcString = "Area = \u03A0r^2";

        // Convert the UTF-16 encoded source string to UTF-8 and ASCII.
        byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
        byte[] asciiString = Encoding.ASCII.GetBytes(srcString);

        // Write the UTF-8 and ASCII encoded byte arrays. 
        output.WriteLine("UTF-8  Bytes: {0}", BitConverter.ToString(utf8String));
        output.WriteLine("ASCII  Bytes: {0}", BitConverter.ToString(asciiString));


        // Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded  
        // string and write.
        output.WriteLine("UTF-8  Text : {0}", Encoding.UTF8.GetString(utf8String));
        output.WriteLine("ASCII  Text : {0}", Encoding.ASCII.GetString(asciiString));

        Console.WriteLine(Encoding.UTF8.GetString(utf8String));
        Console.WriteLine(Encoding.ASCII.GetString(asciiString));
    }
}

}

SQL Error: ORA-00913: too many values

You should specify column names as below. It's good practice and probably solve your problem

insert into abc.employees (col1,col2) 
select col1,col2 from employees where employee_id=100; 

EDIT:

As you said employees has 112 columns (sic!) try to run below select to compare both tables' columns

select * 
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME 
                               and  ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'

and than you should upgrade your tables to have the same structure.

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

redirected uri is the location where the user will be redirected after successfully login to your app. for example to get access token for your app in facebook you need to subimt redirected uri which is nothing only the app Domain that your provide when you create your facebook app.

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

How should I load files into my Java application?

I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

Unable to resolve host "<URL here>" No address associated with host name

Check permission for INTERNET in mainfest file and check network connectivity.

Send POST data on redirect with JavaScript/jQuery?

Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.

Android - Launcher Icon Size

Don't Create 9-patch images for launcher icons . You have to make separate image for each one.

LDPI - 36 x 36
MDPI - 48 x 48
HDPI - 72 x 72
XHDPI - 96 x 96
XXHDPI - 144 x 144
XXXHDPI - 192 x 192.
WEB - 512 x 512 (Require when upload application on Google Play)

Note: WEB(512 x 512) image is used when you upload your android application on Market.

|| Android App Icon Size ||

All Devices

hdpi=281*164
mdpi=188*110
xhdpi=375*219
xxhdpi=563*329
xxxhdpi=750*438

48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)

Angular JS Uncaught Error: [$injector:modulerr]

ok if you are getting a Uncaught Error: [$injector:modulerr] and the angular module is in the error that is telling you, you have an duplicate ng-app module.

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

How to run two jQuery animations simultaneously?

If you run the above as they are, they will appear to run simultaenously.

Here's some test code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function () {
    $('#first').animate({ width: 200 }, 200);
    $('#second').animate({ width: 600 }, 200);
});
</script>
<div id="first" style="border:1px solid black; height:50px; width:50px"></div>
<div id="second" style="border:1px solid black; height:50px; width:50px"></div>

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

Why is "except: pass" a bad programming practice?

First, it violates two principles of Zen of Python:

  • Explicit is better than implicit
  • Errors should never pass silently

What it means, is that you intentionally make your error pass silently. Moreover, you don't event know, which error exactly occurred, because except: pass will catch any exception.

Second, if we try to abstract away from the Zen of Python, and speak in term of just sanity, you should know, that using except:pass leaves you with no knowledge and control in your system. The rule of thumb is to raise an exception, if error happens, and take appropriate actions. If you don't know in advance, what actions these should be, at least log the error somewhere (and better re-raise the exception):

try:
    something
except:
    logger.exception('Something happened')

But, usually, if you try to catch any exception, you are probably doing something wrong!

Passing variables to the next middleware using next() in Express.js

This is what the res.locals object is for. Setting variables directly on the request object is not supported or documented. res.locals is guaranteed to hold state over the life of a request.

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use(function(req, res, next) {
    res.locals.user = req.user;  
    res.locals.authenticated = !req.user.anonymous;
    next();
});

To retrieve the variable in the next middleware:

app.use(function(req, res, next) {
    if (res.locals.authenticated) {
        console.log(res.locals.user.id);
    }
    next();
});

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

Select all DIV text with single mouse click

Easily achieved with the css property user-select set to all. Like this:

_x000D_
_x000D_
div.anyClass {_x000D_
  user-select: all;_x000D_
}
_x000D_
_x000D_
_x000D_

How to edit binary file on Unix systems

I like KHexEdit, which is part of KDE

Its "Windows style" UI is probably quite quick to learn for most people (compared to Vim or Emacs anyway :)

Is there a standardized method to swap two variables in Python?

Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

How can I create a copy of an Oracle table without copying the data?

In other way you can get ddl of table creation from command listed below, and execute the creation.

SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL 
  • TYPE is TABLE,PROCEDURE etc.

With this command you can get majority of ddl from database objects.

How can I hide an HTML table row <tr> so that it takes up no space?

var result_style = document.getElementById('result_tr').style;
result_style.display = '';

is working perfectly for me..

How to split a large text file into smaller files with equal number of lines?

Use:

sed -n '1,100p' filename > output.txt

Here, 1 and 100 are the line numbers which you will capture in output.txt.

Efficient iteration with index in Scala

A simple and efficient way, inspired from the implementation of transform in SeqLike.scala

    var i = 0
    xs foreach { el =>
      println("String #" + i + " is " + xs(i))
      i += 1
    }

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

set the width of select2 input (through Angular-ui directive)

add method container css in your script like this :

$("#your_select_id").select2({
      containerCss : {"display":"block"}
});

it will set your select's width same as width your div.

Parsing GET request parameters in a URL that contains another URL

$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);

$my_url outputs:

http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234

So now you can get this value using $_GET['id'] or $_REQUEST['id'] (decoded).

echo urldecode($_GET["id"]);

Output

http://google.com/?var=234&key=234

To get every GET parameter:

foreach ($_GET as $key=>$value) {
  echo "$key = " . urldecode($value) . "<br />\n";
  }

$key is GET key and $value is GET value for $key.

Or you can use alternative solution to get array of GET params

$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
  $pairs = explode('&', $_SERVER['QUERY_STRING']);
  foreach($pairs as $pair) {
    $part = explode('=', $pair);
    $get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
    }
  }

$get_parameters is same as url decoded $_GET.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

How do I detect IE 8 with jQuery?

You can use $.browser to detect the browser name. possible values are :

  • webkit (as of jQuery 1.4)
  • safari (deprecated)
  • opera
  • msie
  • mozilla

or get a boolean flag: $.browser.msie will be true if the browser is MSIE.

as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.

Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.

php stdClass to array

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);

UIImage resize (Scale proportion)

This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.

- (UIImage *) scaleProportionalToSize: (CGSize)size
{
    float widthRatio = size.width/self.size.width;
    float heightRatio = size.height/self.size.height;

    if(widthRatio > heightRatio)
    {
        size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
    } else {
        size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
    }

    return [self scaleToSize:size];
}

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

JavaScript checking for null vs. undefined and difference between == and ===

The difference is subtle.

In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.

But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).

Example:

var a;
typeof a;     # => "undefined"

a = null;
typeof null;  # => "object"

This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.

As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.

You may use those operators to check between undefined an null. For example:

null === null            # => true
undefined === undefined  # => true
undefined === null       # => false
undefined == null        # => true

The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is @Ben's answer updated for use with Ember...note you have to use Ember.get because context is passed in as a String.

Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
  var ret = "";
  var newContext = Ember.get(this, context);
  for(var prop in newContext)
  {
    if (newContext.hasOwnProperty(prop)) {
      ret = ret + options.fn({property:prop,value:newContext[prop]});
    }
  }
  return ret;
});

Template:

{{#eachProperty object}}
  {{key}}: {{value}}<br/>
{{/eachProperty }}

Selecting option by text content with jQuery

Replace this:

var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
    $(this).select(); // This is where my problem is
});

With this:

$('#cbCategory').val(cat);

Calling val() on a select list will automatically select the option with that value, if any.

difference between throw and throw new Exception()

Your second example will reset the exception's stack trace. The first most accurately preserves the origins of the exception. Also you've unwrapped the original type which is key in knowing what actually went wrong... If the second is required for functionality - e.g. To add extended info or re-wrap with special type such as a custom 'HandleableException' then just be sure that the InnerException property is set too!

MySql difference between two timestamps in days?

If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.

SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
|   17 |
+------+

How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

Does Spring Data JPA have any way to count entites using method name resolving?

JpaRepository also extends QueryByExampleExecutor. So you don't even need to define custom methods on your interface:

public interface UserRepository extends JpaRepository<User, Long> {
    // no need of custom method
}

And then query like:

User probe = new User();
u.setName = "John";
long count = repo.count(Example.of(probe));

Disable Input fields in reactive form

this.form.enable()
this.form.disable()

Or formcontrol 'first'

this.form.get('first').enable()
this.form.get('first').disable()

You can set disable or enable on initial set.

 first: new FormControl({disabled: true}, Validators.required)

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

For me none of above worked. However, I solved problem with installing libssl-dev.

sudo apt-get install libssl-dev

This might work if you have same error message as in my case:

fatal error: openssl/opensslv.h: No such file or directory ... .... command 'x86_64-linux-gnu-gcc' failed with exit status 1

Android Image View Pinch Zooming

Add bellow line in build.gradle:

compile 'com.commit451:PhotoView:1.2.4'

or

compile 'com.github.chrisbanes:PhotoView:1.3.0'

In Java file:

PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();

Git Cherry-pick vs Merge Workflow

Both rebase (and cherry-pick) and merge have their advantages and disadvantages. I argue for merge here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase is preferred.)

merge is preferred over cherry-pick and rebase for a couple of reasons.

  1. Robustness. The SHA1 identifier of a commit identifies it not just in and of itself but also in relation to all other commits that precede it. This offers you a guarantee that the state of the repository at a given SHA1 is identical across all clones. There is (in theory) no chance that someone has done what looks like the same change but is actually corrupting or hijacking your repository. You can cherry-pick in individual changes and they are likely the same, but you have no guarantee. (As a minor secondary issue the new cherry-picked commits will take up extra space if someone else cherry-picks in the same commit again, as they will both be present in the history even if your working copies end up being identical.)
  2. Ease of use. People tend to understand the merge workflow fairly easily. rebase tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.

Even with a merge-heavy workflow rebase and cherry-pick are still useful for particular cases:

  1. One downside to merge is cluttered history. rebase prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase code that you have shared with other repositories. Once a commit is pushed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.
  2. cherry-pick is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.

As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.

Round float to x decimals?

The Mark Dickinson answer, although complete, didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)

Hope this helps anyone.

Understanding Linux /proc/id/maps

Please check: http://man7.org/linux/man-pages/man5/proc.5.html

address           perms offset  dev   inode       pathname
00400000-00452000 r-xp 00000000 08:02 173521      /usr/bin/dbus-daemon

The address field is the address space in the process that the mapping occupies.

The perms field is a set of permissions:

 r = read
 w = write
 x = execute
 s = shared
 p = private (copy on write)

The offset field is the offset into the file/whatever;

dev is the device (major:minor);

inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).

The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).

Under Linux 2.0, there is no field giving pathname.

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

Java collections convert a string to a list of characters

In Java8 you can use streams I suppose. List of Character objects:

List<Character> chars = str.chars()
    .mapToObj(e->(char)e).collect(Collectors.toList());

And set could be obtained in a similar way:

Set<Character> charsSet = str.chars()
    .mapToObj(e->(char)e).collect(Collectors.toSet());

Python sys.argv lists and indexes

So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?

import sys
def main():
  if len(sys.argv) >= 2:
    fname = sys.argv[1]
    lname = sys.argv[2]
  else:
    name = 'World'
  print 'Hello', fname, lname
if __name__ == '__main__':
  main()

Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?

Edit 2: Got it figured out:

import sys
def main():
  if len(sys.argv) >= 2:
    name = sys.argv[1] + " " + sys.argv[2]
  else:
    name = 'World'
  print 'Hello', name
if __name__ == '__main__':
  main()

Automatically create requirements.txt

if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.

T-SQL query to show table definition?

There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')

Could not resolve '...' from state ''

I've just had this same issue with Ionic.

It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.

After going back into the app, my states worked fine.

I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.

Comparing two dataframes and getting the differences

Since pandas >= 1.1.0 we have DataFrame.compare and Series.compare.

Note: the method can only compare identically-labeled DataFrame objects, this means DataFrames with identical row and column labels.

df1 = pd.DataFrame({'A': [1, 2, 3],
                    'B': [4, 5, 6],
                    'C': [7, np.NaN, 9]})

df2 = pd.DataFrame({'A': [1, 99, 3],
                    'B': [4, 5, 81],
                    'C': [7, 8, 9]})

   A  B    C
0  1  4  7.0
1  2  5  NaN
2  3  6  9.0 

    A   B  C
0   1   4  7
1  99   5  8
2   3  81  9
df1.compare(df2)

     A          B          C      
  self other self other self other
1  2.0  99.0  NaN   NaN  NaN   8.0
2  NaN   NaN  6.0  81.0  NaN   NaN

How do I 'git diff' on a certain directory?

To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:

In a Folder Compare ViewRules (Referee Icon):

Enter image description here

And then, enable follow symbolic links and update session defaults:

Enter image description here


OR,

set up the alias like so:

git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"

Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.

How to increase font size in the Xcode editor?

For Xcode 12: (beta 3)

For the code editing windows, use the new

Editor -> Font Size -> Increase

or

Editor -> Font Size -> Decrease

menu items. This globally increases or decreases the font sizes for all editing windows. There is also an

Editor -> Font Size -> Reset

option. These also respond to the ?+ or ?- keyboard shortcuts.

By default, the file navigator on the left side corresponds to the

System Preferences -> General -> Sidebar icon size

You can also override the system size inside Xcode using the

Xcode -> Preferences -> General -> Navigator Size

Get selected value/text from Select on change

jquery

    $('#select_id').change(function(){
    // selected value 
    alert($(this).val());
    // selected text 
    alert($(this).find("option:selected").text());
})

html

<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

2D character array initialization in C

char **options[2][100];

declares a size-2 array of size-100 arrays of pointers to pointers to char. You'll want to remove one *. You'll also want to put your string literals in double quotes.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

Its not necessary to apply above solutions, I simply changed my internet, it was working fine with my home internet but after 3 to 4 hours my friend suggest me to connect with different internet then I did data package and connect my laptop with it, now it is working fine.

Rolling or sliding window iterator?

I tested a few solutions and one I came up with and found the one I came up with to be the fastest so I thought I would share it.

import itertools
import sys

def windowed(l, stride):
    return zip(*[itertools.islice(l, i, sys.maxsize) for i in range(stride)])

return error message with actionResult

IN your view insert

@Html.ValidationMessage("Error")

then in the controller after you use new in your model

var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}

How to add jQuery code into HTML Page

for latest Jquery. Simply:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

I faced similar issue after upgrading to java 12, for me the solution was to update jacoco version <jacoco.version>0.8.3</jacoco.version>

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

SQL Server 2008: how do I grant privileges to a username?

If you want to give your user all read permissions, you could use:

EXEC sp_addrolemember N'db_datareader', N'your-user-name'

That adds the default db_datareader role (read permission on all tables) to that user.

There's also a db_datawriter role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:

EXEC sp_addrolemember N'db_datawriter', N'your-user-name'

If you need to be more granular, you can use the GRANT command:

GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName

and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.

This is all very well documented in the MSDN Books Online for SQL Server.

And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users, right-click on that user you want to give permissions to, then Properties adn at the bottom you see "Database role memberships" where you can add the user to db roles.

alt text

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

break/exit script

Here:

if(n < 500)
{
    # quit()
    # or 
    # stop("this is some message")
}
else
{
    *insert rest of program here*
}

Both quit() and stop(message) will quit your script. If you are sourcing your script from the R command prompt, then quit() will exit from R as well.

In PHP how can you clear a WSDL cache?

Edit your php.ini file, search for soap.wsdl_cache_enabled and set the value to 0

[soap]
; Enables or disables WSDL caching feature.
; http://php.net/soap.wsdl-cache-enabled
soap.wsdl_cache_enabled=0

Python: Fetch first 10 results from a list

Use the slicing operator:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]

Change image in HTML page every few seconds

You can load the images at the beginning and change the css attributes to show every image.

var images = array();
for( url in your_urls_array ){
   var img = document.createElement( "img" );
   //here the image attributes ( width, height, position, etc )
   images.push( img );
}

function player( position )
{
  images[position-1].style.display = "none" //be careful working with the first position
  images[position].style.display = "block";
  //reset position if needed
  timer = setTimeOut( "player( position )", time );
}

SQL Query for Selecting Multiple Records

You want to add the IN() clause to your WHERE

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)

If you have a list of Ids stored in a table you can also do this:

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (SELECT Id FROM table)

Class name does not name a type in C++

The preprocessor inserts the contents of the files A.h and B.h exactly where the include statement occurs (this is really just copy/paste). When the compiler then parses A.cpp, it finds the declaration of class A before it knows about class B. This causes the error you see. There are two ways to solve this:

  1. Include B.h in A.h. It is generally a good idea to include header files in the files where they are needed. If you rely on indirect inclusion though another header, or a special order of includes in the compilation unit (cpp-file), this will only confuse you and others as the project gets bigger.
  2. If you use member variable of type B in class A, the compiler needs to know the exact and complete declaration of B, because it needs to create the memory-layout for A. If, on the other hand, you were using a pointer or reference to B, then a forward declaration would suffice, because the memory the compiler needs to reserve for a pointer or reference is independent of the class definition. This would look like this:

    class B; // forward declaration        
    class A {
    public:
        A(int id);
    private:
        int _id;
        B & _b;
    };
    

    This is very useful to avoid circular dependencies among headers.

I hope this helps.

Getting the folder name from a path

I used this code snippet to get the directory for a path when no filename is in the path:

for example "c:\tmp\test\visual";

string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));

Output:

visual

"make clean" results in "No rule to make target `clean'"

Check that the file is called GNUMakefile, makefile or Makefile.

If it is called anything else (and you don't want to rename it) then try:

make -f othermakefilename clean

Practical uses for the "internal" keyword in C#

As rule-of-thumb there are two kinds of members:

  • public surface: visible from an external assembly (public, protected, and internal protected): caller is not trusted, so parameter validation, method documentation, etc. is needed.
  • private surface: not visible from an external assembly (private and internal, or internal classes): caller is generally trusted, so parameter validation, method documentation, etc. may be omitted.

How to add property to a class dynamically?

For those coming from search engines, here are the two things I was looking for when talking about dynamic properties:

class Foo:
    def __init__(self):
        # we can dynamically have access to the properties dict using __dict__
        self.__dict__['foo'] = 'bar'

assert Foo().foo == 'bar'


# or we can use __getattr__ and __setattr__ to execute code on set/get
class Bar:
    def __init__(self):
        self._data = {}
    def __getattr__(self, key):
        return self._data[key]
    def __setattr__(self, key, value):
        self._data[key] = value

bar = Bar()
bar.foo = 'bar'
assert bar.foo == 'bar'

__dict__ is good if you want to put dynamically created properties. __getattr__ is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).

If you only want one dynamic property, have a look at the property() built-in function.

Bind class toggle to window scroll event

Directives are not "inside the angular world" as they say. So you have to use apply to get back into it when changing stuff

how to convert string into time format and add two hours

You can use SimpleDateFormat to convert the String to Date. And after that you have two options,

  • Make a Calendar object and and then use that to add two hours, or
  • get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05"); 
    Calendar gc = new GregorianCalendar();
    gc.setTime(d);
    gc.add(Calendar.HOUR, 2);
    Date d2 = gc.getTime();
    

    Or,

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05");
    Long time = d.getTime();
    time +=(2*60*60*1000);
    Date d2 = new Date(time);
    

Have a look to these tutorials.

Which is faster: Stack allocation or Heap allocation

I don't think stack allocation and heap allocation are generally interchangable. I also hope that the performance of both of them is sufficient for general use.

I'd strongly recommend for small items, whichever one is more suitable to the scope of the allocation. For large items, the heap is probably necessary.

On 32-bit operating systems that have multiple threads, stack is often rather limited (albeit typically to at least a few mb), because the address space needs to be carved up and sooner or later one thread stack will run into another. On single threaded systems (Linux glibc single threaded anyway) the limitation is much less because the stack can just grow and grow.

On 64-bit operating systems there is enough address space to make thread stacks quite large.

How to pass prepareForSegue: an object

I used this solution so that I could keep the invocation of the segue and the data communication within the same function:

private var segueCompletion : ((UIStoryboardSegue, Any?) -> Void)?

func performSegue(withIdentifier identifier: String, sender: Any?, completion: @escaping (UIStoryboardSegue, Any?) -> Void) {
    self.segueCompletion = completion;
    self.performSegue(withIdentifier: identifier, sender: sender);
    self.segueCompletion = nil
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.segueCompletion?(segue, sender)
}

A use case would be something like:

func showData(id : Int){
    someService.loadSomeData(id: id) {
        data in
        self.performSegue(withIdentifier: "showData", sender: self) {
            storyboard, sender in
            let dataView = storyboard.destination as! DataView
            dataView.data = data
        }
    }
}

This seems to work for me, however, I'm not 100% sure that the perform and prepare functions are always executed on the same thread.

How to kill all active and inactive oracle sessions for user

BEGIN
  FOR r IN (select sid,serial# from v$session where username='user')
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid  || ',' || r.serial# || '''';
  END LOOP;
END;
/

It works for me.

Centering image and text in R Markdown for a PDF report

none of the answers worked but this

\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}

but then the following problem is that it works for only one figure and then will not for any other figures.

I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.

what's the differences between r and rb in fopen

This makes a difference on Windows, at least. See that link for details.

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

How to pass integer from one Activity to another?

In Sender Activity Side:

Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);

In Receiver Activity Side:

int receiveValue = getIntent().getIntExtra("value", 0);

Highlight the difference between two strings in PHP

There is also a PECL extension for xdiff:

In particular:

Example from PHP Manual:

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_POST['article'];

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

Formatting Decimal places in R

You can try my package formattable.

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> x <- formattable(1.128347132904321674821, digits = 2, format = "f")
> x
[1] 1.13

The good thing is, x is still a numeric vector and you can do more calculations with the same formatting.

> x + 1
[1] 2.13

Even better, the digits are not lost, you can reformat with more digits any time :)

> formattable(x, digits = 6, format = "f")
[1] 1.128347

Get all files and directories in specific path fast

In .NET 4.0 there's the Directory.EnumerateFiles method which returns an IEnumerable<string> and is not loading all the files in memory. It's only once you start iterating over the returned collection that files will be returned and exceptions could be handled.

How can one print a size_t variable portably using the printf family?

As AraK said, the c++ streams interface will always work portably.

std::size_t s = 1024; std::cout << s; // or any other kind of stream like stringstream!

If you want C stdio, there is no portable answer to this for certain cases of "portable." And it gets ugly since as you've seen, picking the wrong format flags may yield a compiler warning or give incorrect output.

C99 tried to solve this problem with inttypes.h formats like "%"PRIdMAX"\n". But just as with "%zu", not everyone supports c99 (like MSVS prior to 2013). There are "msinttypes.h" files floating around to deal with this.

If you cast to a different type, depending on flags you may get a compiler warning for truncation or a change of sign. If you go this route pick a larger relevant fixed size type. One of unsigned long long and "%llu" or unsigned long "%lu" should work, but llu may also slow things down in a 32bit world as excessively large. (Edit - my mac issues a warning in 64 bit for %llu not matching size_t, even though %lu, %llu, and size_t are all the same size. And %lu and %llu are not the same size on my MSVS2012. So you may need to cast + use a format that matches.)

For that matter, you can go with fixed size types, such as int64_t. But wait! Now we're back to c99/c++11, and older MSVS fails again. Plus you also have casts (e.g. map.size() is not a fixed size type)!

You can use a 3rd party header or library such as boost. If you're not already using one, you may not want to inflate your project that way. If you're willing to add one just for this issue, why not use c++ streams, or conditional compilation?

So you're down to c++ streams, conditional compilation, 3rd party frameworks, or something sort of portable that happens to work for you.

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

How to use bluetooth to connect two iPhone?

We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

Get the IP Address of local computer

Can't you just send to INADDR_BROADCAST? Admittedly, that'll send on all interfaces - but that's rarely a problem.

Otherwise, ioctl and SIOCGIFBRDADDR should get you the address on *nix, and WSAioctl and SIO_GET_BROADCAST_ADDRESS on win32.

Do you use source control for your database items?

If your Database is SQL Server, we might have just the solution you're looking for. SQL Source Control 1.0 has now been released.

http://www.red-gate.com/products/SQL_Source_Control/index.htm

This integrates into SSMS and provides the glue between your database objects and your VCS. The 'scripting out' happens transparently (it uses the SQL Compare engine under the hood), which should make it so straightforward to use that developers won't be discouraged from adopting the process.

An alternative Visual Studio solution is ReadyRoll, which is implemented as a sub-type of the SSDT Database Project. This takes a migrations-driven approach, which is more suited to the automation requirements of DevOps teams.

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

TypeError: $(...).DataTable is not a function

This worked for me. But make sure to load the jquery.js before the preferred dataTable.js file. Cheers!

<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/data-table/jquery.dataTables.js"></script>

 <script>$(document).ready(function () {
    $.noConflict();
    var table = $('# your selector').DataTable();
});</script>

Wait for all promises to resolve

Recently had this problem but with unkown number of promises.Solved using jQuery.map().

function methodThatChainsPromises(args) {

    //var args = [
    //    'myArg1',
    //    'myArg2',
    //    'myArg3',
    //];

    var deferred = $q.defer();
    var chain = args.map(methodThatTakeArgAndReturnsPromise);

    $q.all(chain)
    .then(function () {
        $log.debug('All promises have been resolved.');
        deferred.resolve();
    })
    .catch(function () {
        $log.debug('One or more promises failed.');
        deferred.reject();
    });

    return deferred.promise;
}

How to search if dictionary value contains certain string with Python

You can do it like this:

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was having the same error message for a mistake I made: Make sure you use a correct s3 uri such as: s3://my-bucket-name/

(If my-bucket-name is at the root of your aws s3 obviously)

I insist on that because when copy pasting the s3 bucket from your browser you get something like https://s3.console.aws.amazon.com/s3/buckets/my-bucket-name/?region=my-aws-regiontab=overview

Thus I made the mistake to use s3://buckets/my-bucket-name which raises:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

How to lock orientation of one view controller to portrait mode only in Swift

To set Landscape orientation to all view of your app & allow only one view to All orientations (to be able to add camera roll for example):

In AppDelegate.swift:

var adaptOrientation = false

In: didFinishLaunchingWithOptions

NSNotificationCenter.defaultCenter().addObserver(self, selector: "adaptOrientationAction:", name:"adaptOrientationAction", object: nil)

Elsewhere in AppDelegate.swift:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    return checkOrientation(self.window?.rootViewController)
}

func checkOrientation(viewController:UIViewController?)-> Int{
    if (adaptOrientation == false){
        return Int(UIInterfaceOrientationMask.Landscape.rawValue)
    }else {
        return Int(UIInterfaceOrientationMask.All.rawValue)
    }
}

func adaptOrientationAction(notification: NSNotification){
    if adaptOrientation == false {
        adaptOrientation = true
    }else {
        adaptOrientation = false
    }
}

Then in the view that segue to the one you want to be able to have All orientations:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "YOURSEGUE") {
        NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
    }
}

override func viewWillAppear(animated: Bool) {
    if adaptOrientation == true {
        NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
    }
}

Last thing is to tick Device orientation: - Portrait - Landscape Left - Landscape Right

vbscript output to console

This was found on Dragon-IT Scripts and Code Repository.

You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

Flutter : Vertically center column

CrossAlignment.center is using the Width of the 'Child Widget' to center itself and hence gets rendered at the start of the page.

When the Column is centered within the page body's 'Center Container' , the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page

enter image description here

Code

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
    title:"DynamicWidgetApp",
    home:DynamicWidgetApp(),

));

class DynamicWidgetApp extends StatefulWidget{
  @override
  DynamicWidgetAppState createState() => DynamicWidgetAppState();
  }

class  DynamicWidgetAppState extends State<DynamicWidgetApp>{
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
     //Removing body:Center will change the reference
    // and render the widget at the start of the page 
        child: Column(
            mainAxisAlignment : MainAxisAlignment.center,
            crossAxisAlignment : CrossAxisAlignment.center,
            children: [
              Text("My Centered Widget"),
            ]
          ),
      ),
      floatingActionButton: FloatingActionButton(
        // onPressed: ,
        child : Icon(Icons.add),
      ),
      );
    }
  }

Relative Paths in Javascript in an external file

Good question.

  • When in a CSS file, URLs will be relative to the CSS file.

  • When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).

There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:

<script type="text/javascript">

  directory_root = "http://www.example.com/resources";

</script> 

and to reference that root whenever you assign URLs dynamically.

ng-repeat: access key and value for each object in array of objects

In fact, your data is not well design. You'd better use something like :

$scope.steps = [
    {stepName: "companyName", isComplete: true},
    {stepName: "businessType", isComplete: true},
    {stepName: "physicalAddress", isComplete: true}
];

Then it is easy to do what you want :

<div ng-repeat="step in steps">
 Step {{step.stepName}} status : {{step.isComplet}}
</div>

Example: http://jsfiddle.net/rX7ba/

Java 8: Lambda-Streams, Filter by Method with Exception

If you don't mind using 3rd party libraries, AOL's cyclops-react lib, disclosure::I am a contributor, has a ExceptionSoftener class that can help here.

 s.filter(softenPredicate(a->a.isActive()));

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

Please to solve this problem we just have set installed JDK path in

standalone.conf

file which under the bin folder of JBoss\Wildfly Server. To solve this we do the following steps:

  1. Open the standlone.conf file which under JBoss_or_wildfly\bin folder
  2. Within this file find for #JAVA_HOME text.
  3. Remove the # character and set your installed JDK path as JAVA_HOME="C:\Program Files\Java\jdk1.8.0_65" Hope this will solve your problem Thanks

Change Bootstrap tooltip color

Seems to have changed in Bootstrap 4

If you want to change color of a bottom placed tooltip in red, just add this to your CSS :

.tooltip-inner {
    background-color: #f00;
}

.bs-tooltip-bottom .arrow::before {
    border-bottom-color: #f00;
}

get the value of DisplayName attribute

If instead

[DisplayName("Something To Name")]

you use

[Display(Name = "Something To Name")]

Just do this:

private string GetDisplayName(Class1 class1)
{
    string displayName = string.Empty;

    string propertyName = class1.Name.GetType().Name;

    CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");

    if (displayAttribute != null)
    {
        displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
    }

    return displayName;
}

Does Python have an ordered set?

An ordered set is functionally a special case of an ordered dictionary.

The keys of a dictionary are unique. Thus, if one disregards the values in an ordered dictionary (e.g. by assigning them None), then one has essentially an ordered set.

As of Python 3.1 and 2.7 there is collections.OrderedDict. The following is an example implementation of an OrderedSet. (Note that only few methods need to be defined or overridden: collections.OrderedDict and collections.MutableSet do the heavy lifting.)

import collections

class OrderedSet(collections.OrderedDict, collections.MutableSet):

    def update(self, *args, **kwargs):
        if kwargs:
            raise TypeError("update() takes no keyword arguments")

        for s in args:
            for e in s:
                 self.add(e)

    def add(self, elem):
        self[elem] = None

    def discard(self, elem):
        self.pop(elem, None)

    def __le__(self, other):
        return all(e in other for e in self)

    def __lt__(self, other):
        return self <= other and self != other

    def __ge__(self, other):
        return all(e in self for e in other)

    def __gt__(self, other):
        return self >= other and self != other

    def __repr__(self):
        return 'OrderedSet([%s])' % (', '.join(map(repr, self.keys())))

    def __str__(self):
        return '{%s}' % (', '.join(map(repr, self.keys())))
    
    difference = __sub__ 
    difference_update = __isub__
    intersection = __and__
    intersection_update = __iand__
    issubset = __le__
    issuperset = __ge__
    symmetric_difference = __xor__
    symmetric_difference_update = __ixor__
    union = __or__

How to check if a function exists on a SQL database

I tend to use the Information_Schema:

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'FUNCTION' ) 

for functions, and change Routine_Type for stored procedures

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'PROCEDURE' ) 

hadoop No FileSystem for scheme: file

I also came across similar issue. Added core-site.xml and hdfs-site.xml as resources of conf (object)

Configuration conf = new Configuration(true);    
conf.addResource(new Path("<path to>/core-site.xml"));
conf.addResource(new Path("<path to>/hdfs-site.xml"));

Also edited version conflicts in pom.xml. (e.g. If configured version of hadoop is 2.8.1, but in pom.xml file, dependancies has version 2.7.1, then change that to 2.8.1) Run Maven install again.

This solved error for me.

Port 80 is being used by SYSTEM (PID 4), what is that?

I just got this problem today, since it showed up after Norton requested reboot I blamed Norton.
But it wasn't Norton, I removed Norton, rebooted -> problem still there.

netstat -nao was showing that PID 4 owned my port 80 connection.

I then went to control panel, then "Turn Windows features on or off" then unchecked Internet Information Services.
Rebooted, the problem went away.
My xampp server is running ok now.

I don't ever remembering turning IIS on in the first place. I had been running many months before this happened. I still don't know what caused it in the first place. Maybe a previous windows updated enabled iis and my reboot turned it on, I don't know.

How to use Redirect in the new react-router-dom of Reactjs

Simply call it inside any function you like.

this.props.history.push('/main');

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

this worked for me on iis8 together with some of the other answers. My error was a 404.6 specifically

<system.webServer>
  <security>
  <requestFiltering>
    <verbs applyToWebDAV="false">
       <add verb="DELETE" allowed="true" />
    </verbs>
  </requestFiltering>
  </security>
</system.webServer>

Benefits of inline functions in C++?

Inlining is a suggestion to the compiler which it is free to ignore. It's ideal for small bits of code.

If your function is inlined, it's basically inserted in the code where the function call is made to it, rather than actually calling a separate function. This can assist with speed as you don't have to do the actual call.

It also assists CPUs with pipelining as they don't have to reload the pipeline with new instructions caused by a call.

The only disadvantage is possible increased binary size but, as long as the functions are small, this won't matter too much.

I tend to leave these sorts of decisions to the compilers nowadays (well, the smart ones anyway). The people who wrote them tend to have far more detailed knowledge of the underlying architectures.

JavaScript: remove event listener

If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.

clickHandler = function(event){
  if (click++ == 49)
    canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);

How do I search for an object by its ObjectId in the mongo console?

I just had this issue and was doing exactly as was documented and it still was not working.

Look at your error message and make sure you do not have any special characters copied in. I was getting the error

SyntaxError: illegal character @(shell):1:43

When I went to character 43 it was just the start of my object ID, after the open quotes, exactly as I pasted it in. I put my cursor there and hit backspace nothing appeared to happen when it should have removed the open quote. I hit backspace again and it removed the open quote, then I put the quote back in and executed the query and it worked, despite looking exactly the same.

I was doing development in WebMatrix and copied the object id from the console. Whenever you copy from the console in WebMatrix you're likely to pick up some invisible characters that will cause errors.

How to get the last row of an Oracle a table

The last row according to a strict total order over composite key K(k1, ..., kn):

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

Given the special case where K is simple (i.e. not composite), the above is shortened to:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

Note that for this query to return just one row the key must order without ties. If ties are allowed, this query will return all the rows tied with the greatest key.

How to trigger button click in MVC 4

ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.

Instead, you need to wrap that form in code something like this:

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
    <!-- form goes here -->

    <input type="submit" value="Sign Up" />
}

This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp() method, assuming your routes are properly set up (the defaults should work).

Youtube - downloading a playlist - youtube-dl

The easiest thing to do is to create a file.txt file and pass the link url link so:

https://www.youtube.com/watch?v=5Lj1BF0Kn8c&list=PL9YFoJnn53xyf9GNZrtiraspAIKc80s1i

make sure to include the -a parameter in terminal:

youtube-dl -a file.txt

Multiple IF AND statements excel

With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs

=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))

although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))

To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula

=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))

Is it better to use std::memcpy() or std::copy() in terms to performance?

In theory, memcpy might have a slight, imperceptible, infinitesimal, performance advantage, only because it doesn't have the same requirements as std::copy. From the man page of memcpy:

To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).

In other words, memcpy can ignore the possibility of overlapping data. (Passing overlapping arrays to memcpy is undefined behavior.) So memcpy doesn't need to explicitly check for this condition, whereas std::copy can be used as long as the OutputIterator parameter is not in the source range. Note this is not the same as saying that the source range and destination range can't overlap.

So since std::copy has somewhat different requirements, in theory it should be slightly (with an extreme emphasis on slightly) slower, since it probably will check for overlapping C-arrays, or else delegate the copying of C-arrays to memmove, which needs to perform the check. But in practice, you (and most profilers) probably won't even detect any difference.

Of course, if you're not working with PODs, you can't use memcpy anyway.

Sort an array of objects in React and render them

This might be what you're looking for:

// ... rest of code

// copy your state.data to a new array and sort it by itemM in ascending order
// and then map 
const myData = [].concat(this.state.data)
    .sort((a, b) => a.itemM > b.itemM ? 1 : -1)
    .map((item, i) => 
        <div key={i}> {item.matchID} {item.timeM}{item.description}</div>
    );

// render your data here...

The method sort will mutate the original array . Hence I create a new array using the concat method. The sorting on the field itemM should work on sortable entities like string and numbers.

Including JavaScript class definition from another file in Node.js

If you append this to user.js:

exports.User = User;

then in server.js you can do:

var userFile = require('./user.js');
var User = userFile.User;

http://nodejs.org/docs/v0.4.10/api/globals.html#require

Another way is:

global.User = User;

then this would be enough in server.js:

require('./user.js');

'mvn' is not recognized as an internal or external command,

Add maven directory /bin to System variables under the name Path.

To check this, you can echo %PATH%

Round up double to 2 decimal places

Use a format string to round up to two decimal places and convert the double to a String:

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)

Example:

let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"

If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):

let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"

How to use custom packages

I am an experienced programmer, but, quite new into Go world ! And I confess I've faced few difficulties to understand Go... I faced this same problem when trying to organize my go files in sub-folders. The way I did it :

GO_Directory ( the one assigned to $GOPATH )

GO_Directory //the one assigned to $GOPATH
__MyProject
_____ main.go
_____ Entites
_____ Fiboo // in my case, fiboo is a database name
_________ Client.go // in my case, Client is a table name

On File MyProject\Entities\Fiboo\Client.go

package Fiboo

type Client struct{
    ID int
    name string
}

on file MyProject\main.go

package main

import(
    Fiboo "./Entity/Fiboo" 
)

var TableClient  Fiboo.Client

func main(){
    TableClient.ID = 1
    TableClient.name = 'Hugo'

    // do your things here
}

( I am running Go 1.9 on Ubuntu 16.04 )

And remember guys, I am newbie on Go. If what I am doing is bad practice, let me know !

Hash function for a string

First, it usually does not matter that much in practice. Most hash functions are "good enough".

But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.

Your second hash function might be slightly better, because it probably should separate the string "ab" from the string "ba". On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.

I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.

Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>, Glib has several hash functions in C, and POCO has some hash function.

I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.

#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
   unsigned h = FIRSTH;
   while (*s) {
     h = (h * A) ^ (s[0] * B);
     s++;
   }
   return h; // or return h % C;
}

But I don't claim to be an hash expert. Of course, the values of A, B, C, FIRSTH should preferably be primes, but you could have chosen other prime numbers.

Look at some MD5 implementation to get a feeling of what hash functions can be.

Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.

Error "library not found for" after putting application in AdMob

I had a similar "library not found" issue. However it was because I accidentally was using the .xcodeproj file instead of the .xcworkspace file.

Constructor overload in TypeScript

In the case where an optional, typed parameter is good enough, consider the following code which accomplishes the same without repeating the properties or defining an interface:

export class Track {
   public title: string;
   public artist: string;
   public lyrics: string;

   constructor(track?: Track) {
     Object.assign(this, track);
   }
}

Keep in mind this will assign all properties passed in track, eve if they're not defined on Track.

jQuery Button.click() event is triggered twice

If you're using AngularJS:

If you're using AngularJS and your jQuery click event is INSIDE THE CONTROLLER, it will get disturbed by the Angular's framework itself and fire twice. To solve this, move it out of the controller and do the following:

// Make sure you're using $(document), or else it won't fire.
$(document).on("click", "#myTemplateId #myButtonId", function () {
   console.log("#myButtonId is fired!");
   // Do something else.
});

angular.module("myModuleName")
   .controller("myController", bla bla bla)

Why does integer division in C# return an integer and not a float?

It's just a basic operation.

Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.

9 / 6 == 1  //true
9 % 6 == 3 // true

The /-operator in combination with the %-operator are used to retrieve those values.

How to use NSJSONSerialization

Swift 2.0 on Xcode 7 (Beta) with do/try/catch block:

// MARK: NSURLConnectionDataDelegate

func connectionDidFinishLoading(connection:NSURLConnection) {
  do {
    if let response:NSDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.MutableContainers) as? Dictionary<String, AnyObject> {
      print(response)
    } else {
      print("Failed...")
    }
  } catch let serializationError as NSError {
    print(serializationError)
  }
}

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

how to convert .java file to a .class file

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:

javac File.java

SQL Server function to return minimum date (January 1, 1753)

This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:

CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
  RETURN (SELECT
    CAST('17530101' AS datetime))
END

Call using:

SELECT [dbo].[DateTimeMinValue]()

WPF button click in C# code

You should place below line

btn.Click = btn.Click + btn1_Click;

How to resolve 'unrecognized selector sent to instance'?

Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.

Ellipsis for overflow text in dropdown boxes

You can use this:

select {
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}
select option {
    width:100px;
    text-overflow:ellipsis;
    overflow:hidden;
}
div {
    border-style:solid; 
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

How do I overload the [] operator in C#

public int this[int index]
{
    get => values[index];
}

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

How can I know which radio button is selected via jQuery?

jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="toggle-form">
      <div id="radio">
        <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
        <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
      </div>
    </form>
    <script type="text/javascript">
    $( document ).ready(function() {
     //Get all radios:
     var radios = jQuery("input[type='radio']");
     checked_radios=radios.filter(":checked");
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

    });
    </script>

or another way

<script type="text/javascript">
$( document ).ready(function() {
  //Get all radios:
  checked_radios=jQuery('input[name=radio]:checked').val(); 
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

});
</script>

Easy way to export multiple data.frame to multiple Excel worksheets

I had this exact problem and I solved it this way:

library(openxlsx) # loads library and doesn't require Java installed

your_df_list <- c("df1", "df2", ..., "dfn")

for(name in your_df_list){
  write.xlsx(x = get(name), 
             file = "your_spreadsheet_name.xlsx", 
             sheetName = name)
}

That way you won't have to create a very long list manually if you have tons of dataframes to write to Excel.

Using OR operator in a jquery if statement

The code you wrote will always return true because state cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15).... AND is what you need not OR.

Use $.inArray instead. This returns the index of the element in the array.

JSFIDDLE DEMO

var statesArray = [10, 15, 19]; // list out all

var index = $.inArray(state, statesArray);

if(index == -1) {
    console.log("Not there in array");
    return true;

} else {
    console.log("Found it");
    return false;
}

How do I remove a file from the FileList

If you are targeting evergreen browsers (Chrome, Firefox, Edge, but also works in Safari 9+) or you can afford a polyfill, you can turn the FileList into an array by using Array.from() like this:

let fileArray = Array.from(fileList);

Then it's easy to handle the array of Files like any other array.

How to check whether an object is a date?

You could check if a function specific to the Date object exists:

function getFormatedDate(date) {
    if (date.getMonth) {
        var month = date.getMonth();
    }
}

C++ Dynamic Shared Library on Linux

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  void* handle = dlopen("myclass.so", RTLD_LAZY);

  MyClass* (*create)();
  void (*destroy)(MyClass*);

  create = (MyClass* (*)())dlsym(handle, "create_object");
  destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");

  MyClass* myClass = (MyClass*)create();
  myClass->DoSomething();
  destroy( myClass );
}

On Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object and destroy_object. Your main application would not need to be changed in any way.

Convert Mat to Array/Vector in OpenCV

cv::Mat m;
m.create(10, 10, CV_32FC3);

float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
    for ( unsigned j = 0; j < 3; j++ ) {
        *(array + i ) = (*it)[j];
        i++;
    }
}

Now you have a float array. In case of 8 bit, simply change float to uchar, Vec3f to Vec3b and CV_32FC3 to CV_8UC3.

Get url without querystring

Request.RawUrl.Split('?')[0]

Just for url name only !!

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

Bat file to run a .exe at the command prompt

As described here, about the Start command, the following would start your application with the parameters you've specified:

start "svcutil" "svcutil.exe" "language:cs" "out:generatedProxy.cs" "config:app.config" "http://localhost:8000/ServiceModelSamples/service"
  • "svcutil", after the start command, is the name given to the CMD window upon running the application specified. This is a required parameter of the start command.

  • "svcutil.exe" is the absolute or relative path to the application you want to run. Using quotation marks allows you to have spaces in the path.

  • After the application to start has been specified, all the following parameters are interpreted as arguments sent to the application.

Store mysql query output into a shell variable

If you want to use a single value in bash use:

  companyid=$(mysql --user=$Username --password=$Password --database=$Database -s --execute="select CompanyID from mytable limit 1;"|cut -f1)

  echo "$companyid"

How can I use iptables on centos 7?

RHEL and CentOS 7 use firewall-cmd instead of iptables. You should use that kind of command:

# add ssh port as permanent opened port
firewall-cmd --zone=public --add-port=22/tcp --permanent

Then, you can reload rules to be sure that everything is ok

firewall-cmd --reload

This is better than using iptable-save, espacially if you plan to use lxc or docker containers. Launching docker services will add some rules that iptable-save command will prompt. If you save the result, you will have a lot of rules that should NOT be saved. Because docker containers can change them ip addresses at next reboot.

Firewall-cmd with permanent option is better for that.

Check "man firewall-cmd" or check the official firewalld docs to see options. There are a lot of options to check zones, configuration, how it works... man page is really complete.

I strongly recommand to not use iptables-service since Centos 7

Error QApplication: no such file or directory

Well, It's a bit late for this but I've just started learning Qt and maybe this could help somebody out there:

If you're using Qt Creator then when you've started creating the project you were asked to choose a kit to be used with your project, Let's say you chose Desktop Qt <version-here> MinGW 64-bit. For Qt 5, If you opened the Qt folder of your installation, you'll find a folder with the version of Qt installed as its name inside it, here you can find the kits you can choose from.

You can go to /PATH/FOR/Qt/mingw<version>_64/include and here you'll find all the includes you can use in your program, just search for QApplication and you'll find it inside the folder QtWidgets, So you can use #include <QtWidgets/QApplication> since the path starts from the include folder.

The same goes for other headers if you're stuck with any and for other kits.

Note: "all the includes you can use" doesn't mean these are the only ones you can use, If you include iostream for example then the compiler will include it from /PATH/FOR/Qt/Tools/mingw<version>_64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/iostream

How to get index using LINQ?

myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;

or the slightly shorter

myCars.Select((car, index) => new {car, index}).First(myCondition).index;

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon() this will destroy the data.

Note, this won't necessarily truly remove the session token from a user, and that same session token at a later point might get picked up and created as a new session with the same id because it's deemed to be fair game to be used.

enum to string in modern C++11 / C++14 / C++17 and future C++20

For C++17 C++20, you will be interested in the work of the Reflection Study Group (SG7). There is a parallel series of papers covering wording (P0194) and rationale, design and evolution (P0385). (Links resolve to the latest paper in each series.)

As of P0194r2 (2016-10-15), the syntax would use the proposed reflexpr keyword:

meta::get_base_name_v<
  meta::get_element_m<
    meta::get_enumerators_m<reflexpr(MyEnum)>,
    0>
  >

For example (adapted from Matus Choclik's reflexpr branch of clang):

#include <reflexpr>
#include <iostream>

enum MyEnum { AAA = 1, BBB, CCC = 99 };

int main()
{
  auto name_of_MyEnum_0 = 
    std::meta::get_base_name_v<
      std::meta::get_element_m<
        std::meta::get_enumerators_m<reflexpr(MyEnum)>,
        0>
    >;

  // prints "AAA"
  std::cout << name_of_MyEnum_0 << std::endl;
}

Static reflection failed to make it into C++17 (rather, into the probably-final draft presented at the November 2016 standards meeting in Issaquah) but there is confidence that it will make it into C++20; from Herb Sutter's trip report:

In particular, the Reflection study group reviewed the latest merged static reflection proposal and found it ready to enter the main Evolution groups at our next meeting to start considering the unified static reflection proposal for a TS or for the next standard.

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Getting selected value of a combobox

Try this:

private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRowView drv = (DataRowView)cmbLineColor.SelectedItem;
        int selectedValue = (int)drv.Row.ItemArray[1];
    }

Is it possible to install both 32bit and 64bit Java on Windows 7?

Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

In fact, i have such a setup myself.

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

Why do I always get the same sequence of random numbers with rand()?

This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:

Declaration:

void srand(unsigned int seed); 

This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.

Find position of a node using xpath

You can do this with XSLT but I'm not sure about straight XPath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="yes" 
              omit-xml-declaration="yes"/>
  <xsl:template match="a/*[text()='tsr']">
    <xsl:number value-of="position()"/>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

How to create a library project in Android Studio and an application project that uses the library project

The simplest way for me to create and reuse a library project:

  1. On an opened project file > new > new module (and answer the UI questions)

enter image description here

  1. check/or add if in the file settings.gradle: include ':myLibrary'
  2. check/or add if in the file build.gradle:

    dependencies { ... compile project(':myLibrary') }

  3. To reuse this library module in another project, copy it's folder in the project instead of step 1 and do the steps 2 and 3.

You can also create a new studio application project You can easily change an existing application module to a library module by changing the plugin assignment in the build.gradle file to com.android.library.

apply plugin: 'com.android.application'

android {...}

to

apply plugin: 'com.android.library'

android {...}

more here

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

How to change the href for a hyperlink using jQuery

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

Join vs. sub-query

Subqueries have ability to calculate aggregation functions on a fly. E.g. Find minimal price of the book and get all books which are sold with this price. 1) Using Subqueries:

SELECT titles, price
FROM Books, Orders
WHERE price = 
(SELECT MIN(price)
 FROM Orders) AND (Books.ID=Orders.ID);

2) using JOINs

SELECT MIN(price)
     FROM Orders;
-----------------
2.99

SELECT titles, price
FROM Books b
INNER JOIN  Orders o
ON b.ID = o.ID
WHERE o.price = 2.99;

What's the "average" requests per second for a production web application?

When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get:

This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM.

Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server.

Total 3,444 M
per hour 2.68 M
per minute 44.59 k
per second 743.13

That's an average of 743 mySQL queries every single second for the past 53 days!

I don't know about you, but to me that's fast! Very fast!!

EF Migrations: Rollback last applied migration?

Update-Database –TargetMigration:"Your migration name"

For this problem I suggest this link:

https://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

Change the value in app.config file dynamically

Expanding on Adis H's example to include the null case (got bit on this one)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

Currency formatting in Python

New in 2.7

>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'

http://docs.python.org/dev/whatsnew/2.7.html#pep-0378

Storing data into list with class

This line is your problem:

lstemail.Add("JOhn","Smith","Los Angeles");

There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add() an instance of the class to lstemail:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

Display html text in uitextview

My first response was made before iOS 7 introduced explicit support for displaying attributed strings in common controls. You may now set attributedText of UITextView to an NSAttributedString created from HTML content using:

-(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error 

- initWithData:options:documentAttributes:error: (Apple Doc)

Original answer, preserved for history:

Unless you use a UIWebView, your solution will rely directly on CoreText. As ElanthiraiyanS points out, some open source projects have emerged to simplify rich text rendering. I would recommend NSAttributedString-Additions-For-HTML (Edit: the project has been supplanted DTCoreText), which features classes to generate and display attributed strings from HTML.

How do I declare a global variable in VBA?

Also you can use -

Private Const SrlNumber As Integer = 910

Private Sub Workbook_Open()
    If SrlNumber > 900 Then
        MsgBox "This serial number is valid"
    Else
        MsgBox "This serial number is not valid"
    End If
End Sub

Its tested on office 2010

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

Seedable JavaScript random number generator

One option is http://davidbau.com/seedrandom which is a seedable RC4-based Math.random() drop-in replacement with nice properties.

Text not wrapping inside a div element

That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all; to your .title rules to force a break.

#calendar_container > #events_container > .event_block > .title {
    width:400px;
    font-size:12px;
    word-break:break-all;
}

jsFiddle example

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

I noticed the same error as soon as I added Google Analytics and started testing on localhost.

I have both AdBlock as well as Ghostery... it actually (for me) wasn't AdBlock interfering - it was Ghostery. To "fix", in Ghostery settings, under "Analytics", uncheck Google Analytics.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

php static function

Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.

Well, okay, one other difference: an E_STRICT warning is generated by your first example.

Relative imports in Python 3

unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that?

It's quite common to have a layout like this...

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

...with a mymodule.py like this...

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

...a myothermodule.py like this...

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

...and a main.py like this...

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

...which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import...

from .mymodule import as_int

The way you're supposed to run it is...

python3 -m mypackage.myothermodule

...but it's somewhat verbose, and doesn't mix well with a shebang line like #!/usr/bin/env python3.

The simplest fix for this case, assuming the name mymodule is globally unique, would be to avoid using relative imports, and just use...

from mymodule import as_int

...although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in PYTHONPATH, and do it like this...

from mypackage.mymodule import as_int

...or if you want it to work "out of the box", you can frob the PYTHONPATH in code first with this...

import sys
import os

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

from mypackage.mymodule import as_int

It's kind of a pain, but there's a clue as to why in an email written by a certain Guido van Rossum...

I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't.

Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame containing only that widget for testing purposes.

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

Showing Difference between two datetime values in hours

I think you're confused because you haven't declared a TimeSpan you've declared a TimeSpan? which is a nullable TimeSpan. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours.

Pycharm: run only part of my Python file

  1. Go to File >> Settings >> Plugins and install the plugin PyCharm cell mode
  2. Go to File >> Settings >> Appearance & Behavior >> Keymap and assign your keyboard shortcuts for Run Cell and Run Cell and go to next

A cell is delimited by ##

Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode

How to convert array values to lowercase in PHP?

Just for completeness: you may also use array_walk:

array_walk($yourArray, function(&$value)
{
  $value = strtolower($value);
});

From PHP docs:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Or directly via foreach loop using references:

foreach($yourArray as &$value)
  $value = strtolower($value);

Note that these two methods change the array "in place", whereas array_map creates and returns a copy of the array, which may not be desirable in case of very large arrays.

What's the most useful and complete Java cheat sheet?

This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.

For the complete API, however, I always use the Javadoc. I reference it constantly.