Programs & Examples On #Jbcrypt

The Java implementation of OpenBSD's Blowfish password hashing code.

How do I generate a SALT in Java for Salted-Hash?

Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.

The process is:

  • you create a salt with getNextSalt
  • you ask the user his password and use the hash method to generate a salted and hashed password. The method returns a byte[] which you can save as is in a database with the salt
  • to authenticate a user, you ask his password, retrieve the salt and hashed password from the database and use the isExpectedPassword method to check that the details match
/**
 * A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique
 * salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is
 * still considered robust and <a href="https://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>.
 * The hashed value has 256 bits.
 */
public class Passwords {

  private static final Random RANDOM = new SecureRandom();
  private static final int ITERATIONS = 10000;
  private static final int KEY_LENGTH = 256;

  /**
   * static utility class
   */
  private Passwords() { }

  /**
   * Returns a random salt to be used to hash a password.
   *
   * @return a 16 bytes random salt
   */
  public static byte[] getNextSalt() {
    byte[] salt = new byte[16];
    RANDOM.nextBytes(salt);
    return salt;
  }

  /**
   * Returns a salted and hashed password using the provided hash.<br>
   * Note - side effect: the password is destroyed (the char[] is filled with zeros)
   *
   * @param password the password to be hashed
   * @param salt     a 16 bytes salt, ideally obtained with the getNextSalt method
   *
   * @return the hashed password with a pinch of salt
   */
  public static byte[] hash(char[] password, byte[] salt) {
    PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
    Arrays.fill(password, Character.MIN_VALUE);
    try {
      SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      return skf.generateSecret(spec).getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
    } finally {
      spec.clearPassword();
    }
  }

  /**
   * Returns true if the given password and salt match the hashed value, false otherwise.<br>
   * Note - side effect: the password is destroyed (the char[] is filled with zeros)
   *
   * @param password     the password to check
   * @param salt         the salt used to hash the password
   * @param expectedHash the expected hashed value of the password
   *
   * @return true if the given password and salt match the hashed value, false otherwise
   */
  public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) {
    byte[] pwdHash = hash(password, salt);
    Arrays.fill(password, Character.MIN_VALUE);
    if (pwdHash.length != expectedHash.length) return false;
    for (int i = 0; i < pwdHash.length; i++) {
      if (pwdHash[i] != expectedHash[i]) return false;
    }
    return true;
  }

  /**
   * Generates a random password of a given length, using letters and digits.
   *
   * @param length the length of the password
   *
   * @return a random password
   */
  public static String generateRandomPassword(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      int c = RANDOM.nextInt(62);
      if (c <= 9) {
        sb.append(String.valueOf(c));
      } else if (c < 36) {
        sb.append((char) ('a' + c - 10));
      } else {
        sb.append((char) ('A' + c - 36));
      }
    }
    return sb.toString();
  }
}

What column type/length should I use for storing a Bcrypt hashed password in a Database?

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

Add Auto-Increment ID to existing table?

Try this

ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT;

for an existing primary key

How do I make an HTML text box show a hint when empty?

$('input[value="text"]').focus(function(){ 
if ($(this).attr('class')=='hint') 
{ 
   $(this).removeClass('hint'); 
   $(this).val(''); 
}
});

$('input[value="text"]').blur(function(){
  if($(this).val() == '')
  {
    $(this).addClass('hint');
    $(this).val($(this).attr('title'));
  } 
});

<input type="text" value="" title="Default Watermark Text">

How to find the index of an element in an array in Java?

here is another example and how indexOf is working.

public int indexOf(Object target) {
    for (int i = 0; i < array.length; i++) {
        if (equals(target, array[i])) {
            return i;
        }
    }
    return -1;
}

Haversine Formula in Python (Bearing and Distance between two GPS points)

You can try the following:

from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253

jQuery select change event get selected option

Another and short way to get value of selected value,

$('#selectElement').on('change',function(){
   var selectedVal = $(this).val();
                       ^^^^  ^^^^ -> presents #selectElement selected value 
                         |
                         v
               presents #selectElement, 
});

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You need to add the following line:

using FootballLeagueSystem;

into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login.

At the moment the compiler can't find the Login class.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Finding and removing non ascii characters from an Oracle Varchar2

Answer given by Francisco Hayoz is the best. Don't use pl/sql functions if sql can do it for you.

Here is the simple test in Oracle 11.2.03

select s
     , regexp_replace(s,'[^'||chr(1)||'-'||chr(127)||']','') "rep ^1-127"
     , dump(regexp_replace(s,'['||chr(127)||'-'||chr(225)||']','')) "rep 127-255"
from (
select listagg(c, '') within group (order by c) s
  from (select 127+level l,chr(127+level) c from dual connect by level < 129))

And "rep 127-255" is

Typ=1 Len=30: 226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255

i.e for some reason this version of Oracle does not replace char(226) and above. Using '['||chr(127)||'-'||chr(225)||']' gives the desired result. If you need to replace other characters just add them to the regex above or use nested replace|regexp_replace if the replacement is different then '' (null string).

How to force Sequential Javascript Execution?

In your example, the first function does actually complete before the second function is started. setTimeout does not hold execution of the function until the timeout is reached, it will simply start a timer in the background and execute your alert statement after the specified time.

There is no native way of doing a "sleep" in JavaScript. You could write a loop that checks for the time, but that will put a lot of strain on the client. You could also do the Synchronous AJAX call, as emacsian described, but that will put extra load on your server. Your best bet is really to avoid this, which should be simple enough for most cases once you understand how setTimeout works.

.includes() not working in Internet Explorer

It works for me:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

i use this in linux :

sed -i 's/utf8mb4/utf8/g' your_file.sql
sed -i 's/utf8_unicode_ci/utf8_general_ci/g' your_file.sql
sed -i 's/utf8_unicode_520_ci/utf8_general_ci/g' your_file.sql

then restore your_file.sql

mysql -u yourdBUser -p yourdBPasswd yourdB < your_file.sql

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

It seems your VirtualBox installation doesn't work correctly. You should try to reinstall/upgrade VirtualBox so that during the installation process it fixes this "Interface not found" issue.

Check if property has attribute

You can use the Attribute.IsDefined method

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:

PropertyInfo[] props = typeof(YourClass).GetProperties();

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Git blame -- prior commits?

Building on DavidN's answer and I want to follow renamed file:

LINE=8 FILE=Info.plist; for commit in $(git log --format='%h%%' --name-only --follow -- $FILE | xargs echo | perl -pe 's/\%\s/,/g'); do hash=$(echo $commit | cut -f1 -d ','); fileMayRenamed=$(echo $commit | cut -f2 -d ','); git blame -n -L$LINE,+1 $hash -- $fileMayRenamed; done | sed '$!N; /^\(.*\)\n\1$/!P; D'

ref: nicely display file rename history in git log

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Check with jquery if div has overflowing elements

This is the jQuery solution that worked for me. offsetWidth etc. didn't work.

function is_overflowing(element, extra_width) {
    return element.position().left + element.width() + extra_width > element.parent().width();
}

If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent()). position is relative to the parent. I've also included extra_width because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:

var extra_width = 0;
$(".tag:visible").each(function() {
    if (!$(this).find("img:visible").width()) {
        // tag image might not be visible at this point,
        // so we add its future width to the overflow calculation
        // the goal is to hide tags that do not fit one line
        extra_width += 28;
    }
    if (is_overflowing($(this), extra_width)) {
        $(this).hide();
    }
});

Hope this helps.

How to change the commit author for one specific commit?

The answers in the question to which you linked are good answers and cover your situation (the other question is more general since it involves rewriting multiple commits).

As an excuse to try out git filter-branch, I wrote a script to rewrite the Author Name and/or Author Email for a given commit:

#!/bin/sh

#
# Change the author name and/or email of a single commit.
#
# change-author [-f] commit-to-change [branch-to-rewrite [new-name [new-email]]]
#
#     If -f is supplied it is passed to "git filter-branch".
#
#     If <branch-to-rewrite> is not provided or is empty HEAD will be used.
#     Use "--all" or a space separated list (e.g. "master next") to rewrite
#     multiple branches.
#
#     If <new-name> (or <new-email>) is not provided or is empty, the normal
#     user.name (user.email) Git configuration value will be used.
#

