Programs & Examples On #Svn

Use this tag for questions about SVN (Subversion), a centralized open-source revision control system distributed under the Apache License.

SVN change username

You can change the user with

  • Subversion 1.6 and earlier:

    svn switch --relocate protocol://currentUser@server/path protocol://newUser@server/path
    
  • Subversion 1.7 and later:

    svn relocate protocol://currentUser@server/path protocol://newUser@server/path
    

To find out what protocol://currentUser@server/path is, run

svn info

in your working copy.

Svn switch from trunk to branch

  • Short version of (correct) tzaman answer will be (for fresh SVN)

    svn switch ^/branches/v1p2p3
    
  • --relocate switch is deprecated anyway, when it needed you'll have to use svn relocate command

  • Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)

On Windows, the caret character (^) must be escaped:

svn switch ^^/branches/v1p2p3

Deleting an SVN branch

From the working copy:

svn rm branches/features
svn commit -m "delete stale feature branch"

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.

I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.

I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.

How to find my Subversion server version number?

To find the version of the subversion REPOSITORY you can:

  1. Look to the repository on the web and on the bottom of the page it will say something like:
    "Powered by Subversion version 1.5.2 (r32768)."
  2. From the command line: <insert curl, grep oneliner here>

If not displayed, view source of the page

<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> 

Now for the subversion CLIENT:

svn --version

will suffice

How to fix Subversion lock error

Using SVN 1.8, deleting lock file does not help (lock file does not exists).

Refresh/Cleanup did not solve either.

What did solve:

1) Backup your directory, just incase...
2) Team... Disconnect. Choose to remove .svn files
3) Add it again to SVN.

Note: In my case, error was due to loss of network connection during initial commit.

Subversion ignoring "--password" and "--username" options

Look to your local svn repo and look into directory .svn . there is file: entries look into them and you'll see lines begins with: svn+ssh://

this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'

if you want to change this, te best way is completly refresh this repository. update/commit what you should for save work. then remove completly directory and last step is create this by svn co/checkout 'URI-for-main-repo' [optionally local directory for store]

you should select connection method to repo file:// svn+ssh:// http:// https:// or other described in documentation.

after that you use svn update/commit as usual.

this topic looks like out of topic. better you go to superuser pages.

Update OpenSSL on OS X with Homebrew

I had this issue and found that the installation of the newer openssl did actually work, but my PATH was setup incorrectly for it -- my $PATH had the ports path placed before my brew path so it always found the older version of openssl.

The fix for me was to put the path to brew (/usr/local/bin) at the front of my $PATH.

To find out where you're loading openssl from, run which openssl and note the output. It will be the location of the version your system is using when you run openssl. Its going to be somewhere other than the brewpath of "/usr/local/bin". Change your $PATH, close that terminal tab and open a new one, and run which openssl. You should see a different path now, probably under /usr/local/bin. Now run openssl version and you should see the new version you installed "OpenSSL 1.0.1e 11 Feb 2013".

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I had this problem on a project I run on Netbeans. I simply right clicked on the file and update to fix it (after SVN up).

Remove file from SVN repository without deleting local copy

When you want to remove one xxx.java file from SVN:

  1. Go to workspace path where the file is located.
  2. Delete that file from the folder (xxx.java)
  3. Right click and commit, then a window will open.
  4. Select the file you deleted (xxx.java) from the folder, and again right click and delete.. it will remove the file from SVN.

Merge a Branch into Trunk

Do an svn update in the trunk, note the revision number.

From the trunk:

svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName

You can check where the branch was cut from the trunk by doing an svn log

svn log --stop-on-copy

How to save password when using Subversion from the console

I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config does not help to store the password.

The password was successfully saved after removing this folder (just in case renaming):

%USERPROFILE%\AppData\Roaming\Subversion\auth

Environment:

Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.

How do I 'svn add' all unversioned files to SVN?

You can use command

svn add * force--

or

svn add <directory/file name>

If your files/directories are not adding recursively. Then check this.

Recursive adding is default property. You can see in SVN book.

Issue can be in your ignore list or global properties.

I got solution google issue tracker

Check global properties for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Properties.
  • See if you don't have a property svn:global-ignores with a value of *
  • If you have property with star(*) then it will ignore recursive adding. So remove this property.

Check global ignore pattern for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Settings > General.
  • See in Global Ignore Pattern, if you don't have set star(*) there.
  • If you found star(*), remove this property.

This guy also explained why this property added in my project.

The most like way that it got there is that someone right-clicked a file without any extension and selected TortoiseSVN -> SVN Ignore -> * (recursively), and then committed this.

You can check the log to see who committed that property change, find out what they were actually trying to do, and ask them to be more careful in future. :)

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

This looks like a problem with the svn:mergeinfo property getting out of wack between the branch and the trunk.

Which leads to the following questions (forgive my command line instructions as I done use tortoise much):

  1. Are you merging at the trunk root level or the sub folder level? In my experience it is always best to do at the root level, this way the whole trunk thinks it has been merged to rather than just part (this seems to confuse svn greatly in 1.5.0)

  2. My next question is were you using the --reintergrate parameter? I can never remember how to get to this in tortoise, but when you are going back to the trunk from a branch then you should use this parameter.

  3. Have you merged the trunk into the branch before you have reintegrated? This can help remove conflicts that you may see when you merge back?

  4. Have you got any svn:mergeinfo properties on the branch that are not at the root level? This I have found always causes problems. You can always find this out by going svn -R pg svn:mergeinfo. You can then record the locations and revisions that were below the root, if you find them relevant then move them to the root by svn merge --record-only -r start:end <location> and then delete them from the sub root locations with svn pd svn:mergeinfo <location> You then need to commit these changes

  5. Once you have all that is done try merging again.

Associating existing Eclipse project with existing SVN repository

I am using Tortoise SVN client. You can alternativley check out the required project from SVN in some folder. You can see a .SVN folder inside the project. Copy the .SVN folder into the workspace folder. Now remove the project from eclipse and import the same again into eclipse. You can see now the project is now associated with svn

How to resolve "local edit, incoming delete upon update" message

I just got this same issue and I found that

$ svn revert foo bar

solved the problem.

svn resolve did not work for me:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working
svn: Try 'svn help' for more info
svn: Not enough arguments provided

$ svn resolve --accept working .

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working foo
Resolved conflicted state of 'foo'

$ svn st
!  +    foo
!  +  C bar
      >   local edit, incoming delete upon update

How to add an existing folder with files to SVN?

I don't use commands. You should be able to do this using the GUI:

  • Right-click an empty space in your My Documents folder, select TortoiseSVN > Repo-browser.
  • Enter http://subversion... (your URL path to your Subversion server/directory you will save to) as your path and select OK
  • Right-click the root directory in Repo and select Add folder. Give it the name of your project and create it.
  • Right-click the project folder in the Repo-browser and select Checkout. The Checkout directory will be your Visual Studio\Projects\{your project} folder. Select OK.
  • You will receive a warning that the folder is not empty. Say Yes to checkout/export to that folder - it will not overwrite your project files.
  • Open your project folder. You will see question marks on folders that are associated with your VS project that have not yet been added to Subversion. Select those folders using Ctrl + Click, then right-click one of the selected items and select TortoiseSVN > Add
  • Select OK on the prompt
  • Your files should add. Select OK on the Add Finished! dialog
  • Right-click in an empty area of the folder and select Refresh. You’ll see “+” icons on the folders/files, now
  • Right-click an empty area in the folder once again and select SVN Commit
  • Add a message regarding what you are committing and click OK

What is the correct way to restore a deleted file from SVN?

With Tortoise SVN:

If you haven't committed your changes yet, you can do a revert on the parent folder where you deleted the file or directory.

If you have already committed the deleted file, then you can use the repository browser, change to the revision where the file still existed and then use the command Copy to... from the context menu. Enter the path to your working copy as the target and the deleted file will be copied from the repository to your working copy.

How can I commit a single file using SVN over a network?

cd myapp/trunk
svn commit -m "commit message" page1.html

For more information, see:

svn commit --help

I also recommend this free book, if you're just getting started with Subversion.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

I have encounter the same issue and found that i have forgot to prefix the commit message with project identifier. Project identifier is must in our case followed by the commit message. So at the server end it doesn't found the prefix and raised the issue.

Connect Android Studio with SVN

Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.

Working Copy Locked

To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:

I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).

So to resolve this:

Either

1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe

1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe

Then

2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.

From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.

SVN- How to commit multiple files in a single shot

You can use --targets ARG option where ARG is the name of textfile containing the targets for commit.

svn ci --targets myfiles.txt -m "another commit"

What does the red exclamation point icon in Eclipse mean?

What I did was peculiar but somehow it fixed the problem. Pick any project and perform a fake edit of the build.properties file (e.g., add and remove a space and then save the file). Clean and rebuild the projects in your workspace.

Hope this solve some of your problems.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

SVN remains in conflict?

If you are using the Eclipse IDE and stumble upon this error when committing, here's an in-tool solution for you. I'm using Subclipse, but the solution for Subversive could be similar.

What you maybe didn't notice is that there is an additional symbol on the conflicting file, which marks the file indeed as "conflicted".

Right-click on the file, choose "Team" and "Edit conflicts...". Choose the appropriate action. I merged the file manually on text-level before, so I took the first option, which will take the current state of your local copy as "resolved solution". Now hit "OK" and that's it.

The conflicting symbol should have disappeared and you should be able to commit again.

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

Working copy XXX locked and cleanup failed in SVN

While doing svn update using tortoise svn, the process got interrupted and stopped complaining the file is in use. Next it asked me to use CleanUp command on the folder. I tried to run CleanUp command but it failed to do so. Then I found a command shell which was using the folder files. So, I closed the command shell and checked if any editor is using the files related to it. We need to close them as well. Again, I tried CleanUp on the folder with options Break locks,revert changes,clear working copy status . The CleanUp went successfully. Then finally able to update my svn folder.

Where does SVN client store user authentication data?

Read SVNBook | Client Credentials.

With modern SVN you can just run svn auth to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth on Windows and ~/.subversion/auth/ on Unix-like systems.

PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user

Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials

How to checkout a specific Subversion revision from the command line?

It seems that you can use the repository browser. Click the revision button at top-right and change it to the revision you want. Then right-click your file in the browser and use 'Copy to working copy...' but change the filename it will check out, to avoid a clash.

SVN commit command

Command-line SVN

You need to add your files to your working copy, before you commit your changes to the repository:

svn add <file|folder>

Afterwards:

svn commit

See here for detailed information about svn add.

TortoiseSVN

It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):

If you want to include an unversioned file, just check that file to add it to the commit.

See: TortoiseSVN: Committing Your Changes To The Repository

Why am I getting tree conflicts in Subversion?

In my experience, SVN creates a tree conflict WHENEVER I delete a folder. There appears to be no reason.

I'm the only one working on my code -> delete a directory -> commit -> conflict!

I can't wait to switch to Git.

I should clarify - I use Subclipse. That's probably the problem! Again, I can't wait to switch...