force=''
if test "x$1" = "x-f"; then
    force='-f'
    shift
fi

die() {
    printf '%s\n' "$@"
    exit 128
}
targ="$(git rev-parse --verify "$1" 2>/dev/null)" || die "$1 is not a commit"
br="${2:-HEAD}"

TARG_COMMIT="$targ"
TARG_NAME="${3-}"
TARG_EMAIL="${4-}"
export TARG_COMMIT TARG_NAME TARG_EMAIL

filt='

    if test "$GIT_COMMIT" = "$TARG_COMMIT"; then
        if test -n "$TARG_EMAIL"; then
            GIT_AUTHOR_EMAIL="$TARG_EMAIL"
            export GIT_AUTHOR_EMAIL
        else
            unset GIT_AUTHOR_EMAIL
        fi
        if test -n "$TARG_NAME"; then
            GIT_AUTHOR_NAME="$TARG_NAME"
            export GIT_AUTHOR_NAME
        else
            unset GIT_AUTHOR_NAME
        fi
    fi

'

git filter-branch $force --env-filter "$filt" -- $br

Fitting a Normal distribution to 1D data

You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt


# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')

# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f,  std = %.2f" % (mu, std)
plt.title(title)

plt.show()

Here's the plot generated by the script:

Plot

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

Bind failed: Address already in use

Address already in use means that the port you are trying to allocate for your current execution is already occupied/allocated to some other process.

If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)

So if you encounter this error, just see which application/process is using the port.

In linux try using netstat -tulpn. This command will list down a process list with all running processes.

Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.

Anyway you can stop the process which uses your port and let your application take it.

If you are in linux environment try,

  • Use netstat -tulpn to display the processes
  • kill <pid> This will terminate the process

If you are using windows,

  • Use netstat -a -o -n to check for the port usages
  • Use taskkill /F /PID <pid> to kill that process

Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python foo.py > file

SelectedValue vs SelectedItem.Value of DropDownList

One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.

Difference between filter and filter_by in SQLAlchemy

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name=="john")

How to emulate GPS location in the Android Emulator?

If you're using Eclipse, go to Window->Open Perspective->DDMS, then type one in Location Controls and hit Send.

Eclipse gives “Java was started but returned exit code 13”

if you have updated your jdk to 7 you are most likely to face this problem.

This happens mainly due to:

  1. incompatible sdk and jdk versions
  2. using a 32 bit java version for your 64 bit eclipse JVM (programfilex86-java)

WHAT YOU HAVE TO DO : firstly check the eclipse.ini file to see if you have a path that is pointing to your jdk it should look something like this

-vm    
C:\Program Files\Java\blah\blah\blah\javaw.exe    

if not then locate the jdk 7 javaw.exe file
sample :

C:\Program Files\Java\jdk1.7.0_45\jre\bin\javaw.exe 

paste -vm and the path below it into your eclipse.ini file

-vm  
C:\Program Files\Java\jdk1.7.0_45\jre\bin\javaw.exe        

make sure that you type the above just before the -vmargs and after the OpenFile

Can't import database through phpmyadmin file size too large

You have three options:

  • Use another way to get the file on the server, and use a mysql client on the server
  • Use another client to connect to the server and load the data
  • Change your PHP settings to allow such huge files. Don't forget to increment the execution time as well.

Center a popup window on screen?

_x000D_
_x000D_
.center{_x000D_
    left: 50%;_x000D_
    max-width: 350px;_x000D_
    padding: 15px;_x000D_
    text-align:center;_x000D_
    position: relative;_x000D_
    transform: translateX(-50%);_x000D_
    -moz-transform: translateX(-50%);_x000D_
    -webkit-transform: translateX(-50%);_x000D_
    -ms-transform: translateX(-50%);_x000D_
    -o-transform: translateX(-50%);   _x000D_
}
_x000D_
_x000D_
_x000D_

How do I drop table variables in SQL-Server? Should I even do this?

Here is a solution

Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)

SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
    EXEC sp_executesql @SQL;

Works fine on SQL Server 2014 Christophe

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

HTML input fields does not get focus when clicked

If you are faced this problem while using canvas with DOM on mobile devices, the answer of Ashwin G worked for me perfectly, but I did it through javascript

var element = document.getElementById("myinputfield");
element.onclick = element.select();

After, everything worked flawlessly.

How to disable horizontal scrolling of UIScrollView?

since iOS7 use

self.automaticallyAdjustsScrollViewInsets = NO;

//and create you page scroller with 3 pages

    self.pageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.pageView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height)];
    [self.pageView setShowsVerticalScrollIndicator:NO];
    [self.pageView setPagingEnabled:YES];
    [self.view addSubview:self.pageView];

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

Uninstall all installed gems, in OSX?

gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax

grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo in case you get permission issues.

How to change Maven local repository in eclipse

In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

Maven User Settings dialog

It's the second file input; the first with information in it.

If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>

You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

What is the difference between a stored procedure and a view?

  1. A VIEW is a dynamic query where you can use a "WHERE"-Clause
  2. A stored procedure is a fixed data selection, which returns a predefined result
  3. Nor a view, nor a stored procedure allocate memory. Only a materialized view
  4. A TABLE is just one ENTITY, a view can collect data from different ENTITIES or TABLES

How to get streaming url from online streaming radio station

Shahar's answer was really helpful, but I found it quite tedious to do this all myself, so I made a nifty little Python program:

import re
import urllib2
import string
url1 = raw_input("Please enter a URL from Tunein Radio: ");
open_file = urllib2.urlopen(url1);
raw_file = open_file.read();
API_key = re.findall(r"StreamUrl\":\"(.*?),",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
use_key = urllib2.urlopen(str(API_key[0]));
key_content = use_key.read();
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print "I found " + str(total) + " streams.";
for element in raw_stream_url:
    print "Stream #" + str(i + 1);
    print "Stream stats:";
    print "Bandwidth: " + str(bandwidth[i]) + " kilobytes per second."
    print "Reliability: " + str(reliability[i]) + "%"
    print "HasPlaylist: " + str(isPlaylist[i]) + "."
    print "Stream codec: " + str(codec[i]) + "."
    print "This audio stream is " + tipe[i].lower() + "."
    print "Pure streaming URL: " + str(raw_stream_url[i]) + ".";
    i = i + 1
raw_input("Press enter to close TMUS.")

It's basically Shahar's solution automated.

Convert Mercurial project to Git

You can try using fast-export:

cd ~
git clone https://github.com/frej/fast-export.git
git init git_repo
cd git_repo
~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD

Also have a look at this SO question.


If you're using Mercurial version below 4.6, adrihanu got your back:

As he stated in his comment: "In case you use Mercurial < 4.6 and you got "revsymbol not found" error. You need to update your Mercurial or downgrade fast-export by running git checkout tags/v180317 inside ~/fast-export directory.".

How to set value of input text using jQuery

In pure js it will be simpler

EmployeeId.value = 'fgg';

_x000D_
_x000D_
EmployeeId.value = 'fgg';
_x000D_
<div class="editor-label">_x000D_
  <label for="EmployeeId">Employee Number</label>_x000D_
</div>_x000D_
_x000D_
<div class="editor-field textBoxEmployeeNumber">_x000D_
  <input class="text-box single-line" data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="text" value="" />_x000D_
  _x000D_
  <span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I also faced the same problem. Whenever we or webdriver opens up the FF browser will check for the updates if any. In that case, i will try to update during the execution time and then you will be getting the error even if it is updated properly just because you have not update the Selenium version appropriately.

Navigate to "http://docs.seleniumhq.org/download/" and download the latest version. Now go and check, the problem would be resolved, indeed. :)

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

Rename multiple files by replacing a particular pattern in the filenames using a shell script