Adding a SVN repository in Eclipse

Try to connect to the repository using command line SVN to see if you get a similar error.

$ svn checkout http://svn.python.org/projects/peps/trunk

If you keep getting the error, it is probably an issue with your proxy server. I have found that I can't check out internet based SVN projects at work because the firewall blocks most HTTP commands. It only allows GET, POST and others necessary for browsing.

SVN Error - Not a working copy

If you get a "not a working copy" when doing a recursive svn cleanup my guess is that you have a directory which should be a working copy (i.e. the .svn directory at the top level says so), but it is missing its own .svn directory. In that case, you could try to just remove/move that directory and then do a local update (i.e. rm -rf content; svn checkout content).

If you get a not a working copy error, it means that Subversion cannot find a proper .svn directory in there. Check to see if there is an .svn directory in contents

The ideal solution is a fresh checkout, if possible.

SVN: Folder already under version control but not comitting?

I had a similar-looking problem after adding a directory tree which contained .svn directories (because it was an svn:external in its source environment): svn status told me "?", but when trying to add it, it was "already under version control".

Since no other versioned directories were present, I did

find . -mindepth 2 -name '.svn' -exec rm -rf '{}' \;

to remove the wrong .svn directories; after doing this, I was able to add the new directory.

Note:

  • If other versioned directories are contained, the find expression must be changed to be more specific
  • If unsure, first omit the "-exec ..." part to see what would be deleted

How to have git log show filenames like svn log -v

I find the following is the ideal display for listing what files changed per commit in a concise format :

git log --pretty=oneline --graph --name-status

Is there a Subversion command to reset the working copy?

Delete everything inside your local copy using:

rm -r your_local_svn_dir_path/*

And the revert everything recursively using the below command.

svn revert -R your_local_svn_dir_path

This is way faster than deleting the entire directory and then taking a fresh checkout, because the files are being restored from you local SVN meta data. It doesn't even need a network connection.

Why is Git better than Subversion?

Git in Windows is quite well supported now.

Check out GitExtensions = http://code.google.com/p/gitextensions/

and the manual for a better Windows Git experience.

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Update Item to Revision vs Revert to Revision

@BaltoStar update to revision syntax:

http://svnbook.red-bean.com/en/1.6/svn.ref.svn.c.update.html

svn update -r30

Where 30 is revision number. Hope this help!

Pushing an existing Git repository to SVN

I needed to commit my existing Git repository to an empty SVN repository.

This is how I managed to do this:

$ git checkout master
$ git branch svn
$ git svn init -s --prefix=svn/ --username <user> https://path.to.repo.com/svn/project/
$ git checkout svn
$ git svn fetch
$ git reset --hard remotes/svn/trunk
$ git merge master
$ git svn dcommit

It worked without problems. I hope this helps someone.

Since I had to authorize myself with a different username to the SVN repository (my origin uses private/public key authentication), I had to use the --username property.

How do I ignore a directory with SVN?

Jason's answer will do the trick. However, instead of setting svn:ignore to "." on the cache directory, you may want to include "cache" in the parent directory's svn:ignore property, in case the cache directory is not always present. I do this on a number of "throwaway" folders.

svn : how to create a branch from certain revision of trunk

Try below one:

svn copy http://svn.example.com/repos/calc/trunk@rev-no 
       http://svn.example.com/repos/calc/branches/my-calc-branch 
  -m "Creating a private branch of /calc/trunk."  --parents

No slash "\" between the svn URLs.

svn over HTTP proxy

If you can get SSH to it you can an SSH Port-forwarded SVN server.

Use SSHs -L ( or -R , I forget, it always confuses me ) to make an ssh tunnel so that

127.0.0.1:3690 is really connecting to remote:3690 over the ssh tunnel, and then you can use it via

svn co svn://127.0.0.1/....

SVN Repository Search

This example pipes the complete contents of the repository to a file, which you can then quickly search for filenames within an editor:

svn list -R svn://svn > filelist.txt

This is useful if the repository is relatively static and you want to do rapid searches without having to repeatedly load everything from the SVN server.

How do you see recent SVN log entries?

Besides what Bert F said, many commands, including log has the -r (or --revision) option. The following are some practical examples using this option to show ranges of revisions:

To list everything in ascending order:

svn log -r 1:HEAD

To list everything in descending order:

svn log -r HEAD:1

To list everything from the thirteenth to the base of the currently checked-out revision in ascending order:

svn log -r 13:BASE

To get everything between the given dates:

svn log -r {2011-02-02}:{2011-02-03}

You can combine all the above expressions with the --limit option, so that can you have a quite granular control over what is printed. For more info about these -r expressions refer to svn help log or the relevant chapter in the book Version Control with Subversion

How to rename a file using svn?

The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:

Target file does not exist:

In this case svn mv should work as follows:

$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding     new_file_name
Deleting   old_file_name
Committing transaction...

Target file already exists in repository:

In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name 
D         new_file_name
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
R  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Replacing      new_file_name
Deleting       old_file_name
Committing transaction...

In the output of svn stat, the R indicates that the file has been replaced, and that the file has a history.

Target file already exists locally (unversioned):

In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name 
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding         new_file_name
Deleting       old_file_name
Committing transaction...

How do I create a branch?

Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.

  1. Right Click on updated trunk from local windows machine
  2. Select TortoiseSVN
  3. Click branch/Tag
  4. Select the To path in SVN repository. Note that destination URL is updated according to the path and branch name given
  5. Do not create folder inside branches in repository browser
  6. Add branches path. For example, branches/
  7. Add a meaningful log message for your reference
  8. Click Ok, this creates new folder on local system
  9. Checkout the branch created into new folder

SVN icon overlays not showing properly

I found a simple solution, just open Settings of TortoiseSVN, and expand Icon Overlays, select Icon Set and change the icon set.

The default icon set of mine is XP Style, and I change it to Win10 because Win10 is the OS I am currently using.

The setting

Restart your computer and problem gets solved.

How to do SVN Update on my project using the command line

svn update /path/to/working/copy

If subversion is not in your PATH, then of course

/path/to/subversion/svn update /path/to/working/copy

or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as

svn update

How to use SVN, Branch? Tag? Trunk?

Eric Sink, who appeared on SO podcast#36 in January 2009, wrote an excellent series of articles under the title Source Control How-to.

(Eric is the founder of SourceGear who market a plug-compatible version of SourceSafe, but without the horribleness.)

What should I do when 'svn cleanup' fails?

Answers here didn't help me, but before checking out the project again, I closed and opened Eclipse (Subversive is my SVN client) and the problem disappeared.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache user has read/write access to your entire repository. To do that, chown -R apache:apache *, chmod -R 664 * for everything under your svn repository.

Also, see here and here if you're still stuck.


Update to answer OP's additional question in comments:

The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.

Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:

  • first bit: read permissions
  • second bit: write permissions
  • third bit: execute permissions

For example, 764 on a file would mean that:

  • the owner (first digit) has read/write/execute (7) permission
  • the group (second digit) has read/write (6) permission
  • everyone else (third digit) has read (4) permission

Hope that clears things up!

Subversion stuck due to "previous operation has not finished"?

Further to Sigurd V's answer (you should try that first), some larger code bases have multiple '.svn' folders, and it's not necessarily the one in the root directory which has the locked task.

If that's the case, you have to check each one. If you've already got SQLite and Powershell you can locate the offending directory quickly.

To find which folders is locked run (replacing path\to\sqlite.exe):

Get-ChildItem -Path . -Filter '.svn' -Recurse -Hidden | foreach { $toFind = $_.FullName + "\wc.db" ; gci $toFind | foreach { echo $_.FullName ; path\to\sqlite.exe $_.FullName "select * from work_queue" } }.

This gives a list of .svn directories and, below each one, a list of any current tasks.

If there are any with unfinished tasks, for each one run (replacing path\to\sqlite.exe and path\to\.svn\wc.db):

path\to\sqlite.exe path\to\.svn\wc.db "delete from work_queue"

Download an SVN repository?

For me DownloadSVN is the best SVN client no install no explore shell integration so no need to worry about system instability small and very light weight and it does a great job just recently i had a very bad experience with TortoiseSVN on my WindowsXP_x86:) luckily i found this great SVN client

Does svn have a `revert-all` command?

To revert modified files:

sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'

SVN repository backup strategies

I like to just copy the entire repo directory to my backup location. That way, if something happens, you can just copy the directory back and be ready to go immediately.

Just make sure to preserve permissions, if needed. Usually, this is only a concern on Linux machines.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

To move a file or set of files using Tortoise SVN, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a SVN move versioned files here option.

Note that the destination folder must have already been added to the repository for the SVN move versioned files here option to appear.

How do you overcome the svn 'out of date' error?

I sometimes get this with TortoiseSVN on windows. The solution for me is to svn update the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Using TortoiseSVN via the command line

To enable svn run the TortoiseSVN installation program again, select "Modify" (Allows users to change the way features are installed) and install "command line client tools".

Server certificate verification failed: issuer is not trusted

Run "svn help commit" to all available options. You will see that there is one option responsible for accepting server certificates:

--trust-server-cert : accept unknown SSL server certificates without prompting (but only with --non-interactive)

Add it to your svn command arguments and you will not need to run svn manually to accept it permanently.

svn cleanup: sqlite: database disk image is malformed

I fixed this for an instance of it happening to me by deleting the hidden .svn folder and then performing a checkout on the folder to the same URL.

This did not overwrite any of my modified files & just versioned all of the existing files instead of grabbing fresh copies from the server.

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

SVN 405 Method Not Allowed

This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.

What do the result codes in SVN mean?

You can always get a list by running:

svn status --help

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

How change default SVN username and password to commit changes?

To use alternate credentials for a single operation, use the --username and --password switches for svn.

To clear previously-saved credentials, delete ~/.subversion/auth. You'll be prompted for credentials the next time they're needed.

These settings are saved in the user's home directory, so if you're using a shared account on "this laptop", be careful - if you allow the client to save your credentials, someone can impersonate you. The first option I provided is the better way to go in this case. At least until you stop using shared accounts on computers, which you shouldn't be doing.

To change credentials you need to do:

  • rm -rf ~/.subversion/auth
  • svn up ( it'll ask you for new username & password )

How do I revert an SVN commit?

Alex, try this: svn merge [WorkingFolderPath] -r 1944:1943

Adding new files to a subversion repository

Normally svn add * works. But if you get message like svn: warning: W150002: due to mix off versioned and non-versioned files in working copy. Use this command:

svn add <path to directory> --force

or

svn add * --force

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

SVN Commit failed, access forbidden

Actually, I had this problem same as you. My windows is server 2008 and my subversion info is :

TortoiseSVN 1.7.6, Build 22632 - 64 Bit , 2012/03/08 18:29:39 Subversion 1.7.4, apr 1.4.5 apr-utils 1.3.12 neon 0.29.6 OpenSSL 1.0.0g 18 Jan 2012 zlib 1.2.5

I used this way and I solved this problem. I used [group] option. this option makes problem. I rewrite authz file contents. I remove group option. and I set one by one. I use well.

Thanks for reading.

In Subversion can I be a user other than my login name?

I believe you can set the SVN_USER environment variable to change your SVN username.

What is a pre-revprop-change hook in SVN, and how do I create it?

For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):

http://ayria.livejournal.com/33438.html

Basically copy the code below into a text file and name it pre-revprop-change.bat and save it in the \hooks subdirectory for your repository.

@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

How to properly create an SVN tag from trunk?

As noted by @victor hugo, the "proper" way is to use svn copy. There is one caveat though. The "tag" created that way will not be a true tag, it will be an exact copy of the specified revision, but it will be a different revision itself. So if your build system makes use of svn revision somehow (e.g. incorporates the number obtained with 'svn info' into the version of the product you build), then you won't be able to build exactly the same product from a tag (the result will have the revision of the tag instead of that of the original code).

It looks like by design there is no way in svn to create a truly proper meta tag.

How to use "svn export" command to get a single file from the repository?

Guessing from your directory name, you are trying to access the repository on the local filesystem. You still need to use URL syntax to access it:

svn export file:///e:/repositories/process/test.txt c:\test.txt

Get last dirname/filename in a file path argument in Bash

Bash can get the last part of a path without having to call the external basename:

subdir="/path/to/whatever/${1##*/}"

Failed to load JavaHL Library

Check out this blog. It has a ton of information. Also if installing through brew don´t miss this note:

You may need to link the Java bindings into the Java Extensions folder:

 $ sudo mkdir -p /Library/Java/Extensions
 $ sudo ln -s /usr/local/lib/libsvnjavahl-1.dylib /Library/Java/Extensions/libsvnjavahl-1.dylib

SVN how to resolve new tree conflicts when file is added on two branches

As was mentioned in an older version (2009) of the "Tree Conflict" design document:

XFAIL conflict from merge of add over versioned file

This test does a merge which brings a file addition without history onto an existing versioned file.
This should be a tree conflict on the file of the 'local obstruction, incoming add upon merge' variety. Fixed expectations in r35341.

(This is also called "evil twins" in ClearCase by the way):
a file is created twice (here "added" twice) in two different branches, creating two different histories for two different elements, but with the same name.

The theoretical solution is to manually merge those files (with an external diff tool) in the destination branch 'B2'.

If you still are working on the source branch, the ideal scenario would be to remove that file from the source branch B1, merge back from B2 to B1 in order to make that file visible on B1 (you will then work on the same element).
If a merge back is not possible because merges only occurs from B1 to B2, then a manual merge will be necessary for each B1->B2 merges.

svn list of files that are modified in local copy

Right click folder -> Click Tortoise SVN -> Check for modification

How to change password using TortoiseSVN?

Password changes are handled by the subversion server administrator. As a user there is no password change option.

Check with your server admin.

If you are the admin, find your SVN Server installation. If you don't know where it is, it could be listed in Start->Programs, running under services in Start->Control Panel->Services or it could be listed under C:\Program Files.

The SVN Server should have an application to run to add/change/delete authentication and users.

How do I view an older version of an SVN file?

To directly answer the question of how to "get a copy of that file":

svn cat -r 666 file > file_r666

then you can view the newly created file_r666 with any viewer or comparison program, e.g.

kompare file_r666 file

nicely shows the differences.

I posted the answer because the accepted answer's commands do actually not give a copy of the file and because svn cat -r 666 file | vim does not work with my system (Vim: Error reading input, exiting...)

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

See last changes in svn

You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.

How to edit log message already committed in Subversion?

If your repository enables setting revision properties via the pre-revprop-change hook you can change log messages much easier.

svn propedit --revprop -r 1234 svn:log url://to/repository

Or in TortoiseSVN, AnkhSVN and probably many other subversion clients by right clicking on a log entry and then 'change log message'.

How do you move a file?

Since you're using Tortoise you may want to check out this link on LosTechies. It should be almost exactly what you are looking for.

http://www.lostechies.com/blogs/joshua_lockwood/archive/2007/09/12/subversion-tip-of-the-day-moving-files.aspx

Subclipse svn:ignore

One more thing... If you already ignored those files through Eclipse (with Team -> Ignored resources) you have to undo these settings so the files are controlled by Subclipse again and "Add to svn:ignore" option reappears

How can I remove all my changes in my SVN working directory?

If you have no changes, you can always be really thorough and/or lazy and do...

rm -rf *
svn update

But, no really, do not do that unless you are really sure that the nuke-from-space option is what you want!! This has the advantage of also nuking all build cruft, temporary files, and things that SVN ignores.

The more correct solution is to use the revert command:

svn revert -R .

The -R causes subversion to recurse and revert everything in and below the current working directory.

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Basically, what IntelliJ needs is svn.exe. You will need to install Subversion for Windows. It automatically adds svn.exe to PATH environment variable. After installing, please restart IntelliJ.

Note - Tortoise SVN doesn't install svn.exe, at least I couldn't find it in my TortoiseSVN bin directory.

Force an SVN checkout command to overwrite current files

Pull from the repository to a new directory, then rename the old one to old_crufty, and the new one to my_real_webserver_directory, and you're good to go.

If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.

SVN upgrade working copy

On MacOS:

  1. Get the latest compiled SVN client binaries from here.
  2. Install.
  3. Add binaries to path (the last installation screen explains how).
  4. Open terminal and run the following command on your project directory:

    svn upgrade

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

I had the same problem with Versions displaying the same message. I simply right clicked the offending files and selected 'Revert...' from the right-click menu and all was good.

Basically Versions (actually Subversion) thinks you still want to add the file, but it cannot find it because you deleted it in the file system. The Revert option tells Subversion to forget about adding it.

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

Should I use SVN or Git?

I would opt for SVN since it is more widely spread and better known.

I guess, Git would be better for Linux user.

List files committed for a revision

svn log --verbose -r 42

What do "branch", "tag" and "trunk" mean in Subversion repositories?

The trunk directory is the directory that you're probably most familiar with, because it is used to hold the most recent changes. Your main codebase should be in trunk.

The branches directory is for holding your branches, whatever they may be.

The tags directory is basically for tagging a certain set of files. You do this for things like releases, where you want "1.0" to be these files at these revisions and "1.1" to be these files at these revisions. You usually don't modify tags once they're made. For more information on tags, see Chapter 4. Branching and Merging (in Version Control with Subversion).

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference: http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:

SET IDENTITY_INSERT Genre ON

INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Just FYI, I noticed this information from the jQuery documentation which I believe applies to this issue:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Changing the hosts file like @thanix didn't work for me, but the extension mentioned by @dkruchok did solve the problem.

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

I received the error the OP stated using Django, React, and the django-cors-headers lib. To fix it with this stack, do the following:

In settings.py add the below per the official documentation.

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
'YOUR_HEADER_NAME',
)

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

To solve this problem first make sure that your java software should be 32bit version if it is 64 bit version clearly it will show the mismatch error so try to re-install 32bit of java version And execute the java program in the command of c:\windows\sysWOW64\odbcad32.exe (easiest to copy and paste into run dialog) that's enough your program definitely work

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Basically v3.X was simpler but v4.x is strict in these means of synchronous & asynchronous tasks.

The async/await is pretty simple & helpful way to understand the workflow & issue.

Use this simple approach

const gulp = require('gulp')

gulp.task('message',async function(){
return console.log('Gulp is running...')
})

How should I escape commas and speech marks in CSV files so they work in Excel?

Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.

  1. If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.

  2. Any double quote characters in the value should be escaped with another double quote.

  3. If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.

How do I print to the debug output window in a Win32 app?

To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.

OutputDebugString prints to the debugger output when running inside the debugger.

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

Save each sheet in a workbook to separate CSV files

And here's my solution should work with Excel > 2000, but tested only on 2007:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

(OT: I wonder if SO will replace some of my minor blogging)

Find package name for Android apps to use Intent to launch Market app from web

This is quite a difficult situation, you can get the package name from the apk file, but i assume you want to do it automatically.

AndroLib has the package names for lots of apps but you would have to parse it as there is no API that i could find. Theres a dev section that may have some tools to help you.

Good Luck

Changing CSS for last <li>

:last-child is CSS3 and has no IE support while :first-child is CSS2, I believe the following is the safe way to implement it using jquery

$('li').last().addClass('someClass');

Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

How to run certain task every day at a particular time using ScheduledExecutorService?

In Java 8:

scheduler = Executors.newScheduledThreadPool(1);

//Change here for the hour you want ----------------------------------.at()       
Long midnight=LocalDateTime.now().until(LocalDate.now().plusDays(1).atStartOfDay(), ChronoUnit.MINUTES);
scheduler.scheduleAtFixedRate(this, midnight, 1440, TimeUnit.MINUTES);

How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
        .stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
        .collect(Collectors.joining()));

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

C# list.Orderby descending

list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();

Which works for me to show the time sorted in descending order.

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

You are having issue with newly MySQL version that came with "caching_sha2_password" plugin, follow the below command to get it resolved.

DROP USER 'your_user_name'@'%';
CREATE USER 'your_user_name'@'%' IDENTIFIED WITH mysql_native_password BY 'your_user_password';
GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_user_name'@'%' identified by 'your_user_password';

Or you can just use the below command to keep your privileges as it is:

ALTER USER your_user_name IDENTIFIED WITH mysql_native_password;

Replace or delete certain characters from filenames of all files in a folder

I would recommend the rename command for this. Type ren /? at the command line for more help.

How do I redirect a user when a button is clicked?

You can easily wrap your button tag with tag.Using Url.Action() HTML Helper this will get to navigate to one page to another.

<a href='@Url.Action("YourAction", "YourController")'>
    <input type='button' value='Dummy Button' />
</a>

If you want to navigate with javascript onclick() function then use

<input type='button' value='Dummy Button' onclick='window.location = "@Url.Action("YourAction", "YourController")";' />

Using python PIL to turn a RGB image into a pure black and white image

A simple way to do it using python :

Python
import numpy as np
import imageio

image = imageio.imread(r'[image-path]', as_gray=True)

# getting the threshold value
thresholdValue = np.mean(image)

# getting the dimensions of the image
xDim, yDim = image.shape

# turn the image into a black and white image
for i in range(xDim):
    for j in range(yDim):
        if (image[i][j] > thresholdValue):
            image[i][j] = 255
        else:
            image[i][j] = 0

virtualenvwrapper and Python 3

The latest version of virtualenvwrapper is tested under Python3.2. Chances are good it will work with Python3.3 too.

In Perl, how to remove ^M from a file?

Slightly unrelated, but to remove ^M from the command line using Perl, do this:

perl -p -i -e "s/\r\n/\n/g" file.name

add a temporary column with a value

You mean staticly define a value, like this:

SELECT field1, 
       field2,
       'example' AS newfield
  FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

How to open a file / browse dialog using javascript?

Here's is a way of doing it without any Javascript and it's also compatible with any browser.


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

Also, if you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

How to get first N elements of a list in C#?

To take first 5 elements better use expression like this one:

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);