for file in *.jpg ; do mv $file ${file//IMG/myVacation} ; done

Again assuming that all your image files have the string "IMG" and you want to replace "IMG" with "myVacation".

With bash you can directly convert the string with parameter expansion.

Example: if the file is IMG_327.jpg, the mv command will be executed as if you do mv IMG_327.jpg myVacation_327.jpg. And this will be done for each file found in the directory matching *.jpg.

IMG_001.jpg -> myVacation_001.jpg
IMG_002.jpg -> myVacation_002.jpg
IMG_1023.jpg -> myVacation_1023.jpg
etcetera...

Why do we need virtual functions in C++?

If the base class is Base, and a derived class is Der, you can have a Base *p pointer which actually points to an instance of Der. When you call p->foo();, if foo is not virtual, then Base's version of it executes, ignoring the fact that p actually points to a Der. If foo is virtual, p->foo() executes the "leafmost" override of foo, fully taking into account the actual class of the pointed-to item. So the difference between virtual and non-virtual is actually pretty crucial: the former allows runtime polymorphism, the core concept of OO programming, while the latter does not.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Uncaught Typeerror: cannot read property 'innerHTML' of null

Update:

The question doesn't ask for jquery. So lets do it without jquery:

document.addEventListener("DOMContentLoaded", function(event) { 
    //Do work
});

Note this method will not work on IE8.

Old Answer:

You are calling this script before DOM is ready. If you write this code into jquery's $(function() method it will work.

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

REST API using POST instead of GET

You can't use the API using POST or GET if they are not build to call using these methods separetly. Like if your API say

/service/function?param1=value1&param2=value2

is accessed by using GET method. Then you can not call it using POST method if it is not specified as POST method by its creator. If you do that you may got 405 Method not allowed status.

Generally in POST method you need to send the content in body with specified format which is described in content-type header for ex. application/json for json data.

And after that the request body gets deserialized at server end. So you need to pass the serialized data from the client and it is decided by the service developer.

But in general terms GET is used when server returns some data to the client and have not any impact on server whereas POST is used to create some resource on server. So generally it should not be same.

Shuffling a list of objects

It took me some time to get that too. But the documentation for shuffle is very clear:

shuffle list x in place; return None.

So you shouldn't print(random.shuffle(b)). Instead do random.shuffle(b) and then print(b).

How to access PHP session variables from jQuery function in a .js file?

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $( "#progressbar" ).progressbar({
            value: percent
        });
    };
})(jQuery);

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Change Default branch in gitlab

To change default branch in GitLab:
1. Settings > General > General project settings > Expand
2. Default Branch > Change your project default branch
3. Save changes

enter image description here

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

position: fixed doesn't work on iPad and iPhone

The simple way to fix this problem just types transform property for your element. and it will be fixed. Happy Coding :-)

.classname{
  position: fixed;
  transform: translate3d(0,0,0);
}

Also you can try his way as well this is also work fine.

.classname{
      position: -webkit-sticky;
    }

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

Determine what user created objects in SQL Server

If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":

enter image description here

You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

Set cellpadding and cellspacing in CSS?

For tables, cellspacing and cellpadding are obsolete in HTML 5.

Now for cellspacing you have to use border-spacing. And for cellpadding you have to use border-collapse.

And make sure you don't use this in your HTML5 code. Always try to use these values in a CSS 3 file.

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Check if enum exists in Java

If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.

Sample code:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    private static final Map<String, SampleEnum> nameToValueMap =
        new HashMap<String, SampleEnum>();

    static {
        for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
            nameToValueMap.put(value.name(), value);
        }
    }

    public static SampleEnum forName(String name) {
        return nameToValueMap.get(name);
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    // We know we'll never mutate this, so we can keep
    // a local copy.
    private static final SampleEnum[] copyOfValues = values();

    public static SampleEnum forName(String name) {
        for (SampleEnum value : copyOfValues) {
            if (value.name().equals(name)) {
                return value;
            }
        }
        return null;
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

"This operation requires IIS integrated pipeline mode."

GitHub solution solved the problem for me by adding

  • Global.asax.cs: Set AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start:
  • Manually add the X-Frame-Options header in Application_BeginRequest

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

How do I test for an empty JavaScript object?

    let jsObject = JSON.parse(JSON.stringify(obj), (key, value) => {
                if (value === null ||
                    value === '' ||
                    (value.constructor === Object && Object.entries(value).length === 0) ||
                    (value.constructor === Array && value.length === 0)) {
                    return undefined
                }
                return value
            })

This will filter out all the invalid fields recursively.

How to get the current loop index when using Iterator?

just do something like this:

        ListIterator<String> it = list1.listIterator();
        int index = -1;
        while (it.hasNext()) {
            index++;
            String value = it.next();
            //At this point the index can be checked for the current element.

        }

Configuring angularjs with eclipse IDE

Configuration worked with Eclipse Mars 4.5 version.

1) Install Eclipse Mars 4.5 from https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/mars2 This comes with Tern and embedded Node.js server

2) Install AngularJS Eclipse plugin from Eclipse Marketplace

3) Configure node.js server to the embedded nodejs server within Eclipse (found in the eclipse plugins folder) at Windows-> Preferences -> JavaScript -> Tern -> Server -> node.js. No extra configurations are required.

4) Test configuration in a html or javascript file. https://github.com/angelozerr/angularjs-eclipse

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

What's the pythonic way to use getters and setters?

You can use the magic methods __getattribute__ and __setattr__.

class MyClass:
    def __init__(self, attrvalue):
        self.myattr = attrvalue
    def __getattribute__(self, attr):
        if attr == "myattr":
            #Getter for myattr
    def __setattr__(self, attr):
        if attr == "myattr":
            #Setter for myattr

Be aware that __getattr__ and __getattribute__ are not the same. __getattr__ is only invoked when the attribute is not found.

How to return a value from __init__ in Python?

You can just set it to a class variable and read it from the main program:

class Foo:
    def __init__(self):
        #Do your stuff here
        self.returncode = 42
bar = Foo()
baz = bar.returncode

Is it possible to decompile a compiled .pyc file into a .py file?

You may try Easy Python Decompiler. It's based on Decompyle++ and Uncompyle2. It's supports decompiling python versions 1.0-3.3

Note: I am the author of the above tool.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I would honestly suggest neither. I would use a stylized <button></button> for that behavior.

_x000D_
_x000D_
button.link {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  background-color: transparent;_x000D_
  cursor: pointer;_x000D_
  border: 0;_x000D_
  padding: 0;_x000D_
  color: #00f;_x000D_
  text-decoration: underline;_x000D_
  font: inherit;_x000D_
}
_x000D_
<p>A button that looks like a <button type="button" class="link">link</button>.</p>
_x000D_
_x000D_
_x000D_

This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.


If you MUST use an A element, use javascript:void(0); for reasons already mentioned.

  • Will always intercept in case your onclick event fails.
  • Will not have errant load calls happen, or trigger other events based on a hash change
  • The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.

NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.

PHP function overloading

Sadly there is no overload in PHP as it is done in C#. But i have a little trick. I declare arguments with default null values and check them in a function. That way my function can do different things depending on arguments. Below is simple example:

public function query($queryString, $class = null) //second arg. is optional
{
    $query = $this->dbLink->prepare($queryString);
    $query->execute();

    //if there is second argument method does different thing
    if (!is_null($class)) { 
        $query->setFetchMode(PDO::FETCH_CLASS, $class);
    }

    return $query->fetchAll();
}

//This loads rows in to array of class
$Result = $this->query($queryString, "SomeClass");
//This loads rows as standard arrays
$Result = $this->query($queryString);

Leading zeros for Int in Swift

Swift 3.0+

Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation

extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}

Usage:

let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

How do I find out if first character of a string is a number?

Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:

public boolean isLeadingDigit(final String value){
    final char c = value.charAt(0);
    return (c >= '0' && c <= '9');
}

Convert base64 string to ArrayBuffer

Try this:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

Spring cron expression for every after 30 minutes

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

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

This worked for me.

Google Map API v3 — set bounds and center

Got everything sorted - see the last few lines for code - (bounds.extend(myLatLng); map.fitBounds(bounds);)

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(
    document.getElementById("map_canvas"),
    myOptions);
  setMarkers(map, beaches);
}

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 161.259052, 5],
  ['Cronulla Beach', -36.028249, 153.157507, 3],
  ['Manly Beach', -31.80010128657071, 151.38747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.159302, 1]
];