or

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);

It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.

class MyList : IEnumerable<int>
{

    int maxCount = 0;

    public int RequestCount
    {
        get;
        private set;
    }
    public MyList(int maxCount)
    {
        this.maxCount = maxCount;
    }
    public void Reset()
    {
        RequestCount = 0;
    }
    #region IEnumerable<int> Members

    public IEnumerator<int> GetEnumerator()
    {
        int i = 0;
        while (i < maxCount)
        {
            RequestCount++;
            yield return i++;
        }
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    #endregion
}
class Program
{
    static void Main(string[] args)
    {
        var list = new MyList(15);
        list.Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 5;

        list.Reset();
        list.OrderBy(q => q).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 15;

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
    }
}

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

CSS: Set a background color which is 50% of the width of the window

The most bullet-proof and semantically correct option would be to use fixed-positioned pseudo-element (::after or ::before). Using this technique do not forget to set z-index to elements inside the container. Also mind, that content:"" rule for pseudo-element is needed, otherwise it won't get rendered.

#container {...}

#content::before {
    content:"";
    background-color: #999;
    height: 100%;
    left: 0px;
    position: fixed;
    top: 0px;    
    width: 50%; 
    z-index: 1;
}


#content * {
  position: relative;
  z-index:2;
}

Live example: https://jsfiddle.net/xraymutation/pwz7t6we/16/

Get parent of current directory from Python script

import os def parent_directory(): # Create a relative path to the parent # of the current working directory path = os.getcwd() parent = os.path.dirname(path)

relative_parent = os.path.join(path, parent)

# Return the absolute path of the parent directory
return relative_parent

print(parent_directory())

How can I get the current page name in WordPress?

This seems to be the easiest to use:

<?php single_post_title(); ?>

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!

Set selected radio from radio group with a value

$('input[name="mygroup"]').val([5])

How to rename HTML "browse" button of an input type=file?

<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
    var fileinput = document.getElementById("browse");
    fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>

<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="text" id="filename" readonly="true"/>
<input type="button" value="Click to select file" id="fakeBrowse" onclick="HandleBrowseClick();"/>

http://jsfiddle.net/J8ekg/

How to set time to midnight for current day?

Only need to set it to

DateTime.Now.Date

Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();

It shows

"2017-04-08 00:00:00"

on my machine.

Rounding float in Ruby

For ruby 1.8.7 you could add the following to your code:

class Float
    alias oldround:round
    def round(precision = nil)
        if precision.nil?
            return self
        else
            return ((self * 10**precision).oldround.to_f) / (10**precision)
        end 
    end 
end

JUnit: how to avoid "no runnable methods" in test utils classes

What about adding an empty test method to these classes?

public void avoidAnnoyingErrorMessageWhenRunningTestsInAnt() {
    assertTrue(true); // do nothing;
}

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';

Node.js global variables

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

Use a JavaScript file and then use module exports.

Example:

File globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

var globals = require('globals'); // << globals.js path
globals.domain // << Domain.

Not able to start Genymotion device

Try this: Remove virtual device in Genymotion and Add again the same or other device. (you will lose your settings and apps in that device)

How to debug when Kubernetes nodes are in 'Not Ready' state

First, describe nodes and see if it reports anything:

$ kubectl describe nodes

Look for conditions, capacity and allocatable:

Conditions:
  Type              Status
  ----              ------
  OutOfDisk         False
  MemoryPressure    False
  DiskPressure      False
  Ready             True
Capacity:
 cpu:       2
 memory:    2052588Ki
 pods:      110
Allocatable:
 cpu:       2
 memory:    1950188Ki
 pods:      110

If everything is alright here, SSH into the node and observe kubelet logs to see if it reports anything. Like certificate erros, authentication errors etc.

If kubelet is running as a systemd service, you can use

$ journalctl -u kubelet

How to get selenium to wait for ajax response?

Below is my code for fetch. Took me while researching because jQuery.active doesn't work with fetch. Here is the answer helped me proxy fetch, but its only for ajax not fetch mock for selenium