function setMarkers(map, locations) {
  var image = new google.maps.MarkerImage('images/beachflag.png',
    new google.maps.Size(20, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
    new google.maps.Size(37, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shape = {
    coord: [1, 1, 1, 20, 18, 20, 18 , 1],
    type: 'poly'
  };
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      shadow: shadow,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
    bounds.extend(myLatLng);
  }
  map.fitBounds(bounds);
}

String vs. StringBuilder

My approach has always been to use StringBuilder when concatenating 4 or more strings OR When I don't know how may concatenations are to take place.

Good performance related article on it here

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

Upper memory limit?

Not only are you reading the whole of each file into memory, but also you laboriously replicate the information in a table called list_of_lines.

You have a secondary problem: your choices of variable names severely obfuscate what you are doing.

Here is your script rewritten with the readlines() caper removed and with meaningful names:

file_A1_B1 = open("A1_B1_100000.txt", "r")
file_A2_B2 = open("A2_B2_100000.txt", "r")
file_A1_B2 = open("A1_B2_100000.txt", "r")
file_A2_B1 = open("A2_B1_100000.txt", "r")
file_write = open ("average_generations.txt", "w")
mutation_average = open("mutation_average", "w") # not used
files = [file_A2_B2,file_A2_B2,file_A1_B2,file_A2_B1]
for afile in files:
    table = []
    for aline in afile:
        values = aline.split('\t')
        values.remove('\n') # why?
        table.append(values)
    row_count = len(table)
    row0length = len(table[0])
    print_counter = 4
    for column_index in range(row0length):
        column_total = 0
        for row_index in range(row_count):
            number = float(table[row_index][column_index])
            column_total = column_total + number
        column_average = column_total/row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1
file_write.write('\n')

It rapidly becomes apparent that (1) you are calculating column averages (2) the obfuscation led some others to think you were calculating row averages.

As you are calculating column averages, no output is required until the end of each file, and the amount of extra memory actually required is proportional to the number of columns.

Here is a revised version of the outer loop code:

for afile in files:
    for row_count, aline in enumerate(afile, start=1):
        values = aline.split('\t')
        values.remove('\n') # why?
        fvalues = map(float, values)
        if row_count == 1:
            row0length = len(fvalues)
            column_index_range = range(row0length)
            column_totals = fvalues
        else:
            assert len(fvalues) == row0length
            for column_index in column_index_range:
                column_totals[column_index] += fvalues[column_index]
    print_counter = 4
    for column_index in column_index_range:
        column_average = column_totals[column_index] / row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1

How to generate range of numbers from 0 to n in ES2015 only?

I also found one more intuitive way using Array.from:

const range = n => Array.from({length: n}, (value, key) => key)

Now this range function will return all the numbers starting from 0 to n-1

A modified version of the range to support start and end is:

const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);

EDIT As suggested by @marco6, you can put this as a static method if it suits your use case

Array.range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);

and use it as

Array.range(3, 9)

Display filename before matching line

How about this, which I managed to achieve thanks, in part, to this post.

You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE), inside several directories with a pattern (e.g. /logsapp1, /logsapp2). Each file has a pattern you want to grep (e.g. "init time"), and you want to have the "init time" of each file, but knowing which file it belongs to.

find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt

Then the outputfilename.txt would be something like

./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms

In general

find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt

Explanation:

find command will search the filenames based in the pattern

then, pipe xargs -I{} will redirect the find output to the {}

which will be the input for grep ""pattern" {}

Then the trick to make grep display the filenames \dev\null

and finally, write the output in file with tee outputfile.txt

This worked for me in grep version 9.0.5 build 1989.

What is the size of column of int(11) in mysql in bytes?

In MySQL integer int(11) has size is 4 bytes which equals 32 bit.

Signed value is : -2^(32-1) to 0 to 2^(32-1)-1 = -2147483648 to 0 to 2147483647

Unsigned values is : 0 to 2^32-1 = 0 to 4294967295

How to know that a string starts/ends with a specific string in jQuery?

One option is to use regular expressions:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

HTML anchor tag with Javascript onclick event

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How can I escape white space in a bash loop list?

Just had a simple variant problem... Convert files of typed .flv to .mp3 (yawn).

for file in read `find . *.flv`; do ffmpeg -i ${file} -acodec copy ${file}.mp3;done

recursively find all the Macintosh user flash files and turn them into audio (copy, no transcode) ... it's like the while above, noting that read instead of just 'for file in ' will escape.

How to escape a while loop in C#

Sorry for the necro-add, but there's something I really wanted to insert that's missing in the existing answers (for anyone like me stumbling onto this question via google): refactor your code. Not only will it make it easier to read/maintain, but it'll often remove these types of control-routing issues entirely.

Here's what I'd lean towards if I had to program the function above:

private const string CatchupLineToIndicateLogDump = "mp4:production/CATCHUP/";
private const string BatchFileLocation = "Command.bat";

private void CheckLog()
{
    while (true)
    {
        Thread.Sleep(5000);
        if (System.IO.File.Exists(BatchFileLocation))
        {
            if (doesFileContainStr(BatchFileLocation, CatchupLineToIndicateLogDump))
            {
                RemoveLogAndDump();
                return;
            }
        }
    }
}

private bool doesFileContainStr(string FileLoc, string StrToCheckFor)
{
  // ... code for checking the existing of a string within a file
  // (and returning back whether the string was found.)
}

private void RemoveLogAndDump()
{
  // ... your code to call RemoveEXELog and kick off test.exe
}

Java 8 lambda get and remove element from list

The below logic is the solution without modifying the original list

List<String> str1 = new ArrayList<String>();
str1.add("A");
str1.add("B");
str1.add("C");
str1.add("D");

List<String> str2 = new ArrayList<String>();
str2.add("D");
str2.add("E");

List<String> str3 = str1.stream()
                        .filter(item -> !str2.contains(item))
                        .collect(Collectors.toList());

str1 // ["A", "B", "C", "D"]
str2 // ["D", "E"]
str3 // ["A", "B", "C"]

SQL Server query - Selecting COUNT(*) with DISTINCT

This is a good example where you want to get count of Pincode which stored in the last of address field

SELECT DISTINCT
    RIGHT (address, 6),
    count(*) AS count
FROM
    datafile
WHERE
    address IS NOT NULL
GROUP BY
    RIGHT (address, 6)

Effect of NOLOCK hint in SELECT statements

It will be faster because it doesnt have to wait for locks

Original purpose of <input type="hidden">?

I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.

Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.

This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):

type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".

<input type=hidden name=customerid value="c2415-345-8563">

While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.

UIView frame, bounds and center

Since the question I asked has been seen many times I will provide a detailed answer of it. Feel free to modify it if you want to add more correct content.

First a recap on the question: frame, bounds and center and theirs relationships.

Frame A view's frame (CGRect) is the position of its rectangle in the superview's coordinate system. By default it starts at the top left.

Bounds A view's bounds (CGRect) expresses a view rectangle in its own coordinate system.

Center A center is a CGPoint expressed in terms of the superview's coordinate system and it determines the position of the exact center point of the view.

Taken from UIView + position these are the relationships (they don't work in code since they are informal equations) among the previous properties:

  • frame.origin = center - (bounds.size / 2.0)

  • center = frame.origin + (bounds.size / 2.0)

  • frame.size = bounds.size

NOTE: These relationships do not apply if views are rotated. For further info, I will suggest you take a look at the following image taken from The Kitchen Drawer based on Stanford CS193p course. Credits goes to @Rhubarb.

Frame, bounds and center

Using the frame allows you to reposition and/or resize a view within its superview. Usually can be used from a superview, for example, when you create a specific subview. For example:

// view1 will be positioned at x = 30, y = 20 starting the top left corner of [self view]
// [self view] could be the view managed by a UIViewController
UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

When you need the coordinates to drawing inside a view you usually refer to bounds. A typical example could be to draw within a view a subview as an inset of the first. Drawing the subview requires to know the bounds of the superview. For example:

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

UIView* view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];    
view2.backgroundColor = [UIColor yellowColor];