public static void customPatchXMLHttpRequest(WebDriver driver) {
    try {
        if (driver instanceof JavascriptExecutor) {
            JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
            Object numberOfAjaxConnections = jsDriver.executeScript("return window.openHTTPs");
            if (numberOfAjaxConnections instanceof Long) {
                return;
            }
            String script = "  (function() {" + "var oldFetch = fetch;"
                    + "window.openHTTPs = 0; console.log('starting xhttps');" + "fetch = function(input,init ){ "
                    + "window.openHTTPs++; "

                    + "return oldFetch(input,init).then( function (response) {"
                    + "      if (response.status >= 200 && response.status < 300) {"
                    + "          window.openHTTPs--;  console.log('Call completed. Remaining active calls: '+ window.openHTTPs); return response;"
                    + "      } else {"
                    + "          window.openHTTPs--; console.log('Call fails. Remaining active calls: ' + window.openHTTPs);  return response;"
                    + "      };})" + "};" + "var oldOpen = XMLHttpRequest.prototype.open;"
                    + "XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {"
                    + "window.openHTTPs++; console.log('xml ajax called');"
                    + "this.addEventListener('readystatechange', function() {" + "if(this.readyState == 4) {"
                    + "window.openHTTPs--; console.log('xml ajax complete');" + "}" + "}, false);"
                    + "oldOpen.call(this, method, url, async, user, pass);" + "}" +

                    "})();";
            jsDriver.executeScript(script);
        } else {
            System.out.println("Web driver: " + driver + " cannot execute javascript");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

Convert String array to ArrayList

Use this code for that,

import java.util.Arrays;  
import java.util.List;  
import java.util.ArrayList;  

public class StringArrayTest {

   public static void main(String[] args) {  
      String[] words = {"ace", "boom", "crew", "dog", "eon"};  

      List<String> wordList = Arrays.asList(words);  

      for (String e : wordList) {  
         System.out.println(e);  
      }  
   }  
}

Validating parameters to a Bash script

one liner Bash argument validation, with and without directory validation

Here are some methods that have worked for me. You can use them in either the global script namespace (if in the global namespace, you can't reference the function builtin variables)

quick and dirty one liner

: ${1?' You forgot to supply a directory name'}

output:

./my_script: line 279: 1: You forgot to supply a directory name

Fancier - supply function name and usage

${1? ERROR Function: ${FUNCNAME[0]}() Usage: " ${FUNCNAME[0]} directory_name"}

output:

./my_script: line 288: 1:  ERROR Function: deleteFolders() Usage:  deleteFolders directory_name

Add complex validation logic without cluttering your current function

Add the following line within the function or script that receives the argument.

: ${1?'forgot to supply a directory name'} && validate $1 || die 'Please supply a valid directory'

You can then create a validation function that does something like

validate() {

    #validate input and  & return 1 if failed, 0 if succeed
    if [[ ! -d "$1" ]]; then
        return 1
    fi
}

and a die function that aborts the script on failure

die() { echo "$*" 1>&2 ; exit 1; }

For additional arguments, just add an additional line, replicating the format.

: ${1?' You forgot to supply the first argument'}
: ${2?' You forgot to supply the second argument'}

Detecting when user scrolls to bottom of div with jQuery

In simple DOM usage you can check the condition

element.scrollTop + element.clientHeight == element.scrollHeight

if true then you have reached the end.

How do I make a relative reference to another workbook in Excel?

In Excel, there is a way to embed relative reference to file or directory. You can try type in excel cell : =HYPERLINK("..\Name_of_file_or_folder\","DisplayLinkName")

Win32Exception (0x80004005): The wait operation timed out

I had the same issue. Running exec sp_updatestats did work sometimes, but not always. I decided to use the NOLOCK statement in my queries to speed up the queries. Just add NOLOCK after your FROM clause, e.g.:

SELECT clicks.entryURL, clicks.entryTime, sessions.userID
FROM sessions, clicks WITH (NOLOCK)
WHERE sessions.sessionID = clicks.sessionID AND clicks.entryTime > DATEADD(day, -1, GETDATE())

Read the full article here.

Unicode via CSS :before

Fileformat.info is a pretty good reference for this stuff. In your case, it's already in hex, so the hex value is f066. So you'd do:

content: "\f066";

Understanding the set() function

Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).

If you'd like to sort them, you can simply perform:

sorted(set(y))

which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)

Otherwise, the only thing guaranteed by set is that it makes the elements unique (nothing will be there more than once).

Hope this helps!

AngularJS routing without the hash '#'

In Angular 6, with your router you can use:

RouterModule.forRoot(routes, { useHash: false })

HttpServletRequest - Get query string parameters, no form data

You can use request.getQueryString(),if the query string is like

username=james&password=pwd

To get name you can do this

request.getParameter("username"); 

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Python matplotlib multiple bars

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()

enter image description here

I don't know what's the "y values are also overlapping" means, does the following code solve your problem?

ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

enter image description here

Jquery to open Bootstrap v3 modal of remote url

If using @worldofjr answer in jQuery you are getting error:

e.relatedTarget.data is not a function

you should use:

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

Not that e.relatedTarget if wrapped by $(..)

I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.

How to change 1 char in the string?

I suggest you to use StringBuilder class for it and than parse it to string if you need.

System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();

You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower() it makes new string and your previous string doesn't change.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Here's how I fixed it:

  1. Opened the Install Cerificates.Command.The shell script got executed.
  2. Opened the Python 3.6.5 and typed in nltk.download().The download graphic window opened and all the packages got installed.

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

Click through div to underlying elements

Nope, you can't click ‘through’ an element. You can get the co-ordinates of the click and try to work out what element was underneath the clicked element, but this is really tedious for browsers that don't have document.elementFromPoint. Then you still have to emulate the default action of clicking, which isn't necessarily trivial depending on what elements you have under there.

Since you've got a fully-transparent window area, you'll probably be better off implementing it as separate border elements around the outside, leaving the centre area free of obstruction so you can really just click straight through.

How can I create a table with borders in Android?

To make 1dp collapse-border around every cell without writing a java code and without creating another xml layout with <shape...> tag, you can try this solution:

In <TableLayout...> add android:background="#CCC" and android:paddingTop="1dp" and android:stretchColumns="0"

In <TableRow...> add android:background="#CCC" and android:paddingBottom="1dp" and android:paddingRight="1dp"

In every cell/child in TableRow, i.e. <TextView...> add android:background="#FFF" and android:layout_marginLeft="1dp"

It is very important to follow paddings and margins as described. This solution will draw a 1dp border aka border-collapse property in (X)HTML/CSS.

Background color in <TableLayout...> and <TableRow...> represents a border line color and background in <TextView...> fills a table cell. You can put some padding in cells if necessary.

An example is here:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#CCC"
    android:paddingTop="1dp"
    android:stretchColumns="0"
    android:id="@+id/tlTable01">

    <TableRow
        android:background="#CCC"
        android:paddingBottom="1dp"
        android:paddingRight="1dp">
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:text="Item1"/>
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:gravity="right"
            android:text="123456"/>
    </TableRow>
    <TableRow
        android:background="#CCC"
        android:paddingBottom="1dp"
        android:paddingRight="1dp">
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:text="Item2"/>
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:gravity="right"
            android:text="456789"/>
    </TableRow>
</TableLayout>

Making a Simple Ajax call to controller in asp.net mvc

Use a Razor to dynamically change your URL by calling your action like this:

$.ajax({
    type: "POST",
    url: '@Url.Action("ActionName", "ControllerName")',
    contentType: "application/json; charset=utf-8",
    data: { data: "yourdata" },
    dataType: "json",
    success: function(recData) { alert('Success'); },
    error: function() { alert('A error'); }
});

Tower of Hanoi: Recursive Algorithm

This is code in C++ for Tower of Hanoi, which is recursively called.

#include <iostream>
void toh(int n, char A, char B, char C) {
    if(n == 1) {
        std::cout << "Move Disc 1 from " << A << " to " << C << std::endl;
        return;
    }
    toh(n-1, A, C, B);
    std::cout << "Move Disc " << n << " from " << A << " to " << C <<std::endl;
    toh(n-1, B, A, C);
}
int main() {
    int numberOfDisc;
    char A = 'A', B = 'B', C = 'C';
    std::cout << "Enter the number of disc: ";
    std::cin >> numberOfDisc;
    toh(numberOfDisc,  A, B, C);
    return 0;
}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.

How to configure a HTTP proxy for svn

Have you seen the FAQ entry What if I'm behind a proxy??

... edit your "servers" configuration file to indicate which proxy to use. The files location depends on your operating system. On Linux or Unix it is located in the directory "~/.subversion". On Windows it is in "%APPDATA%\Subversion". (Try "echo %APPDATA%", note this is a hidden directory.)

For me this involved uncommenting and setting the following lines:

#http-proxy-host=my.proxy
#http-proxy-port=80
#http-proxy-username=[username]
#http-proxy-password=[password]

On command line : nano ~/.subversion/servers

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

phpMyAdmin - The MySQL Extension is Missing

At first make sure you have mysql installed properly. You can ensure it just by checking that whether you can access mysql using mysql command promp. So if you mysql is working then probably it is not loading. For that follow the steps given below

First of all, you must find your php.ini. It could be anywhere but if you create a small php file with the

<?php phpinfo(); ?>

script it will tell you where it is. Just look at the path of loaded configuration file. Common places include /etc/apache/, /etc/php4/apache2/php.ini, /etc/php5/apache2/php.ini or even /usr/local/lib/php.ini for Windows it may be C:\Users\username\PHP\php.ini

Edit your server’s php.ini and look for the following line. Remove the ‘;’ from the start of the line and restart Apache. Things should work fine now!

;extension=mysql.so

should become

extension=mysql.so

For windows it will be

;extension=mysql.dll

should become

extension=mysql.dll

Converting string into datetime

I have put together a project that can convert some really neat expressions. Check out timestring.

Here are some examples below:

pip install timestring
>>> import timestring
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm').date
datetime.datetime(2015, 8, 15, 20, 40)
>>> timestring.Range('next week')
<timestring.Range From 03/10/14 00:00:00 to 03/03/14 00:00:00 4496004880>
>>> (timestring.Range('next week').start.date, timestring.Range('next week').end.date)
(datetime.datetime(2014, 3, 10, 0, 0), datetime.datetime(2014, 3, 14, 0, 0))

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

How do I convert a string to a double in Python?

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info

ASP.NET Custom Validator Client side & Server Side validation not firing

Your CustomValidator will only fire when the TextBox isn't empty.

If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.

Note: If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to require the user to enter data in the input control.

EDIT:

If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.

If you don't specify ControlToValidate then your validation functions will be called every time.

This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:

Client Side code (Javascript):

function TextBoxDCountyClient(sender, args) {
    var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
    if (v == '') {
        args.IsValid = false;  // field is empty
    }
    else {
        // do your other validation tests here...
    }
}

Server side code (C#):

protected void TextBoxDTownCity_Validate(
    object source, ServerValidateEventArgs args)
{
    string v = TextBoxDTownCity.Text;
    if (v == string.Empty)
    {
        args.IsValid = false;  // field is empty
    }
    else
    {
        // do your other validation tests here...
    }
}

calculating number of days between 2 columns of dates in data frame

You could find the difference between dates in columns in a data frame by using the function difftime as follows:

df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))

Best way to encode text data for XML in Java?

You could use the Enterprise Security API (ESAPI) library, which provides methods like encodeForXML and encodeForXMLAttribute. Take a look at the documentation of the Encoder interface; it also contains examples of how to create an instance of DefaultEncoder.

Sorting arraylist in alphabetical order (case insensitive)

You need to use custom comparator which will use compareToIgnoreCase, not compareTo.

iPhone SDK on Windows (alternative solutions)

No, you must have an Intel Mac of some sort. I went to Best Buy and got a 24" iMac with 4G RAM for $1499 using their 18 month no interest promotion. I pay a minimum payment of something like $16 a month. As long as I pay the entire thing off within 18 months - no interest. That was the only way I was getting into iPhone development.

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Way to get number of digits in an int?

We can achieve this using a recursive loop

    public static int digitCount(int numberInput, int i) {
        while (numberInput > 0) {
        i++;
        numberInput = numberInput / 10;
        digitCount(numberInput, i);
        }
        return i;
    }

    public static void printString() {
        int numberInput = 1234567;
        int digitCount = digitCount(numberInput, 0);

        System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
    }

Constructors in JavaScript objects

Example here: http://jsfiddle.net/FZ5nC/

Try this template:

<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Name = Name||{};
Name.Space = Name.Space||{};

//============================================================
// Constructor - MUST BE AT TOP OF FILE
//------------------------------------------------------------
Name.Space.ClassName = function Name_Space_ClassName(){}

//============================================================
// Member Functions & Variables
//------------------------------------------------------------
Name.Space.ClassName.prototype = {
  v1: null
 ,v2: null
 ,f1: function Name_Space_ClassName_f1(){}
}

//============================================================
// Static Variables
//------------------------------------------------------------
Name.Space.ClassName.staticVar = 0;

//============================================================
// Static Functions
//------------------------------------------------------------
Name.Space.ClassName.staticFunc = function Name_Space_ClassName_staticFunc(){
}
</script>

You must adjust your namespace if you are defining a static class:

<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Shape = Shape||{};
Shape.Rectangle = Shape.Rectangle||{};
// In previous example, Rectangle was defined in the constructor.
</script>

Example class:

<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Shape = Shape||{};

//============================================================
// Constructor - MUST BE AT TOP OF FILE
//------------------------------------------------------------
Shape.Rectangle = function Shape_Rectangle(width, height, color){
    this.Width = width;
    this.Height = height;
    this.Color = color;
}

//============================================================
// Member Functions & Variables
//------------------------------------------------------------
Shape.Rectangle.prototype = {
  Width: null
 ,Height: null
 ,Color: null
 ,Draw: function Shape_Rectangle_Draw(canvasId, x, y){
    var canvas = document.getElementById(canvasId);
    var context = canvas.getContext("2d");
    context.fillStyle = this.Color;
    context.fillRect(x, y, this.Width, this.Height);
 }
}

//============================================================
// Static Variables
//------------------------------------------------------------
Shape.Rectangle.Sides = 4;

//============================================================
// Static Functions
//------------------------------------------------------------
Shape.Rectangle.CreateSmallBlue = function Shape_Rectangle_CreateSmallBlue(){
    return new Shape.Rectangle(5,8,'#0000ff');
}
Shape.Rectangle.CreateBigRed = function Shape_Rectangle_CreateBigRed(){
    return new Shape.Rectangle(50,25,'#ff0000');
}
</script>

Example instantiation:

<canvas id="painting" width="500" height="500"></canvas>
<script>
alert("A rectangle has "+Shape.Rectangle.Sides+" sides.");

var r1 = new Shape.Rectangle(16, 12, "#aa22cc");
r1.Draw("painting",0, 20);

var r2 = Shape.Rectangle.CreateSmallBlue();
r2.Draw("painting", 0, 0);

Shape.Rectangle.CreateBigRed().Draw("painting", 10, 0);
</script>

Notice functions are defined as A.B = function A_B(). This is to make your script easier to debug. Open Chrome's Inspect Element panel, run this script, and expand the debug backtrace:

<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Fail = Fail||{};

//============================================================
// Static Functions
//------------------------------------------------------------
Fail.Test = function Fail_Test(){
    A.Func.That.Does.Not.Exist();
}

Fail.Test();
</script>

How to get method parameter names?

Here is something I think will work for what you want, using a decorator.

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

Run it, it will yield the following output:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

Unable to connect to any of the specified mysql hosts. C# MySQL

Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)

So stick to the standard format here

Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;

TypeScript typed array usage

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100] as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing as if was a constructor. Since that values is undefined it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100) instead.

You should report this as a bug on CodePlex.

Prevent flex items from overflowing a container

It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width on the offending element/container can put it back in line.

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

Confirm deletion in modal / dialog using Twitter Bootstrap?

I'd realise its a very old question, but since i wondered today for a more efficient method of handling the bootstrap modals. I did some research and found something better then the solutions which are shown above, that can be found at this link:

http://www.petefreitag.com/item/809.cfm

First load the jquery

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');

        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

Then just ask any question/confirmation to href:

<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>

This way the confirmation modal is a lot more universal and so it can easily be re-used on other parts of your website.

Link a .css on another folder

check this quick reminder of file path

Here is all you need to know about relative file paths:

  • Starting with "/" returns to the root directory and starts there
  • Starting with "../" moves one directory backwards and starts there
  • Starting with "../../" moves two directories backwards and starts there (and so on...)
  • To move forward, just start with the first subdirectory and keep moving forward

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

@ViewChild in *ngIf

Working on Angular 8 No need to import ChangeDector

ngIf allows you not to load the element and avoid adding more stress to your application. Here's how I got it running without ChangeDetector

elem: ElementRef;

@ViewChild('elemOnHTML', {static: false}) set elemOnHTML(elemOnHTML: ElementRef) {
    if (!!elemOnHTML) {
      this.elem = elemOnHTML;
    }
}

Then when I change my ngIf value to be truthy I would use setTimeout like this for it to wait only for the next change cycle:

  this.showElem = true;
  console.log(this.elem); // undefined here
  setTimeout(() => {
    console.log(this.elem); // back here through ViewChild set
    this.elem.do();
  });

This also allowed me to avoid using any additional libraries or imports.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I've found a solution for me with Spring and jackson

First specify the filter name in the entity

@Entity
@Table(name = "SECTEUR")
@JsonFilter(ModelJsonFilters.SECTEUR_FILTER)
public class Secteur implements Serializable {

/** Serial UID */
private static final long serialVersionUID = 5697181222899184767L;

/**
 * Unique ID
 */
@Id
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "code", nullable = false, length = 35)
private String code;

/**
 * Identifiant du secteur parent
 */
@JsonView(View.SecteurWithoutChildrens.class)
@Column(name = "id_parent")
private Long idParent;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "id_parent")
private List<Secteur> secteursEnfants = new ArrayList<>(0);

}

Then you can see the constants filters names class with the default FilterProvider used in spring configuration

public class ModelJsonFilters {

public final static String SECTEUR_FILTER = "SecteurFilter";
public final static String APPLICATION_FILTER = "ApplicationFilter";
public final static String SERVICE_FILTER = "ServiceFilter";
public final static String UTILISATEUR_FILTER = "UtilisateurFilter";

public static SimpleFilterProvider getDefaultFilters() {
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAll();
    return new SimpleFilterProvider().setDefaultFilter(theFilter);
}

}

Spring configuration :

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "fr.sodebo")

public class ApiRootConfiguration extends WebMvcConfigurerAdapter {

@Autowired
private EntityManagerFactory entityManagerFactory;


/**
 * config qui permet d'éviter les "Lazy loading Error" au moment de la
 * conversion json par jackson pour les retours des services REST<br>
 * on permet à jackson d'acceder à sessionFactory pour charger ce dont il a
 * besoin
 */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    super.configureMessageConverters(converters);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();

    // config d'hibernate pour la conversion json
    mapper.registerModule(getConfiguredHibernateModule());//

    // inscrit les filtres json
    subscribeFiltersInMapper(mapper);

    // config du comportement de json views
    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    converter.setObjectMapper(mapper);
    converters.add(converter);
}

/**
 * config d'hibernate pour la conversion json
 * 
 * @return Hibernate5Module
 */
private Hibernate5Module getConfiguredHibernateModule() {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    Hibernate5Module module = new Hibernate5Module(sessionFactory);
    module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);

    return module;

}

/**
 * inscrit les filtres json
 * 
 * @param mapper
 */
private void subscribeFiltersInMapper(ObjectMapper mapper) {

    mapper.setFilterProvider(ModelJsonFilters.getDefaultFilters());

}

}

Endly I can specify a specific filter in restConstoller when i need....

@RequestMapping(value = "/{id}/droits/", method = RequestMethod.GET)
public MappingJacksonValue getListDroits(@PathVariable long id) {

    LOGGER.debug("Get all droits of user with id {}", id);

    List<Droit> droits = utilisateurService.findDroitsDeUtilisateur(id);

    MappingJacksonValue value;

    UtilisateurWithSecteurs utilisateurWithSecteurs = droitsUtilisateur.fillLists(droits).get(id);

    value = new MappingJacksonValue(utilisateurWithSecteurs);

    FilterProvider filters = ModelJsonFilters.getDefaultFilters().addFilter(ModelJsonFilters.SECTEUR_FILTER, SimpleBeanPropertyFilter.serializeAllExcept("secteursEnfants")).addFilter(ModelJsonFilters.APPLICATION_FILTER,
            SimpleBeanPropertyFilter.serializeAllExcept("services"));

    value.setFilters(filters);
    return value;

}

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

How can I create a keystore?

This tutorial:

http://techdroid.kbeanie.com/2010/02/sign-your-android-applications-for.html

was very helpful for me the first time I had to create a keystore. It is simple but the instructions on developer.android.com are a little too brief.

The part I was unsure about was where to save and what name to give the keystore file.

I seems it doesn't matter where you put it just be sure to keep it safe and keep a number of backups. I just put it in my app directory

Name the file "something.keystore" where something can be whatever you want. I used app_name.keystore, where app_name was the name of my app.

The next part was what to name the alias. Again it doesn't seem to matter so again I just used the app_name again. Keep the passwords the same as you used before. Fill out the rest of the fields and you are done.

Why is __init__() always called after __new__()?

However, I'm a bit confused as to why __init__ is always called after __new__.

Not much of a reason other than that it just is done that way. __new__ doesn't have the responsibility of initializing the class, some other method does (__call__, possibly-- I don't know for sure).

I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functionality otherwise? (apart from putting the implementation into the __new__ which feels quite hacky).

You could have __init__ do nothing if it's already been initialized, or you could write a new metaclass with a new __call__ that only calls __init__ on new instances, and otherwise just returns __new__(...).

Is there a Google Chrome-only CSS hack?

You could use javascript. The other answers to date seem to also target Safari.

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    alert("You'll only see this in Chrome");
    $('#someID').css('background-position', '10px 20px');
}

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

As biziclop mentioned, some sort of metric space tree would probably be your best option. I have experience using kd-trees and quad trees to do these sorts of range queries and they're amazingly fast; they're also not that hard to write. I'd suggest looking into one of these structures, as they also let you answer other interesting questions like "what's the closest point in my data set to this other point?"

The endpoint reference (EPR) for the Operation not found is

I had this same problem using curl to send a soap request. Solved it by adding "content-type: text/xml" to the http header.

I hope this helps someone.

Why am I getting AttributeError: Object has no attribute

The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error

php variable in html no other way than: <?php echo $var; ?>

There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:

<input type="hidden" name="type" value="<?= $var ?>" >

which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:

<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>

That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.

Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.

Easy way of running the same junit test over and over?

With JUnit 5 I was able to solve this using the @RepeatedTest annotation:

@RepeatedTest(10)
public void testMyCode() {
    //your test code goes here
}

Note that @Test annotation shouldn't be used along with @RepeatedTest.

Send a ping to each IP on a subnet

Broadcast ping:

$ ping 192.168.1.255
PING 192.168.1.255 (192.168.1.255): 56 data bytes
64 bytes from 192.168.1.154: icmp_seq=0 ttl=64 time=0.104 ms
64 bytes from 192.168.1.51: icmp_seq=0 ttl=64 time=2.058 ms (DUP!)
64 bytes from 192.168.1.151: icmp_seq=0 ttl=64 time=2.135 ms (DUP!)
...

(Add a -b option on Linux)

Android studio takes too much memory

Android Studio has recently published an official guide for low-memory machines: Guide

If you are running Android Studio on a machine with less than the recommended specifications (see System Requirements), you can customize the IDE to improve performance on your machine, as follows:

  • Reduce the maximum heap size available to Android Studio: Reduce the maximum heap size for Android Studio to 512Mb.

  • Update Gradle and the Android plugin for Gradle: Update to the latest versions of Gradle and the Android plugin for Gradle to ensure you are taking advantage of the latest improvements for performance.

  • Enable Power Save Mode: Enabling Power Save Mode turns off a number of memory- and battery-intensive background operations, including error highlighting and on-the-fly inspections, autopopup code completion, and automatic incremental background compilation. To turn on Power Save Mode, click File > Power Save Mode.

  • Disable unnecessary lint checks: To change which lint checks Android Studio runs on your code, proceed as follows: Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.In the left pane, expand the Editor section and click Inspections. Click the checkboxes to select or deselect lint checks as appropriate for your project. Click Apply or OK to save your changes.

  • Debug on a physical device: Debugging on an emulator uses more memory than debugging on a physical device, so you can improve overall performance for Android Studio by debugging on a physical device.

  • Include only necessary Google Play Services as dependencies: Including Google Play Services as dependencies in your project increases the amount of memory necessary. Only include necessary dependencies to improve memory usage and performance. For more information, see Add Google Play Services to Your Project.

  • Reduce the maximum heap size available for DEX file compilation: Set the javaMaxHeapSize for DEX file compilation to 200m. For more information, see Improve build times by configuring DEX resources.

  • Do not enable parallel compilation: Android Studio can compile independent modules in parallel, but if you have a low-memory system you should not turn on this feature. To check this setting, proceed as follows: Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog. In the left pane, expand Build, Execution, Deployment and then click Compiler. Ensure that the Compile independent modules in parallel option is unchecked.If you have made a change, click Apply or OK for your change to take effect.

  • Turn on Offline Mode for Gradle: If you have limited bandwitch, turn on Offline Mode to prevent Gradle from attempting to download missing dependencies during your build. When Offline Mode is on, Gradle will issue a build failure if you are missing any dependencies, instead of attempting to download them. To turn on Offline Mode, proceed as follows:

    • Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.

    • In the left pane, expand Build, Execution, Deployment and then click Gradle.

    • Under Global Gradle settings, check the Offline work checkbox.

    • Click Apply or OK for your changes to take effect.

How to find Control in TemplateField of GridView?

Try with below code.

Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.

<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
    OnRowDataBound="mainGrid_RowDataBound"  EmptyDataText="No Data Found.">
    <Columns>
        <asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
                <asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
                <a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
                <input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Handling RowDataBound event,

protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblName = (Label)e.Row.FindControl("lblName");
        LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
        HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
        HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
    }
}

Visual Studio C# IntelliSense not automatically displaying

I'll start off my noting that this hasn't happened since I upgraded my RAM. I was at 4GB and would often have multiple instances of VS open along with SSMS. I have since gone to 8GB and then 16GB.

Here's the steps I go through when I lose intellisense.

If only one file/window appears to be affected, close/reopen that file. If that doesn't work, try below.

In Visual Studio:

  1. Click Tools->Options->Text Editor->All Languages->General
  2. Uncheck "Auto list members"
  3. Uncheck "Parameter information"
  4. Check "Auto list members" (yes, the one you just unchecked)
  5. Check "Parameter information" (again, the one you just unchecked)
  6. Click OK

If this doesn't work, here's a few more steps to try:

  1. Close all VS documents and reopen
  2. If still not working, close/reopen solution
  3. If still not working, restart VS.

For C++ projects:
MSDN has a few things to try: MSDN suggestions

The corrupt .ncb file seems most likely.

From MSDN:

  1. Close the solution.
  2. Delete the .ncb file.
  3. Reopen the solution. (This creates a new .ncb file.)

Notes:

  • This issue does not appear to be specific to C# as C++ and VB users report the same issue

  • Tested in VS 2013/2015

event.preventDefault() vs. return false

When using jQuery, return false is doing 3 separate things when you call it:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

See jQuery Events: Stop (Mis)Using Return False for more information and examples.

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

After many answers that did not work, I finally found a solution when Anonymous access is Disabled on the IIS server. Our server is using Windows authentication, not Kerberos. This is thanks to this blog posting.

No changes were made to web.config.

On the server side, the .SVC file in the ISAPI folder uses MultipleBaseAddressBasicHttpBindingServiceHostFactory

The class attributes of the service are:

[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class InvoiceServices : IInvoiceServices
{
...
}

On the client side, the key that made it work was the http binding security attributes:

EndpointAddress endpoint =
  new EndpointAddress(new Uri("http://SharePointserver/_vti_bin/InvoiceServices.svc"));
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
InvoiceServicesClient myClient = new InvoiceServicesClient(httpBinding, endpoint);
myClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; 

(call service)

I hope this works for you!

How do I convert strings in a Pandas data frame to a 'date' data type?

Another way to do this and this works well if you have multiple columns to convert to datetime.

cols = ['date1','date2']
df[cols] = df[cols].apply(pd.to_datetime)

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

Get class name using jQuery

Be Careful , Perhaps , you have a class and a subclass .

  <div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>

If you use previous solutions , you will have :

myclass mysubclass

So if you want to have the class selector, do the following :

var className = '.'+$('#id').attr('class').split(' ').join('.')

and you will have

.myclass.mysubclass

Now if you want to select all elements that have the same class such as div above :

   var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))