[view1 addSubview:view2];

Different behaviours happen when you change the bounds of a view. For example, if you change the bounds size, the frame changes (and vice versa). The change happens around the center of the view. Use the code below and see what happens:

NSLog(@"Old Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"Old Center %@", NSStringFromCGPoint(view2.center));    

CGRect frame = view2.bounds;
frame.size.height += 20.0f;
frame.size.width += 20.0f;
view2.bounds = frame;

NSLog(@"New Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"New Center %@", NSStringFromCGPoint(view2.center));

Furthermore, if you change bounds origin you change the origin of its internal coordinate system. By default the origin is at (0.0, 0.0) (top left corner). For example, if you change the origin for view1 you can see (comment the previous code if you want) that now the top left corner for view2 touches the view1 one. The motivation is quite simple. You say to view1 that its top left corner now is at the position (20.0, 20.0) but since view2's frame origin starts from (20.0, 20.0), they will coincide.

CGRect frame = view1.bounds;
frame.origin.x += 20.0f;
frame.origin.y += 20.0f;
view1.bounds = frame; 

The origin represents the view's position within its superview but describes the position of the bounds center.

Finally, bounds and origin are not related concepts. Both allow to derive the frame of a view (See previous equations).

View1's case study

Here is what happens when using the following snippet.

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

NSLog(@"view1's frame is: %@", NSStringFromCGRect([view1 frame]));
NSLog(@"view1's bounds is: %@", NSStringFromCGRect([view1 bounds]));
NSLog(@"view1's center is: %@", NSStringFromCGPoint([view1 center]));

The relative image.

enter image description here

This instead what happens if I change [self view] bounds like the following.

// previous code here...
CGRect rect = [[self view] bounds];
rect.origin.x += 30.0f;
rect.origin.y += 20.0f;
[[self view] setBounds:rect];

The relative image.

enter image description here

Here you say to [self view] that its top left corner now is at the position (30.0, 20.0) but since view1's frame origin starts from (30.0, 20.0), they will coincide.

Additional references (to update with other references if you want)

About clipsToBounds (source Apple doc)

Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

In other words, if a view's frame is (0, 0, 100, 100) and its subview is (90, 90, 30, 30), you will see only a part of that subview. The latter won't exceed the bounds of the parent view.

masksToBounds is equivalent to clipsToBounds. Instead to a UIView, this property is applied to a CALayer. Under the hood, clipsToBounds calls masksToBounds. For further references take a look to How is the relation between UIView's clipsToBounds and CALayer's masksToBounds?.

JSON.parse vs. eval()

JSON is just a subset of JavaScript. But eval evaluates the full JavaScript language and not just the subset that’s JSON.

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

How to check if a column exists in a datatable

For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.

 private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
    {
        bool iscolumnExist = true;
        try
        {
            if (null != tableNameToCheck && tableNameToCheck.Columns != null)
            {
                foreach (string columnName in columnsNames)
                {
                    if (!tableNameToCheck.Columns.Contains(columnName))
                    {
                        iscolumnExist = false;
                        break;
                    }
                }
            }
            else
            {
                iscolumnExist = false;
            }
        }            
        catch (Exception ex)
        {

        }
        return iscolumnExist;
    }

Javascript seconds to minutes and seconds

try this : Converting Second to HOURS, MIN and SEC.

function convertTime(sec) {
    var hours = Math.floor(sec/3600);
    (hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
    var min = Math.floor(sec/60);
    (min >= 1) ? sec = sec - (min*60) : min = '00';
    (sec < 1) ? sec='00' : void 0;

    (min.toString().length == 1) ? min = '0'+min : void 0;    
    (sec.toString().length == 1) ? sec = '0'+sec : void 0;    

    return hours+':'+min+':'+sec;
}

Please initialize the log4j system properly warning

What worked for me is to create a log4j properties file (you can find many examples over the net) and place it in properties folder in your project directory (create this folder if not exicts). The right click on the folder and Build Path->Use as Source Folder.

Hope it helps!

How to get rid of the "No bootable medium found!" error in Virtual Box?

FIX 1:

Step1: Go to settings > then select the following configuration(Disable Floppy)

Config

Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.

Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.

FIX 2:

Go to Settings > And Perform the following:

Config1

FIX 3:

Try Fix 1 & 2 together..

forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}

How to open a folder in Windows Explorer from VBA?

I just used this and it works fine:

System.Diagnostics.Process.Start("C:/Users/Admin/files");

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I solved this by installing the correct version of Jquery that my project required using npm

How to clear textarea on click?

This is your javascript file:

function yourFunction(){
     document.getElementById('yourid').value = "";
};

This is the html file:

    <textarea id="yourid" >
    Your text inside the textarea
    </textarea>
    <button onClick="yourFunction();">
     Your button Name
     </button>

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

SQL Server 2017 does introduce a new aggregate function

STRING_AGG ( expression, separator).

Concatenates the values of string expressions and places separator values between them. The separator is not added at the end of string.

The concatenated elements can be ordered by appending WITHIN GROUP (ORDER BY some_expression)

For versions 2005-2016 I typically use the XML method in the accepted answer.

This can fail in some circumstances however. e.g. if the data to be concatenated contains CHAR(29) you see

FOR XML could not serialize the data ... because it contains a character (0x001D) which is not allowed in XML.

A more robust method that can deal with all characters would be to use a CLR aggregate. However applying an ordering to the concatenated elements is more difficult with this approach.

The method of assigning to a variable is not guaranteed and should be avoided in production code.

MySQL query String contains

Mine is using LOCATE in mysql:

LOCATE(substr,str), LOCATE(substr,str,pos)

This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.

In your case:

mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");

How to parse Excel (XLS) file in Javascript/HTML5

include the xslx.js , xlsx.full.min.js , jszip.js

add a onchange event handler to the file input

function showDataExcel(event)
{
            var file = event.target.files[0];
            var reader = new FileReader();
            var excelData = [];
            reader.onload = function (event) {
                var data = event.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

                    for (var i = 0; i < XL_row_object.length; i++)
                    {
                        excelData.push(XL_row_object[i]["your column name"]);

                    }

                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    alert(excelData);
                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);

}

How do I install jmeter on a Mac?

jmeter is now just installed with

brew install jmeter

This version includes the plugin manager that you can use to download the additional plugins.

OUTDATED:

If you want to include the plugins (JMeterPlugins Standard, Extras, ExtrasLibs, WebDriver and Hadoop) use:

brew install jmeter --with-plugins

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

How can I check if a checkbox is checked?

This should work

    function validate() {
        if ($('#remeber').is(':checked')) {
            alert("checked");
        } else {
            alert("You didn't check it! Let me check it for you.");
        }
    }

How to leave/exit/deactivate a Python virtualenv

Use deactivate.

(my_env) user@user:~/my_env$ deactivate
user@user-Lenovo-E40-80:~/my_env$ 

Note, (my_env) is gone.

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

How to generate Javadoc HTML files in Eclipse?

This is a supplement answer related to the OP:

An easy and reliable solution to add Javadocs comments in Eclipse:

  1. Go to Help > Eclipse Marketplace....
  2. Find "JAutodoc".
  3. Install it and restart Eclipse.

To use this tool, right-click on class and click on JAutodoc.

CSS3 transition events

If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:

function once = function(object,event,callback){
    var handle={};

    var eventNames=event.split(" ");

    var cbWrapper=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
        callback.apply(this,arguments);
    };

    eventNames.forEach(function(e){
        object.addEventListener(e,cbWrapper,false);
    });

    handle.cancel=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
    };

    return handle;
};

Usage:

var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
   //do something
});

then if you wish to cancel at some point you can still do it with

handler.cancel();

It's good for other event usages as well :)

How to save an activity state using save instance state?

To get activity state data stored in onCreate(), first you have to save data in savedInstanceState by overriding SaveInstanceState(Bundle savedInstanceState) method.

When activity destroy SaveInstanceState(Bundle savedInstanceState) method gets called and there you save data you want to save. And you get same in onCreate() when activity restart.(savedInstanceState wont be null since you have saved some data in it before activity get destroyed)

Deny direct access to all .php files except index.php

<Files ~ "^.*\.([Pp][Hh][Pp])">
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

java.net.ConnectException: Connection refused

I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

  1. $ sudo vmq-admin listener show

to show the list o allowed ips and ports for vernemq

  1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

to add any ip and your new port. now u should be able to connect without any problem.

Hope it solves your problem. enter image description here

angular ng-repeat in reverse

You can reverse by the $index parameter

<tr ng-repeat="friend in friends | orderBy:'$index':true">

jQuery: Currency Format Number

Here is the cool regex style for digit grouping:

thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

How to add a filter class in Spring Boot?

If you use Spring Boot + Spring Security, you can do that in the security configuration.

In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired FilterDependency filterDependency;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(
                new MyFilter(filterDependency),
                UsernamePasswordAuthenticationFilter.class);
    }
}

And the filter class

class MyFilter extends OncePerRequestFilter  {
    private final FilterDependency filterDependency;

    public MyFilter(FilterDependency filterDependency) {
        this.filterDependency = filterDependency;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain)
        throws ServletException, IOException {
       // filter
       filterChain.doFilter(request, response);
    }
}

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

Why is using the JavaScript eval function a bad idea?

Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.

Mercurial — revert back to old version and continue from there

The answers above were most useful and I learned a lot. However, for my needs the succinct answer is:

hg revert --all --rev ${1}

hg commit -m "Restoring branch ${1} as default"

where ${1} is the number of the revision or the name of the branch. These two lines are actually part of a bash script, but they work fine on their own if you want to do it manually.

This is useful if you need to add a hot fix to a release branch, but need to build from default (until we get our CI tools right and able to build from branches and later do away with release branches as well).

Accessing private member variables from prototype-defined functions

Here's something I've come up with while trying to find most simple solution for this problem, perhaps it could be useful to someone. I'm new to javascript, so there might well be some issues with the code.

// pseudo-class definition scope
(function () {

    // this is used to identify 'friend' functions defined within this scope,
    // while not being able to forge valid parameter for GetContext() 
    // to gain 'private' access from outside
    var _scope = new (function () { })();
    // -----------------------------------------------------------------

    // pseudo-class definition
    this.Something = function (x) {

        // 'private' members are wrapped into context object,
        // it can be also created with a function
        var _ctx = Object.seal({

            // actual private members
            Name: null,
            Number: null,

            Somefunc: function () {
                console.log('Something(' + this.Name + ').Somefunc(): number = ' + this.Number);
            }
        });
        // -----------------------------------------------------------------

        // function below needs to be defined in every class
        // to allow limited access from prototype
        this.GetContext = function (scope) {

            if (scope !== _scope) throw 'access';
            return _ctx;
        }
        // -----------------------------------------------------------------

        {
            // initialization code, if any
            _ctx.Name = (x !== 'undefined') ? x : 'default';
            _ctx.Number = 0;

            Object.freeze(this);
        }
    }
    // -----------------------------------------------------------------

    // prototype is defined only once
    this.Something.prototype = Object.freeze({

        // public accessors for 'private' field
        get Number() { return this.GetContext(_scope).Number; },
        set Number(v) { this.GetContext(_scope).Number = v; },

        // public function making use of some private fields
        Test: function () {

            var _ctx = this.GetContext(_scope);
            // access 'private' field
            console.log('Something(' + _ctx.Name + ').Test(): ' + _ctx.Number);
            // call 'private' func
            _ctx.Somefunc();
        }
    });
    // -----------------------------------------------------------------

    // wrap is used to hide _scope value and group definitions
}).call(this);

function _A(cond) { if (cond !== true) throw new Error('assert failed'); }
// -----------------------------------------------------------------

function test_smth() {

    console.clear();

    var smth1 = new Something('first'),
      smth2 = new Something('second');

    //_A(false);
    _A(smth1.Test === smth2.Test);

    smth1.Number = 3;
    smth2.Number = 5;
    console.log('smth1.Number: ' + smth1.Number + ', smth2.Number: ' + smth2.Number);

    smth1.Number = 2;
    smth2.Number = 6;

    smth1.Test();
    smth2.Test();

    try {
        var ctx = smth1.GetContext();
    } catch (err) {
        console.log('error: ' + err);
    }
}

test_smth();

Remove last character from C++ string

if (str.size () > 0)  str.resize (str.size () - 1);

An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.

BTW - Is there really no std::string::pop_back ? - seems strange.

Multiple Java versions running concurrently under Windows

Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like

java ...

This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable JAVA6HOME with the value C:\java\java6 (if Java 6 is installed in this directory) and change the batch file calling

%JAVA6HOME%\bin\java ...

Get first 100 characters from string, respecting full words

Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.

//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);
}

Note that it automatically adds ellipses, if you don't want that just use '\\1' as the second parameter for the preg_replace call.

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Centering the image in Bootstrap

Use This as the solution

This worked for me perfectly..

<div align="center">
   <img src="">
</div>

Undefined symbols for architecture arm64

The issue is that the cocoapods have not been built for arm64 architecture yet thus they cannot be linked when you build them. Likely you cannot use those packages until they are updated and use that architecture. You can fix the linker error by going to project -> target (your project name) -> build settings and change architectures to standard architectures (armv7, armv7s), and valid architectures to armv7, armv7s.

Note though, this means you won't get the full power of the 64 bit processor. You said you are building for the 5s, so there may be some reason you need this. If you for some reason absolutely need that power (perhaps you are building a game), and desperately need those files, you could submit a pull request and then recompile the project to arm64 by setting those same fields to arm64 in the files you pulled from the open source projects. But, unless you really need these files to be 64 bit compatible, that seems like a bit of overkill for now.

EDIT: Some people also reported that setting Build For Active Architectures to YES was also necessary to solve this problem.

As of 2014-04-28 the setting should look something like this:

enter image description here

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

How to change theme for AlertDialog

I have written an article in my blog on how to configure the layout of an AlertDialog with XML style files. The main problem is that you need different style definitions for different layout parameters. Here is a boilerplate based on the AlertDialog style of Holo Light Platform version 19 for a style file that should cover a bunch of the standard layout aspects like text sizes and background colors.

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    ...
    <item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
    <item name="android:alertDialogStyle">@style/MyAlertDialogStyle</item>
    ...
</style>

<style name="MyBorderlessButton">
    <!-- Set background drawable and text size of the buttons here -->
    <item name="android:background">...</item>
    <item name="android:textSize">...</item>
</style>

<style name="MyButtonBar">
    <!-- Define a background for the button bar and a divider between the buttons here -->
    <item name="android:divider">....</item>
    <item name="android:dividerPadding">...</item>
    <item name="android:showDividers">...</item>
    <item name="android:background">...</item>
</style>

<style name="MyAlertDialogTitle">
    <item name="android:maxLines">1</item>
    <item name="android:scrollHorizontally">true</item>
</style>

<style name="MyAlertTextAppearance">
    <!-- Set text size and color of title and message here -->
    <item name="android:textSize"> ... </item>
    <item name="android:textColor">...</item>
</style>

<style name="MyAlertDialogTheme">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowTitleStyle">@style/MyAlertDialogTitle</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
    <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:textAppearanceMedium">@style/MyAlertTextAppearance</item>
    <!-- If you don't want your own button bar style use
            @android:style/Holo.Light.ButtonBar.AlertDialog
            and
            ?android:attr/borderlessButtonStyle
         instead of @style/MyButtonBar and @style/MyBorderlessButton -->
    <item name="android:buttonBarStyle">@style/MyButtonBar</item>
    <item name="android:buttonBarButtonStyle">@style/MyBorderlessButton</item>
</style>