that means

var brothers=$('.myclass.mysubclass')

Update 2018

OR can be implemented with vanilla javascript in 2 lines:

  const { classList } = document.querySelector('#id');
  document.querySelectorAll(`.${Array.from(classList).join('.')}`);

Docker error: invalid reference format: repository name must be lowercase

In my case I was trying to run postgres through docker. Initially I was running as :

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password POSTGRES_USER=test_user POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

I was missing -e after each environment variable. Changing the above command to the one below worked

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password -e POSTGRES_USER=test_user -e POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Spring @PropertySource using YAML

I found a workaround by using @ActiveProfiles("test") and adding an application-test.yml file to src/test/resources.

It ended up looking like this:

@SpringApplicationConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests {

}

The file application-test.yml just contains the properties that I want to override from application.yml (which can be found in src/main/resources).

How to check if that data already exist in the database during update (Mongoose And Express)

In addition to already posted examples, here is another approach using express-async-wrap and asynchronous functions (ES2017).

Router

router.put('/:id/settings/profile', wrap(async function (request, response, next) {
    const username = request.body.username
    const email = request.body.email
    const userWithEmail = await userService.findUserByEmail(email)
    if (userWithEmail) {
        return response.status(409).send({message: 'Email is already taken.'})
    }
    const userWithUsername = await userService.findUserByUsername(username)
    if (userWithUsername) {
        return response.status(409).send({message: 'Username is already taken.'})
    }
    const user = await userService.updateProfileSettings(userId, username, email)
    return response.status(200).json({user: user})
}))

UserService

async function updateProfileSettings (userId, username, email) {
    try {
        return User.findOneAndUpdate({'_id': userId}, {
            $set: {
                'username': username,
                'auth.email': email
            }
        }, {new: true})
    } catch (error) {
        throw new Error(`Unable to update user with id "${userId}".`)
    }
}

async function findUserByEmail (email) {
    try {
        return User.findOne({'auth.email': email.toLowerCase()})
    } catch (error) {
        throw new Error(`Unable to connect to the database.`)
    }
}

async function findUserByUsername (username) {
    try {
        return User.findOne({'username': username})
    } catch (error) {
        throw new Error(`Unable to connect to the database.`)
    }
}

// other methods

export default {
    updateProfileSettings,
    findUserByEmail,
    findUserByUsername,
}

Resources

async function

await

express-async-wrap

Const in JavaScript: when to use it and is it necessary?

const is not immutable.

From the MDN:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

Pandas DataFrame to List of Lists

We can use the DataFrame.iterrows() function to iterate over each of the rows of the given Dataframe and construct a list out of the data of each row:

# Empty list 
row_list =[] 

# Iterate over each row 
for index, rows in df.iterrows(): 
    # Create list for the current row 
    my_list =[rows.Date, rows.Event, rows.Cost] 

    # append the list to the final list 
    row_list.append(my_list) 

# Print 
print(row_list) 

We can successfully extract each row of the given data frame into a list

Null pointer Exception on .setOnClickListener

Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.

Load HTML page dynamically into div with jQuery

I think this would do it:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){

         $(".divlink").click(function(){
         $("#content").attr("src" , $(this).attr("ref"));

});

});
</script>
</head>
<body>
<iframe id="content"></iframe>

<a href="#" ref="page1.html" class="divlink" >Page 1</a><br />
<a href="#" ref="page2.html" class="divlink" >Page 2</a><br />
<a href="#" ref="page3.html" class="divlink" >Page 3</a><br />
<a href="#" ref="page4.html" class="divlink" >Page 4</a><br />
<a href="#" ref="page5.html" class="divlink" >Page 5</a><br />
<a href="#" ref="page6.html" class="divlink" >Page 6</a><br />
</body>
</html>

By the way if you can avoid Jquery, you can just use the target attribute of <a> element:

<html>
<body>
<iframe id="content" name="content"></iframe>

<a href="page1.html" target="content" >Page 1</a><br />
<a href="page2.html" target="content" >Page 2</a><br />
<a href="page3.html" target="content" >Page 3</a><br />
<a href="page4.html" target="content" >Page 4</a><br />
<a href="page5.html" target="content" >Page 5</a><br />
<a href="page6.html" target="content" >Page 6</a><br />
</body>
</html> 

Remote Procedure call failed with sql server 2008 R2

This error appears to happen when .mof files (Managed Object Format (MOF)) don’t get installed and registered correctly during set-up. To resolve this issue, I executed the following mofcomp command in command prompt to re-register the *.mof files:

mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof"

This one worked for me

Ignore mapping one property with Automapper

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

to be used as follow :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

thanks to Can Gencer for the tip :)

source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

'cannot find or open the pdb file' Visual Studio C++ 2013

There are no problems here this is perfectly normal - it shows informational messages about what debug-info was loaded (and which wasn't) and also that your program executed and exited normally - a zero return code means success.

If you don't see anything on the screen thry running your program with CTRL-F5 instead of just F5.

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

For me following worked:

in directive declare it like this:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            myFunction: '=',
        },
        templateUrl: 'myDirective.html'
    };
})  

In directive template use it in following way:

<select ng-change="myFunction(selectedAmount)">

And then when you use the directive, pass the function like this:

<data-my-directive
    data-my-function="setSelectedAmount">
</data-my-directive>

You pass the function by its declaration and it is called from directive and parameters are populated.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

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

or

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

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

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

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

how to display a javascript var in html body

Try This...

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var number = "123";_x000D_
      document.getElementById("myText").innerHTML = number;_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
  <h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

YouTube Autoplay not working

It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes

<iframe id="existing-iframe-example"
          width="640" height="360"
          src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
          frameborder="0"
          style="border: solid 4px #37474F"
          ></iframe>

Update :

Audio/Video Updates in Chrome 73

Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa

Convert a list of characters into a string

h = ['a','b','c','d','e','f']
g = ''
for f in h:
    g = g + f

>>> g
'abcdef'

CMake complains "The CXX compiler identification is unknown"

Run apt-get install build-essential on your system.

This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.

See this page for more info.

Command not found error in Bash variable assignment

I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.

#!/bin/bash
STR = "Hello World"
echo $STR

Didn't work because of the spaces around the equal sign. If you were to run...

#!/bin/bash
STR="Hello World"
echo $STR

It would work

How do I restart my C# WinForm Application?

A much simpler approach that worked for me is:

Application.Restart();
Environment.Exit(0);

This preserves the command-line arguments and works despite event handlers that would normally prevent the application from closing.

The Restart() call tries to exit, starts a new instance anyway and returns. The Exit() call then terminates the process without giving any event handlers a chance to run. There is a very brief period in which both processes are running, which is not a problem in my case, but maybe in other cases.

The exit code 0 in Environment.Exit(0); specifies a clean shutdown. You can also exit with 1 to specify an error occurred.

How to run python script in webpage

Well, OP didn't say server or client side, so i will just leave this here in case someone like me is looking for client side:

http://skulpt.org/using.html

Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just a simple JS.

Java ArrayList of Doubles

Try this:

List<Double> list = Arrays.asList(1.38, 2.56, 4.3);

which returns a fixed size list.

If you need an expandable list, pass this result to the ArrayList constructor:

List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));

How to round an average to 2 decimal places in PostgreSQL?

you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

This answer is not for DevOps/ system admin guys, but for them who are using IDE like eclipse and facing invalid LOC header (bad signature) issue.

You can force update the maven dependencies, as follows:

enter image description here

enter image description here

How to determine if a point is in a 2D triangle?

The easiest way and it works with all types of triangles is simply determine the angles of the P point A, B , C points angles. If any of the angles are bigger than 180.0 degree then it is outside, if 180.0 then it is on the circumference and if acos cheating on you and less than 180.0 then it is inside.Take a look for understanding http://math-physics-psychology.blogspot.hu/2015/01/earlish-determination-that-point-is.html

Find and replace strings in vim on multiple lines

As a side note, instead of having to type in the line numbers, just highlight the lines where you want to find/replace in one of the visual modes:

  • VISUAL mode (V)
  • VISUAL BLOCK mode (Ctrl+V)
  • VISUAL LINE mode (Shift+V, works best in your case)

Once you selected the lines to replace, type your command:

:s/<search_string>/<replace_string>/g

You'll note that the range '<,'> will be inserted automatically for you:

:'<,'>s/<search_string>/<replace_string>/g

Here '< simply means first highlighted line, and '> means last highlighted line.

Note that the behaviour might be unexpected when in NORMAL mode: '< and '> point to the start and end of the last highlight done in one of the VISUAL modes. Instead, in NORMAL mode, the special line number . can be used, which simply means current line. Hence, you can find/replace only on the current line like this:

:.s/<search_string>/<replace_string>/g

Another thing to note is that inserting a second : between the range and the find/replace command does no harm, in other words, these commands will still work:

:'<,'>:s/<search_string>/<replace_string>/g
:.:s/<search_string>/<replace_string>/g

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

Counting repeated elements in an integer array

private static void getRepeatedNumbers() {

    int [] numArray = {2,5,3,8,1,2,8,3,3,1,5,7,8,12,134};
    Set<Integer> nums = new HashSet<Integer>();
    
    for (int i =0; i<numArray.length; i++) {
        if(nums.contains(numArray[i]))
            continue;
            int count =1;
            for (int j = i+1; j < numArray.length; j++) {
                if(numArray[i] == numArray[j]) {
                    count++;
                }
                    
            }
            System.out.println("The "+numArray[i]+ " is repeated "+count+" times.");
            nums.add(numArray[i]);
        }
    }
    

OkHttp Post Body as JSON

In okhttp v4.* I got it working that way


// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

// ...

json : String = "..."

val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)

// go on with Request.Builder() etc

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Even after this my code is working fine , so i just removed all warning messages with this statement at line 1 .

<?php error_reporting(E_ERROR); ?>

Can I add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

 public static class ConfigurationManagerWrapper
 {
      public static ConfigurationSection GetSection( string name )
      {
         return ConfigurationManager.GetSection( name );
      }

      .....

      public static ConfigurationSection GetWidgetSection()
      {
          return GetSection( "widgets" );
      }
 }

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

MySQL: is a SELECT statement case sensitive?

You can try it. hope it will be useful.

SELECT * FROM `table` WHERE `Value` COLLATE latin1_general_cs = "IAreSavage"

Auto-redirect to another HTML page

<meta http-equiv="refresh" content="5; url=http://example.com/">

Table overflowing outside of div

overflow-x: auto;
overflow-y : hidden;

Apply the styling above to the parent div.

Bash ignoring error for a particular command

Don't stop and also save exit status

Just in case if you want your script not to stop if a particular command fails and you also want to save error code of failed command:

set -e
EXIT_CODE=0
command || EXIT_CODE=$?
echo $EXIT_CODE

How to add \newpage in Rmarkdown in a smart way?

In the initialization chunk I define a function