<style name="MyAlertDialogStyle">
    <!-- Define background colors of title, message, buttons, etc. here -->
    <item name="android:fullDark">...</item>
    <item name="android:topDark">...</item>
    <item name="android:centerDark">...</item>
    <item name="android:bottomDark">...</item>
    <item name="android:fullBright">...</item>
    <item name="android:topBright">...</item>
    <item name="android:centerBright">...</item>
    <item name="android:bottomBright">...</item>
    <item name="android:bottomMedium">...</item>
    <item name="android:centerMedium">...</item>
</style>

How can I zoom an HTML element in Firefox and Opera?

Zoom and transform scale are not the same thing. They are applied at different times. Zoom is applied before the rendering happens, transform - after. The result of this is if you take a div with width/height = 100% nested inside of another div, with fixed size, if you apply zoom, everything inside your inner zoom will shrink, or grow, but if you apply transform your entire inner div will shrink (even though width/height is set to 100%, they are not going to be 100% after transformation).

PHP: HTTP or HTTPS?

This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

What is an unhandled promise rejection?

"DeprecationWarning: Unhandled promise rejections are deprecated"

TLDR: A promise has resolve and reject, doing a reject without a catch to handle it is deprecated, so you will have to at least have a catch at top level.

How do I use the nohup command without getting nohup.out?

If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :

Create a 2 line script called zz.sh

#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
  • The echo command's output goes into STDOUT filestream (file descriptor 1).
  • The error command's output goes into STDERR filestream (file descriptor 2)

Currently, simply executing the script sends both STDOUT and STDERR to the screen.

./zz.sh

Now start with the standard redirection :

zz.sh > zfile.txt

In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.

The above is the same as :

zz.sh 1> zfile.txt

Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.

zz.sh 2> zfile.txt

Combining the above two, you get:

zz.sh 1> zfile.txt 2>&1

Explanation:

  • FIRST, send STDOUT 1 to zfile.txt
  • THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
  • Therefore, both 1 and 2 goes into the same file (zfile.txt)

Eventually, you can pack the whole thing inside nohup command & to run it in the background:

nohup zz.sh 1> zfile.txt 2>&1&

Test whether string is a valid integer

Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case statement.

case ${variable#[-+]} in
  *[!0-9]* | '') echo Not a number ;;
  * ) echo Valid number ;;
esac

The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.

How to test whether a service is running from the command line

You could use wmic with the /locale option

call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
if %ErrorLevel% EQU 0 (
    echo Running
) else (
    echo Not running
)

Strip HTML from Text JavaScript

Converting HTML for Plain Text emailing keeping hyperlinks (a href) intact

The above function posted by hypoxide works fine, but I was after something that would basically convert HTML created in a Web RichText editor (for example FCKEditor) and clear out all HTML but leave all the Links due the fact that I wanted both the HTML and the plain text version to aid creating the correct parts to an STMP email (both HTML and plain text).

After a long time of searching Google myself and my collegues came up with this using the regex engine in Javascript:

str='this string has <i>html</i> code i want to <b>remove</b><br>Link Number 1 -><a href="http://www.bbc.co.uk">BBC</a> Link Number 1<br><p>Now back to normal text and stuff</p>
';
str=str.replace(/<br>/gi, "\n");
str=str.replace(/<p.*>/gi, "\n");
str=str.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<(?:.|\s)*?>/g, "");

the str variable starts out like this:

this string has <i>html</i> code i want to <b>remove</b><br>Link Number 1 -><a href="http://www.bbc.co.uk">BBC</a> Link Number 1<br><p>Now back to normal text and stuff</p>

and then after the code has run it looks like this:-

this string has html code i want to remove
Link Number 1 -> BBC (Link->http://www.bbc.co.uk)  Link Number 1


Now back to normal text and stuff

As you can see the all the HTML has been removed and the Link have been persevered with the hyperlinked text is still intact. Also I have replaced the <p> and <br> tags with \n (newline char) so that some sort of visual formatting has been retained.

To change the link format (eg. BBC (Link->http://www.bbc.co.uk) ) just edit the $2 (Link->$1), where $1 is the href URL/URI and the $2 is the hyperlinked text. With the links directly in body of the plain text most SMTP Mail Clients convert these so the user has the ability to click on them.

Hope you find this useful.

How to delete session cookie in Postman?

new version of postman app has the ability to do that programmatically in pre-request or tests scripts since 2019/08

see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support

clear all cookies

const jar = pm.cookies.jar();

jar.clear(pm.request.url, function (error) {
  // error - <Error>
});

get all cookies

const jar = pm.cookies.jar();

jar.getAll('http://example.com', function (error, cookies) {
  // error - <Error>
  // cookies - <PostmanCookieList>
  // PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});

get specific cookie

const jar = pm.cookies.jar();

jar.get('http://example.com', 'token', function (error, value) {
  // error - <Error>
  // value - <String>
});

pip install from git repo branch

For windows & pycharm setup:

If you are using pycharm and If you want to use pip3 install git+https://github.com/...

  • firstly, you should download git from https://git-scm.com/downloads
  • then restart pycharm
  • and you can use pycharm terminal to install what you want

enter image description here

Ways to eliminate switch in code

Function pointers are one way to replace a huge chunky switch statement, they are especially good in languages where you can capture functions by their names and make stuff with them.

Of course, you ought not force switch statements out of your code, and there always is a chance you are doing it all wrong, which results with stupid redundant pieces of code. (This is unavoidable sometimes, but a good language should allow you to remove redundancy while staying clean.)

This is a great divide&conquer example:

Say you have an interpreter of some sort.

switch(*IP) {
    case OPCODE_ADD:
        ...
        break;
    case OPCODE_NOT_ZERO:
        ...
        break;
    case OPCODE_JUMP:
        ...
        break;
    default:
        fixme(*IP);
}

Instead, you can use this:

opcode_table[*IP](*IP, vm);

... // in somewhere else:
void opcode_add(byte_opcode op, Vm* vm) { ... };
void opcode_not_zero(byte_opcode op, Vm* vm) { ... };
void opcode_jump(byte_opcode op, Vm* vm) { ... };
void opcode_default(byte_opcode op, Vm* vm) { /* fixme */ };

OpcodeFuncPtr opcode_table[256] = {
    ...
    opcode_add,
    opcode_not_zero,
    opcode_jump,
    opcode_default,
    opcode_default,
    ... // etc.
};

Note that I don't know how to remove the redundancy of the opcode_table in C. Perhaps I should make a question about it. :)

Submitting form and pass data to controller method of type FileStreamResult

here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.

make the following changes in FormMethod

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){

}

and inside your home controller for binding the string you should specify [FromBody]

using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
     // Set a local variable with the incoming data
     string str = id;

}

FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Entity Framework 5 Updating a Record

public interface IRepository
{
    void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}

public class Repository : DbContext, IRepository
{
    public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
    {
        Set<T>().Attach(obj);
        propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
        SaveChanges();
    }
}

Input placeholders for Internet Explorer

I found a quite simple solution using this method:

http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

it's a jquery hack, and it worked perfectly on my projects

Submit form using <a> tag

You can use hidden submit button and click it using java script/jquery like this:

  <form id="contactForm" method="post" class="contact-form">

        <button type="submit" id="submitBtn" style="display:none;" data-validate="contact-form">Hidden Button</button>
        <a href="javascript:;" class="myClass" onclick="$('#submitBtn').click();">Submit</a>

  </form>

Reading a .txt file using Scanner class in Java

  1. Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).

  2. Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:

    URL url = insertionSort.class.getResource("10_Random");
    
    File file = new File(url.toURI());
    
  3. Specify the absolute file path via command-line arguments:

    File file = new File(args[0]);
    

In Eclipse:

  1. Choose "Run configurations"
  2. Go to the "Arguments" tab
  3. Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section

How do I disable a jquery-ui draggable?

Seems like no one looked at the original documentation. May be there was no it at that time))

Initialize a draggable with the disabled option specified.

$( ".selector" ).draggable({ disabled: true });

Get or set the disabled option, after init.

//getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );

What does set -e mean in a bash script?

set -e stops the execution of a script if a command or pipeline has an error - which is the opposite of the default shell behaviour, which is to ignore errors in scripts. Type help set in a terminal to see the documentation for this built-in command.

Could not find folder 'tools' inside SDK

If you get the "Failed to find DDMS files..." do this:

  1. Open eclipse
  2. Open install new software
  3. Click "Add..." -> type in (e.g.) "Android_over_HTTP" and in address put "http://dl-ssl.google.com/android/eclipse/".

Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux

Hope this helps !

Why do we usually use || over |? What is the difference?

| does not do short-circuit evaluation in boolean expressions. || will stop evaluating if the first operand is true, but | won't.

In addition, | can be used to perform the bitwise-OR operation on byte/short/int/long values. || cannot.

Convert String[] to comma separated string in java

You can also use org.apache.commons.lang.StringUtils API to form a comma separated result from string array in Java.

StringUtils.join(strArr,",");

Pandas (python): How to add column to dataframe for index?

I stumbled on this question while trying to do the same thing (I think). Here is how I did it:

df['index_col'] = df.index

You can then sort on the new index column, if you like.

How do I remove blank elements from an array?

Shortest way cities.select(&:present?)

Async always WaitingForActivation

For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task class and TaskStatus enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.

In the context of methods marked as async, the resulting Task is not a Task representing the execution of the method, but a Task for the continuation of the method.

This is only able to make use of a few possible states:

  • Canceled
  • Faulted
  • RanToCompletion
  • WaitingForActivation

I understand that Runningcould appear to have been a better default than WaitingForActivation, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await-ing something else). The other option may have been to add a new value to TaskStatus, however this could have been a breaking change for existing applications and libraries.

All of this is very different to when making use of Task.Run which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus enumeration.

If you wish to keep track of the status of an async method, take a look at the IProgress(T) interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T) interface.

Using 'starts with' selector on individual class names

While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:

You can use this custom jQuery selector, which I call :acp() for "A Class Prefix." Code is at the bottom of this post.

var test = $('div:acp("starting_text")');

This will select any and all <div> elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

This will return elements 1, 2, and 3, but not 4 or 5.

Here's the declaration for the :acp custom selector, which you can put anywhere:

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.

Jenkins Git Plugin: How to build specific tag?

I set the Advanced->Refspec field to refs/tags/[your tag name]. This seems simpler than the various other suggestions for Refspec, but it worked just fine for me.

UPDATE 23/7/2014 - Actually, after further testing, it turns out this didn't work as expected. It appears that the HEAD version was still being checked out. Please undo this as the accepted answer. I ended up getting a working solution by following the post from gotgenes in this thread (30th March). The issue mentioned in that post of unnecessary triggering of builds was not an issue for me, as my job is triggered from an upstream job, not from polling SCM.

UPDATE APR-2018 - Note in the comments that this does work for one person, and agrees with Jenkins documentation.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:

TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning

This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.

Defining static const integer members in class definition

Not just int's. But you can't define the value in the class declaration. If you have:

class classname
{
    public:
       static int const N;
}

in the .h file then you must have:

int const classname::N = 10;

in the .cpp file.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Adding one day to a date

Try this

echo date('Y-m-d H:i:s',date(strtotime("+1 day", strtotime("2009-09-30 20:24:00"))));

Catch KeyError in Python

If you don't want to handle error just NoneType and use get() e.g.:

manager.connect.get("")

How do I view cookies in Internet Explorer 11 using Developer Tools

  1. Click on the Network button
  2. Enable capture of network traffic by clicking on the green triangular button in top toolbar
  3. Capture some network traffic by interacting with the page
  4. Click on DETAILS/Cookies
  5. Step through each captured traffic segment; detailed information about cookies will be displayed

PHP: HTML: send HTML select option attribute in POST

You can use jquery function.

<form name='add'>
   <input type='text' name='stud_name' id="stud_name" value=""/>
   Age: <select name='age' id="age">
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='submit' name='submit'/>
</form>

jquery code :

<script type="text/javascript" src="jquery.js"></script>

<script>
    $(function() {
          $("#age").change(function(){
          var option = $('option:selected', this).attr('stud_name');
          $('#stud_name').val(option);
       });
    });
</script>

decompiling DEX into Java sourcecode

Android Reverse Engineering is possible . Follow these steps to get .java file from apk file.

Step1 . Using dex2jar

  • Generate .jar file from .apk file
  • command : dex2jar sampleApp.apk

Step2 . Decompiling .jar using JD-GUI

  • it decompiles the .class files i.e., we'll get obfuscated .java back from the apk.

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

How to use _CRT_SECURE_NO_WARNINGS

If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

Inner text shadow with CSS

Building on the :before :after technique by web_designer, here is something that comes closer to your look:

First, make your text the color of the inner shadow (black-ish in the case of the OP).

Now, use an :after psuedo class to create a transparent duplicate of the original text, placed directly on top of it. Assign a regular text shadow to it with no offset. Assign the original text color to the shadow, and adjust alpha as needed.

http://dabblet.com/gist/2499892

You don't get complete control over spread, etc. of the shadow like you do in PS, but for smaller blur values it is quite passable. The shadow goes past the bounds of the text, so if you are working in an environment with a high contrast background-foreground, it will be obvious. For lower contrast items, especially ones with the same hue, it's not too noticeable. For example, I've been able to make very nice looking etched text in metal backgrounds using this technique.

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

So the simplest way is,

alter table table_name change column_name column_name int(11) NULL;

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

Best way to create unique token in Rails?

There are some pretty slick ways of doing this demonstrated in this article:

https://web.archive.org/web/20121026000606/http://blog.logeek.fr/2009/7/2/creating-small-unique-tokens-in-ruby

My favorite listed is this:

rand(36**8).to_s(36)
=> "uur0cj2h"

How to avoid warning when introducing NAs by coercion

suppressWarnings() has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.

> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion 
> y <- destring(c("1", "2", "X"))
> y
[1]  1  2 NA
> x
[1]  1  2 NA

How to reload the current state?

$state.go($state.current, $stateParams, {reload: true, inherit: false});

How to re-create database for Entity Framework?

While this question is premised by not caring about the data, sometimes maintenance of the data is essential.

If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name

Apparently... a moderator saw fit to delete my post so I'll paste it here:

How to recover from Entity Framework nightmare - database already has tables with the same name

Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.

Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.

Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.

Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.

To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.

Step 1: Production DB clean First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.

Step 2: Local environment clean Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.

Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.

Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.

Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.

Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...

Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.

Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.

Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.

Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

How to execute python file in linux

yes there is. add

#!/usr/bin/env python

to the beginning of the file and do

chmod u+rx <file>

assuming your user owns the file, otherwise maybe adjust the group or world permissions.

.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.

How to set time zone of a java.util.Date?

tl;dr

…parsed … from a String … time zone is not specified … I want to set a specific time zone

LocalDateTime.parse( "2018-01-23T01:23:45.123456789" )  // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
    .atZone( ZoneId.of( "Africa/Tunis" ) )              // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.

No Time Zone in j.u.Date

As the other correct answers stated, a java.util.Date has no time zone. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.

Avoid j.u.Date

For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.

Instead use the java.time package bundled with Java 8.

java.time

The java.time classes can represent a moment on the timeline in three ways:

  • UTC (Instant)
  • With an offset (OffsetDateTime with ZoneOffset)
  • With a time zone (ZonedDateTime with ZoneId)

Instant

In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.

Instant instant = Instant.now();

OffsetDateTime

Apply an offset-from-UTC to adjust into some locality’s wall-clock time.

Apply a ZoneOffset to get an OffsetDateTime.

ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );

ZonedDateTime

Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).

Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

LocalDateTime

If the input string lacked any indicator of offset or zone, parse as a LocalDateTime.

If you are certain of the intended time zone, assign a ZoneId to produce a ZonedDateTime. See code example above in tl;dr section at top.

Formatted Strings

Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.

String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]

For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.


Table of all date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.

In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.

String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );

Call the toString method to generate a String in ISO 8601 format.

String output = dateTimeIndia.toString();

Joda-Time also offers rich capabilities for generating all kinds of other String formats.

If required, you can convert from Joda-Time DateTime to a java.util.Date.

Java.util.Date date = dateTimeIndia.toDate();

Search StackOverflow for "joda date" to find many more examples, some quite detailed.


Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.