pagebreak <- function() {
  if(knitr::is_latex_output())
    return("\\newpage")
  else
    return('<div style="page-break-before: always;" />')
}

In the markdown part where I want to insert a page break, I type

`r pagebreak()`

Convert Char to String in C

I use this to convert char to string (an example) :

char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);

Round a double to 2 decimal places

In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?

You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;  
(int) 20034.56 = 20034;  
20034/100.0 = 200.34;

You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.

SQL Server date format yyyymmdd

Assuming your "date" column is not actually a date.

Select convert(varchar(8),cast('12/24/2016' as date),112)

or

Select format(cast('12/24/2016' as date),'yyyyMMdd')

Returns

20161224

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Pandas "Can only compare identically-labeled DataFrame objects" error

Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

One solution is to sort the index first (Note: some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

Note: == is also sensitive to the order of columns, so you may have to use sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

Note: This can still raise (if the index/columns aren't identically labelled after sorting).

javascript scroll event for iPhone/iPad?

Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.

So, if you register the scroll event handler and check window.pageYOffset inside that event handler, everything works just fine.

Initialise numpy array of unknown length

Since y is an iterable I really do not see why the calls to append:

a = np.array(list(y))

will do and it's much faster:

import timeit

print timeit.timeit('list(s)', 's=set(x for x in xrange(1000))')
# 23.952975494633154

print timeit.timeit("""li=[]
for x in s: li.append(x)""", 's=set(x for x in xrange(1000))')
# 189.3826994248866

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

import an array in python

Another option is numpy.genfromtxt, e.g:

import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")

This will make data a numpy array with as many rows and columns as are in your file

How can the error 'Client found response content type of 'text/html'.. be interpreted

I had got this error after changing the web service return type and SoapDocumentMethod.

Initially it was:

[WebMethod]
public int Foo()
{
    return 0;
}

I decided to make it fire and forget type like this:

[SoapDocumentMethod(OneWay = true)]
[WebMethod]
public void Foo()
{
    return;
}

In such cases, updating the web reference helped.

To update a web service reference:

  • Expand solution explorer
  • Locate Web References - this will be visible only if you have added a web service reference in your project
  • Right click and click update web reference

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

How do I upgrade PHP in Mac OS X?

Upgrading to Snow Leopard won't solve the your primary problem of keeping PHP up to date. Apple doesn't always keep the third party software that it bundles up to date with OS updates. And relying on Apple to get you the bug fix / security update you need is asking for trouble.

Additionally, I would recommend installing through MacPorts (and doing the config necessary to use it instead of Apple's PHP) rather than try to upgrade the Apple supplied PHP in place. Anything you do to /usr/bin risks being overwritten by some future Apple update.

SQL Server Management Studio, how to get execution time down to milliseconds

You can try this code:

USE AdventureWorks2012;
GO
SET STATISTICS TIME ON;
GO
SELECT ProductID, StartDate, EndDate, StandardCost 
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
GO
SET STATISTICS TIME OFF;
GO

Remove Item in Dictionary based on Value

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
    {
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
        {
            src.Remove(item.Key);
        }
    }

How to remove a web site from google analytics

Updated Answer (July 22, 2015)

The solution to delete an Account/Property/View is still very similar to @Pranav ?'s answer. Google has just moved a few things around, so I thought I would update.

Step #1

Click Admin Tab at the top of the page

Step #1

Step #2

Once you are on the Admin Page, You need to decide if you want to delete the Account, Property, or View. Make sure to select the desired Account, Property, or View from the Drop Down Menu.

In the following pictures, I will show you how to delete the Account, which removes all information including Properties and Views under that particular account.

Click Account Settings to remove Account, Property Settings to remove Property, and View Settings to remove View.

Step #2

Step #3

On Account Settings, you will notice a button 'Move to Trash Can'. You will click this to remove the Account, Property or View. You will have to verify Moving the Account to the Trash Can on the next page/picture.

Step #3

Step #4

When you have verified this is the account you want to delete, go ahead and select 'Trash Account'.

Note: When you Trash an Account it moves all the information to Admin/Account/Trash Can, where it can be recovered within 1 month. Keep in mind that every Account has its own Trash Can. Once that time has lapsed the Account, Property or View will be deleted FOREVER!

Step #4

Hope this helps someone in the future, since I just struggled trying to figure it out even though its pretty simple now.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

Angular 2: How to style host element of the component?

Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Difference between DOMContentLoaded and load events

Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.

// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);

function doStuff(){
    //
}
if(isIE){
    // play it safe, very few users, exec ur JS when all resources are loaded
    window.onload=function(){doStuff();}
} else {
    // add event listener to trigger your function when DOMContentLoaded
    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',doStuff);
    } else {
        // DOMContentLoaded already loaded, so better trigger your function
        doStuff();
    }
}

"unmappable character for encoding" warning in Java

Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling

javac -encoding UTF-8 HelloWorld.java

and also You can add this compile option to your IDE ex: Intellij idea
(File>settings>Java Compiler) add as additional command line parameter

enter image description here

-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used. (DOC)

What is getattr() exactly and how do I use it?

setattr()

We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.

getattr()

With getattr we retrive these values

For example

Employee = type("Employee", (object,), dict())

employee = Employee()

# Set salary to 1000
setattr(employee,"salary", 1000 )

# Get the Salary
value = getattr(employee, "salary")

print(value)

Is there a "between" function in C#?

Here's a complete class.

/// <summary>
/// An extension class for the between operation
/// name pattern IsBetweenXX where X = I -> Inclusive, X = E -> Exclusive
/// <a href="https://stackoverflow.com/a/13470099/37055"></a>
/// </summary>
public static class BetweenExtensions
{

    /// <summary>
    /// Between check <![CDATA[min <= value <= max]]> 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenII<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);
    }

    /// <summary>
    /// Between check <![CDATA[min < value <= max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenEI<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) <= 0);
    }

    /// <summary>
    /// between check <![CDATA[min <= value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenIE<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) < 0);
    }

    /// <summary>
    /// between check <![CDATA[min < value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>

    public static bool IsBetweenEE<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) < 0);
    }
}

plus some unit test code

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethodIsBeetween()
    {
        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.0));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(4.9, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.1));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEE(4.9, 5.1));

        Assert.IsFalse(5.0.IsBetweenII(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEI(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenIE(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEE(5.1, 4.9));

    }
}

Notification not showing in Oreo

private void addNotification() {
                NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                // Add as notification
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                {
                NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                nChannel.enableLights(true);
                assert manager != null;
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
                manager.createNotificationChannel(nChannel);
                }
                assert manager != null;
                manager.notify(0, builder.build());
    }

How to make Bootstrap carousel slider use mobile left/right swipe

UPDATE:

I came up with this solution when I was pretty new to web design. Now that I am older and wiser, the answer Liam gave seems to be a better option. See the next top answer; it is a more productive solution.

I worked on a project recently and this example worked perfectly. I am giving you the link below.

First you have to add jQuery mobile:

http://jquerymobile.com/

This adds the touch functionality, and then you just have to make events such as swipe:

<script>
$(document).ready(function() {
   $("#myCarousel").swiperight(function() {
      $(this).carousel('prev');
    });
   $("#myCarousel").swipeleft(function() {
      $(this).carousel('next');
   });
});
</script>

The link is below, where you can find the tutorial I used:

http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/

Remote JMX connection

I know this thread is pretty old, but there's an additional option that will help greatly. See here: https://realjenius.com/2012/11/21/java7-jmx-tunneling-freedom/

-Dcom.sun.management.jmxremote.rmi.port=1099

Should __init__() call the parent class's __init__()?

If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

>>> class C(object):
        def __init__(self):
            self.b = 1


>>> class D(C):
        def __init__(self):
            super().__init__() # in Python 2 use super(D, self).__init__()
            self.a = 1


>>> class E(C):
        def __init__(self):
            self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b  # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b  # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    e.b  # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'

__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

I rarely use __new__. I do all the initialization in __init__.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

How to format numbers by prepending 0 to single-digit numbers?

Here's the easiest solution I found:-

let num = 9; // any number between 0 & 99
let result = ( '0' + num ).substr( -2 );

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

How to disable HTML links

Try the element:

$(td).find('a').attr('disabled', 'disabled');

Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.

Firefox doesn't seem to play nice. This example works:

<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>

$('#a1').attr('disabled', 'disabled');

$(document).on('click', 'a', function(e) {
    if ($(this).attr('disabled') == 'disabled') {
        e.preventDefault();
    }
});

Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.

Self-reference for cell, column and row in worksheet functions

My current Column is calculated by:

Method 1:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))

Method 2:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)

My current Row is calculated by:

=RIGHT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ROW()))

so an indirect link to Sheet2!My Column but a different row, specified in Column A on my row is:

Method 1:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))&INDIRECT(ADDRESS(ROW(),1,4,1)))

Method 2:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)&INDIRECT(ADDRESS(ROW(),1,4,1)))

So if A6=3 and my row is 6 and my Col is C returns contents of "Sheet2!C3"

So if A7=1 and my row is 7 and my Col is D returns contents of "Sheet2!D1"

SELECT query with CASE condition and SUM()

I don't think you need a case statement. You just need to update your where clause and make sure you have correct parentheses to group the clauses.

SELECT Sum(CAMount) as PaymentAmount 
from TableOrderPayment 
where (CStatus = 'Active' AND CPaymentType = 'Cash') 
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())

The answers posted before mine assume that CDate<=SYSDATETIME() is also appropriate for Cash payment type as well. I think I split mine out so it only looks for that clause for check payments.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

Making a request to a RESTful API using python

Using requests and json makes it simple.

  1. Call the API
  2. Assuming the API returns a JSON, parse the JSON object into a Python dict using json.loads function
  3. Loop through the dict to extract information.

Requests module provides you useful function to loop for success and failure.

if(Response.ok): will help help you determine if your API call is successful (Response code - 200)

Response.raise_for_status() will help you fetch the http code that is returned from the API.

Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()

How to deal with a slow SecureRandom generator?

If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random where that's available.

If you want a PRNG, do something like this:

SecureRandom.getInstance("SHA1PRNG");

What strings are supported depends on the SecureRandom SPI provider, but you can enumerate them using Security.getProviders() and Provider.getService().

Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.

The exception is that if you don't call setSeed() before getting data, then the PRNG will seed itself once the first time you call next() or nextBytes(). It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.

Wireshark vs Firebug vs Fiddler - pros and cons?

Fiddler is the winner every time when comparing to Charles.

The "customize rules" feature of fiddler is unparalleled in any http debugger. The ability to write code to manipulate http requests and responses on-the-fly is invaluable to me and the work I do in web development.

There are so many features to fiddler that charles just does not have, and likely won't ever have. Fiddler is light-years ahead.

Turn a string into a valid filename?

This whitelist approach (ie, allowing only the chars present in valid_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with Windows file naming limitations and thus be a lot more complex.

>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'

Regular Expression Match to test for a valid year

In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.

Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.

This will work for exact matching using non-capturing groups:

(?:19|20)\d{2}