Programs & Examples On #Git flow

The git-flow workflow defines a strict branching model designed around a project release. It provides a robust framework for managing larger projects. Use this tag for help with applying git-flow to your workflow, or for help with the supporting scripts (either the original scripts or the AVH Edition).

Git merge master into feature branch

You might be able to do a "cherry-pick" to pull the exact commit(s) that you need in to your feature branch.

Do a git checkout hotfix1 to get on the hotfix1 branch. Then do a git log to get the SHA-1 hash (big sequence of random letters and numbers that uniquely identifies a commit) of the commit in question. Copy that (or the first 10 or so characters).

Then, git checkout feature1 to get back onto your feature branch.

Then, git cherry-pick <the SHA-1 hash that you just copied>

That will pull that commit, and only that commit, into your feature branch. That change will be in the branch - you just "cherry-picked" it in. Then, resume work, edit, commit, push, etc. to your heart's content.

When, eventually, you perform another merge from one branch into your feature branch (or vice-versa), Git will recognize that you've already merged in that particular commit, know that it doesn't have to make it again, and just "skip over" it.

Create a branch in Git from another branch

If you want to make a branch from some another branch then follow bellow steps:

Assumptions:

  1. You are currently in master branch.
  2. You have no changes to commit. (If you have any changes to commit, stash it!).
  3. BranchExisting is the name of branch from which you need to make a new branch with name BranchMyNew.

Steps:

  1. Fetch the branch to your local machine.

    $ git fetch origin BranchExisting : BranchExisting
    

This command will create a new branch in your local with same branch name.

  1. Now, from master branch checkout to the newly fetched branch

    $ git checkout BranchExisting
    
  2. You are now in BranchExisting. Now create a new branch from this existing branch.

    $ git checkout -b BranchMyNew
    

Here you go!

Php multiple delimiters in explode

You can try this solution.... It works great

function explodeX( $delimiters, $string )
{
    return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';

$exploded = explodeX( array('&', ',', '|' ), $list );

echo '<pre>';
print_r($exploded);
echo '</pre>';

Source : http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

Double value to round up in Java

Live @Sergey's solution but with integer division.

double value = 23.8764367843;
double rounded = (double) Math.round(value * 100) / 100;
System.out.println(value +" rounded is "+ rounded);

prints

23.8764367843 rounded is 23.88

EDIT: As Sergey points out, there should be no difference between multipling double*int and double*double and dividing double/int and double/double. I can't find an example where the result is different. However on x86/x64 and other systems there is a specific machine code instruction for mixed double,int values which I believe the JVM uses.

for (int j = 0; j < 11; j++) {
    long start = System.nanoTime();
    for (double i = 1; i < 1e6; i *= 1.0000001) {
        double rounded = (double) Math.round(i * 100) / 100;
    }
    long time = System.nanoTime() - start;
    System.out.printf("double,int operations %,d%n", time);
}
for (int j = 0; j < 11; j++) {
    long start = System.nanoTime();
    for (double i = 1; i < 1e6; i *= 1.0000001) {
        double rounded = (double) Math.round(i * 100.0) / 100.0;
    }
    long time = System.nanoTime() - start;
    System.out.printf("double,double operations %,d%n", time);
}

Prints

double,int operations 613,552,212
double,int operations 661,823,569
double,int operations 659,398,960
double,int operations 659,343,506
double,int operations 653,851,816
double,int operations 645,317,212
double,int operations 647,765,219
double,int operations 655,101,137
double,int operations 657,407,715
double,int operations 654,858,858
double,int operations 648,702,279
double,double operations 1,178,561,102
double,double operations 1,187,694,386
double,double operations 1,184,338,024
double,double operations 1,178,556,353
double,double operations 1,176,622,937
double,double operations 1,169,324,313
double,double operations 1,173,162,162
double,double operations 1,169,027,348
double,double operations 1,175,080,353
double,double operations 1,182,830,988
double,double operations 1,185,028,544

python: get directory two levels up

More cross-platform implementation will be:

import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()

Using parent is not supported on Windows. Also need to add .resolve(), to:

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)

How to read a file from jar in Java?

Just for completeness, there has recently been a question on the Jython mailinglist where one of the answers referred to this thread.

The question was how to call a Python script that is contained in a .jar file from within Jython, the suggested answer is as follows (with "InputStream" as explained in one of the answers above:

PythonInterpreter.execfile(InputStream)

Python: TypeError: cannot concatenate 'str' and 'int' objects

If you want to concatenate int or floats to a string you must use this:

i = 123
a = "foobar"
s = a + str(i)

How do I get the parent directory in Python?

import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Ping site and return result in PHP

With the following function you are just sending the pure ICMP packets using socket_create. I got the following code from a user note there. N.B. You must run the following as root.

Although you can't put this in a standard web page you can run it as a cron job and populate a database with the results.

So it's best suited if you need to monitor a site.

function twitterIsUp() {
    return ping('twitter.com');
}

function ping ($host, $timeout = 1) {
    /* ICMP ping packet with a pre-calculated checksum */
    $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
    $socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
    socket_connect($socket, $host, null);

    $ts = microtime(true);
    socket_send($socket, $package, strLen($package), 0);
    if (socket_read($socket, 255)) {    
        $result = microtime(true) - $ts;
    } else {
        $result = false;
    }
    socket_close($socket);

    return $result;
}

How to hide 'Back' button on navigation bar on iPhone?

navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true

if you use this code block inside didLoad or loadView worked but not worked perfectly.If you look carefully you can see back button is hiding when your view load.Look's weird.

What is the perfect solution?

Add BarButtonItem component from componentView (Command + Shift + L) to your target viewControllers navigation bar.

Select BarButtonItem set Title = " " from right panel

enter image description here

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

Detecting scroll direction

  1. Initialize an oldValue
  2. Get the newValue by listening to the event
  3. Subtract the two
  4. Conclude from the result
  5. Update oldValue with the newValue

// Initialization

let oldValue = 0;

//Listening on the event

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

How do I detect IE 8 with jQuery?

Don't forget that you can also use HTML to detect IE8.

<!--[if IE 8]>
<script type="text/javascript">
    ie = 8;
</script>
<![endif]-->

Having that before all your scripts will let you just check the "ie" variable or whatever.

How to validate a credit card number

I hope the following two links help to solve your problem.

FYI, various credit cards are available in the world. So, your thought is wrong. Credit cards have some format. See the following links. The first one is pure JavaScript and the second one is using jQuery.

Demo:

_x000D_
_x000D_
function testCreditCard() {_x000D_
  myCardNo = document.getElementById('CardNumber').value;_x000D_
  myCardType = document.getElementById('CardType').value;_x000D_
  if (checkCreditCard(myCardNo, myCardType)) {_x000D_
    alert("Credit card has a valid format")_x000D_
  } else {_x000D_
    alert(ccErrors[ccErrorNo])_x000D_
  };_x000D_
}
_x000D_
<script src="https://www.braemoor.co.uk/software/_private/creditcard.js"></script>_x000D_
_x000D_
<!-- COPIED THE DEMO CODE FROM THE SOURCE WEBSITE (https://www.braemoor.co.uk/software/creditcard.shtml) -->_x000D_
_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td style="padding-right: 30px;">American Express</td>_x000D_
      <td>3400 0000 0000 009</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Carte Blanche</td>_x000D_
      <td>3000 0000 0000 04</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Discover</td>_x000D_
      <td>6011 0000 0000 0004</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Diners Club</td>_x000D_
      <td>3852 0000 0232 37</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>enRoute</td>_x000D_
      <td>2014 0000 0000 009</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>JCB</td>_x000D_
      <td>3530 111333300000</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>MasterCard</td>_x000D_
      <td>5500 0000 0000 0004</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Solo</td>_x000D_
      <td>6334 0000 0000 0004</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Switch</td>_x000D_
      <td>4903 0100 0000 0009</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visa</td>_x000D_
      <td>4111 1111 1111 1111</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Laser</td>_x000D_
      <td>6304 1000 0000 0008</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<hr /> Card Number:_x000D_
<select tabindex="11" id="CardType" style="margin-left: 10px;">_x000D_
  <option value="AmEx">American Express</option>_x000D_
  <option value="CarteBlanche">Carte Blanche</option>_x000D_
  <option value="DinersClub">Diners Club</option>_x000D_
  <option value="Discover">Discover</option>_x000D_
  <option value="EnRoute">enRoute</option>_x000D_
  <option value="JCB">JCB</option>_x000D_
  <option value="Maestro">Maestro</option>_x000D_
  <option value="MasterCard">MasterCard</option>_x000D_
  <option value="Solo">Solo</option>_x000D_
  <option value="Switch">Switch</option>_x000D_
  <option value="Visa">Visa</option>_x000D_
  <option value="VisaElectron">Visa Electron</option>_x000D_
  <option value="LaserCard">Laser</option>_x000D_
</select> <input type="text" id="CardNumber" maxlength="24" size="24" style="margin-left: 10px;"> <button id="mybutton" type="button" onclick="testCreditCard();" style="margin-left: 10px; color: #f00;">Check</button>_x000D_
_x000D_
<p style="color: red; font-size: 10px;"> COPIED THE DEMO CODE FROM TEH SOURCE WEBSITE (https://www.braemoor.co.uk/software/creditcard.shtml) </p>
_x000D_
_x000D_
_x000D_

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

Mocha / Chai expect.to.throw not catching thrown errors

As this answer says, you can also just wrap your code in an anonymous function like this:

expect(function(){
    model.get('z');
}).to.throw('Property does not exist in model schema.');

Comments in Markdown

This works on GitHub:

[](Comment text goes here)

The resulting HTML looks like:

<a href="Comment%20text%20goes%20here"></a>

Which is basically an empty link. Obviously you can read that in the source of the rendered text, but you can do that on GitHub anyway.

Transaction isolation levels relation with locks on table

The locks are always taken at DB level:-

Oracle official Document:- To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)

How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.

One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values that represent the transaction isolation levels you can use in JDBC.

Contains method for a slice

You can use the reflect package to iterate over an interface whose concrete type is a slice:

func HasElem(s interface{}, elem interface{}) bool {
    arrV := reflect.ValueOf(s)

    if arrV.Kind() == reflect.Slice {
        for i := 0; i < arrV.Len(); i++ {

            // XXX - panics if slice element points to an unexported struct field
            // see https://golang.org/pkg/reflect/#Value.Interface
            if arrV.Index(i).Interface() == elem {
                return true
            }
        }
    }

    return false
}

https://play.golang.org/p/jL5UD7yCNq

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

How to import a csv file into MySQL workbench?

In case you have smaller data set, a way to achieve it by GUI is:

  1. Open a query window
  2. SELECT * FROM [table_name]
  3. Select Import from the menu bar
  4. Press Apply on the bottom right below the Result Grid

enter image description here

Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY

CSS file not refreshing in browser

I faced the same problem. Renaming the file worked for me.

How to clear Flutter's Build cache?

I was facing the same issue and i found out that I was having two terminals in visual studio code, On first terminal it was already running my flutter project and on the other terminal I was running different solutions shared in this thread. Due to this reason no solution was working for me. So there are two ways you can solve this problem. 1- Restart visual studio code (it will automatically close the terminals) 2- Stop the terminal in which flutter project is already running and then run flutter clean command.

File tree view in Notepad++

You can also use you own computer built-in functions:

  • Create a file, write this on it:
tree /a /f >tree.txt
  • Save the file as any_name_you_want.BAT
  • Launch it, it will create a file named tree.txt that contains you directory TREE.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Storing images in SQL Server?

Another option was released in 2012 called File tables: https://msdn.microsoft.com/en-us/library/ff929144.aspx

How to Merge Two Eloquent Collections?

The merge() method on the Collection does not modify the collection on which it was called. It returns a new collection with the new data merged in. You would need:

$related = $related->merge($tag->questions);

However, I think you're tackling the problem from the wrong angle.

Since you're looking for questions that meet a certain criteria, it would probably be easier to query in that manner. The has() and whereHas() methods are used to generate a query based on the existence of a related record.

If you were just looking for questions that have any tag, you would use the has() method. Since you're looking for questions with a specific tag, you would use the whereHas() to add the condition.

So, if you want all the questions that have at least one tag with either 'Travel', 'Trains', or 'Culture', your query would look like:

$questions = Question::whereHas('tags', function($q) {
    $q->whereIn('name', ['Travel', 'Trains', 'Culture']);
})->get();

If you wanted all questions that had all three of those tags, your query would look like:

$questions = Question::whereHas('tags', function($q) {
    $q->where('name', 'Travel');
})->whereHas('tags', function($q) {
    $q->where('name', 'Trains');
})->whereHas('tags', function($q) {
    $q->where('name', 'Culture');
})->get();

Importing CSV data using PHP/MySQL

set_time_limit(10000);

$con = mysql_connect('127.0.0.1','root','password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("db", $con);

$fp = fopen("file.csv", "r");

while( !feof($fp) ) {
  if( !$line = fgetcsv($fp, 1000, ';', '"')) {
     continue;
  }

    $importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')";

    mysql_query($importSQL) or die(mysql_error());  

}

fclose($fp);
mysql_close($con);

Flask - Calling python function on button OnClick event

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

And your json.html page should look like below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').on('click', function(e) {
            e.preventDefault()
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>


//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Move the jar files from your classpath to web-inf/lib, and run a new tomcat server.

Error during SSL Handshake with remote server

I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.

So, I had to generate the SSL certificate again and it started working...

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

Excel - Combine multiple columns into one column

Function Concat(myRange As Range, Optional myDelimiter As String) As String 
  Dim r As Range 
  Application.Volatile 
  For Each r In myRange 
    If Len(r.Text) Then 
      Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text 
    End If 
  Next 
End Function

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

Calling variable defined inside one function from another function

The simplest option is to use a global variable. Then create a function that gets the current word.

current_word = ''
def oneFunction(lists):
    global current_word
    word=random.choice(lists[category])
    current_word = word

def anotherFunction():
    for letter in get_word():              
          print("_",end=" ")

 def get_word():
      return current_word

The advantage of this is that maybe your functions are in different modules and need to access the variable.

Reading a text file and splitting it into single words in python

Given this file:

$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6

If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):

with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)    

Prints:

line1
word1
word2
line2
...
word6 

Similarly, if you want to flatten the file into a single flat list of words in the file, you might do something like this:

with open('words.txt') as f:
    flat_list=[word for line in f for word in line.split()]

>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']

Which can create the same output as the first example with print '\n'.join(flat_list)...

Or, if you want a nested list of the words in each line of the file (for example, to create a matrix of rows and columns from a file):

with open('words.txt') as f:
    matrix=[line.split() for line in f]

>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]

If you want a regex solution, which would allow you to filter wordN vs lineN type words in the example file:

import re
with open("words.txt") as f:
    for line in f:
        for word in re.findall(r'\bword\d+', line):
            # wordN by wordN with no lineN

Or, if you want that to be a line by line generator with a regex:

 with open("words.txt") as f:
     (word for line in f for word in re.findall(r'\w+', line))

Use grep to report back only line numbers

using only grep:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

Is there a template engine for Node.js?

If you're looking for a minimalist approach to templates, you can check out JSON Template.

A more full-featured alternative is EJS. It's a bit more similar to something you'd get from Django.

Your mileage may vary for each of these - they're designed for a browser Javascript environment, and not Node.js.

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

Vertical align in bootstrap table

For me <td class="align-middle" >${element.imie}</td> works. I'm using Bootstrap v4.0.0-beta .

Convert date to YYYYMM format

SELECT LEFT(CONVERT(varchar, GetDate(),112),6)

Call Javascript function from URL/address bar

Write in address bar

javascript:alert("hi");

Make sure you write in the beginning: javascript:

How do I get the name of the active user via the command line in OS X?

getting username in MAC terminal is easy...

I generally use whoami in terminal...

For example, in this case, I needed that to install Tomcat Server...

enter image description here

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

try this:

ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";

EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):

The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue

So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";

            List<ComboboxItem> list = new List<ComboboxItem>();

            ComboboxItem item = new ComboboxItem();
            item.Text = "choose a server...";
            item.Value = "-1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S1";
            item.Value = "1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S2";
            item.Value = "2";
            list.Add(item);

            cbx.DataSource = list; // bind combobox to a datasource

or use SelectedItem property:

if (cbx.SelectedItem != null)
             Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());

Gets byte array from a ByteBuffer in java

Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

Validating with an XML schema in Python

You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies.

Example - validate a file:

import xmlschema
xmlschema.validate('doc.xml', 'some.xsd')

The method raises an exception if the file doesn't validate against the XSD. That exception then contains some violation details.

If you want to validate many files you only have to load the XSD once:

xsd = xmlschema.XMLSchema('some.xsd')
for filename in filenames:
    xsd.validate(filename)

If you don't need the exception you can validate like this:

if xsd.is_valid('doc.xml'):
    print('do something useful')

Alternatively, xmlschema directly works on file objects and in memory XML trees (either created with xml.etree.ElementTree or lxml). Example:

import xml.etree.ElementTree as ET
t = ET.parse('doc.xml')
result = xsd.is_valid(t)
print('Document is valid? {}'.format(result))

How to make asynchronous HTTP requests in PHP

class async_file_get_contents extends Thread{
    public $ret;
    public $url;
    public $finished;
        public function __construct($url) {
        $this->finished=false;
        $this->url=$url;
    }
        public function run() {
        $this->ret=file_get_contents($this->url);
        $this->finished=true;
    }
}
$afgc=new async_file_get_contents("http://example.org/file.ext");

How do I get a specific range of numbers from rand()?

Just to add some extra detail to the existing answers.

The mod % operation will always perform a complete division and therefore yield a remainder less than the divisor.

x % y = x - (y * floor((x/y)))

An example of a random range finding function with comments:

uint32_t rand_range(uint32_t n, uint32_t m) {
    // size of range, inclusive
    const uint32_t length_of_range = m - n + 1;

    // add n so that we don't return a number below our range
    return (uint32_t)(rand() % length_of_range + n);
}

Another interesting property as per the above:

x % y = x, if x < y

const uint32_t value = rand_range(1, RAND_MAX); // results in rand() % RAND_MAX + 1
// TRUE for all x = RAND_MAX, where x is the result of rand()
assert(value == RAND_MAX);
result of rand()

How to Auto resize HTML table cell to fit the text size

Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto; to the <table> element.

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

How to check if a variable is empty in python?

Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.

bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.

If you wanted to handle strings containing numbers as PHP does, you could do something like:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

How do you update Xcode on OSX to the latest version?

In my case (Xcode 6.1, iOS 8.2) I did not see the update in AppStore. I found Xcode 6.2 for download and pressed "Install". Then, it installed and asked for the update (more than 2 Gb). Xcode 6.2 works correctly with iOS 8.2 and iOS 8.1.2

Hopefully this tip will help somebody else...

How to read a value from the Windows registry

RegQueryValueEx

This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.

(I can't tell if my link is working or not, but if you just google for "RegQueryValueEx" the first hit is the msdn documentation.)

Add image in pdf using jspdf

This worked for me in Angular 2:

var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)

jsPDF version 1.5.3

assets directory is in src directory of the Angular project root

Python dict how to create key or append an element to key?

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

stopPropagation vs. stopImmediatePropagation

Surprisingly, all other answers only say half the truth or are actually wrong!

  • e.stopImmediatePropagation() stops any further handler from being called for this event, no exceptions
  • e.stopPropagation() is similar, but does still call all handlers for this phase on this element if not called already

What phase?

E.g. a click event will always first go all the way down the DOM (called “capture phase”), finally reach the origin of the event (“target phase”) and then bubble up again (“bubble phase”). And with addEventListener() you can register multiple handlers for both capture and bubble phase independently. (Target phase calls handlers of both types on the target without distinguishing.)

And this is what the other answers are incorrect about:

  • quote: “event.stopPropagation() allows other handlers on the same element to be executed”
    • correction: if stopped in the capture phase, bubble phase handlers will never be reached, also skipping them on the same element
  • quote: “event.stopPropagation() [...] is used to stop executions of its corresponding parent handler only”
    • correction: if propagation is stopped in the capture phase, handlers on any children, including the target aren’t called either, not only parents
    • ...and: if propagation is stopped in the bubble phase, all capture phase handlers have already been called, including those on parents

A fiddle and mozilla.org event phase explanation with demo.

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

How do I read a text file of about 2 GB?

If you only need to read the file, I can suggest Large Text File Viewer. https://www.portablefreeware.com/?id=693

and also refer this

Text editor to open big (giant, huge, large) text files

else if you would like to make your own tool try this . i presume that you know filestream reader in c#

const int kilobyte = 1024;
const int megabyte = 1024 * kilobyte;
const int gigabyte = 1024 * megabyte;

public void ReadAndProcessLargeFile(string theFilename, long whereToStartReading = 0)
{
    FileStream fileStream = new FileStream(theFilename, FileMode.Open, FileAccess.Read);
    using (fileStream)
    {
        byte[] buffer = new byte[gigabyte];
        fileStream.Seek(whereToStartReading, SeekOrigin.Begin);
        int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        while(bytesRead > 0)
        {
            ProcessChunk(buffer, bytesRead);
            bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        }
    }
}

private void ProcessChunk(byte[] buffer, int bytesRead)
{
    // Do the processing here
}

refer this kindly

http://www.codeproject.com/Questions/543821/ReadplusBytesplusfromplusLargeplusBinaryplusfilepl

how to check if the input is a number or not in C?

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}

IOException: read failed, socket might closed - Bluetooth on Android 4.3

On newer versions of Android, I was receiving this error because the adapter was still discovering when I attempted to connect to the socket. Even though I called the cancelDiscovery method on the Bluetooth adapter, I had to wait until the callback to the BroadcastReceiver's onReceive() method was called with the action BluetoothAdapter.ACTION_DISCOVERY_FINISHED.

Once I waited for the adapter to stop discovery, then the connect call on the socket succeeded.

If a DOM Element is removed, are its listeners also removed from memory?

Just extending other answers...

Delegated events handlers will not be removed upon element removal.

$('body').on('click', '#someEl', function (event){
  console.log(event);
});

$('#someEL').remove(); // removing the element from DOM

Now check:

$._data(document.body, 'events');

git: patch does not apply

My issue is that I ran git diff, then ran git reset --hard HEAD, then realized I wanted to undo, so I tried copying the output from git diff into a file and using git apply, but I got an error that "patch does not apply". After switching to patch and trying to use it, I realized that a chunk of the diff was repeated for some reason, and after removing the duplicate, patch (and presumably also git apply) worked.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

How to switch between python 2.7 to python 3 from command line?

No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

#!python2
print "hello"

Or

#!python3
print("hello")

From the command line:

py -3 hello.py

Or

py -2 hello.py

py hello.py by itself will choose the latest Python installed, or consult the PY_PYTHON environment variable, e.g. set PY_PYTHON=3.6.

See Python Launcher for Windows

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

In Python, how do I convert all of the items in a list to floats?

I had to extract numbers first from a list of float strings:

   df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')

then each convert to a float:

   ad=[]
   for z in range(len(df4)):
      ad.append([float(i) for i in df4['sscore'][z]])

in the end assign all floats to a dataframe as float64:

   df4['fscore'] = np.array(ad,dtype=float)

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For those wanting to use Postgresql on OpenSuse (and co), try the following:

zypper --no-refresh in php5-pgsql

On - window.location.hash - Change?

var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    }
    return false;
}
var RunTabs = setInterval(TrackHash, 200);

That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.

How to connect Robomongo to MongoDB

I was able to connect Robomongo to a remote instance of MongoDB running on Mongo Labs using the connection string as follows:

  1. Download the latest version of Robomongo. I downloaded 0.9 RC6 from here.

  2. From the connection string, populate the server address and port numbers as follows.

    Connection settings

  3. Populate DB name and username and password as follows under the authentication tab.

    Authentication settings

  4. Test the connection.

    Test connection

    Enter image description here

How to change Tkinter Button state from disabled to normal?

You simply have to set the state of the your button self.x to normal:

self.x['state'] = 'normal'

or

self.x.config(state="normal")

This code would go in the callback for the event that will cause the Button to be enabled.


Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)

The method pack in Button(...).pack() returns None, and you are assigning it to self.x. You actually want to assign the return value of Button(...) to self.x, and then, in the following line, use self.x.pack().

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

How to insert &nbsp; in XSLT

you can also use:

<xsl:value-of select="'&amp;nbsp'"/>

remember the amp after the & or you will get an error message

mysql_config not found when installing mysqldb python interface

The commands (mysql too) mPATH might be missing.

export PATH=$PATH:/usr/local/mysql/bin/

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

tomcat - CATALINA_BASE and CATALINA_HOME variables

CATALINA_HOME vs CATALINA_BASE

If you're running multiple instances, then you need both variables, otherwise only CATALINA_HOME.

In other words: CATALINA_HOME is required and CATALINA_BASE is optional.

CATALINA_HOME represents the root of your Tomcat installation.

Optionally, Tomcat may be configured for multiple instances by defining $CATALINA_BASE for each instance. If multiple instances are not configured, $CATALINA_BASE is the same as $CATALINA_HOME.

See: Apache Tomcat 7 - Introduction

Running with separate CATALINA_HOME and CATALINA_BASE is documented in RUNNING.txt which say:

The CATALINA_HOME and CATALINA_BASE environment variables are used to specify the location of Apache Tomcat and the location of its active configuration, respectively.

You cannot configure CATALINA_HOME and CATALINA_BASE variables in the setenv script, because they are used to find that file.

For example:

(4.1) Tomcat can be started by executing one of the following commands:

  %CATALINA_HOME%\bin\startup.bat         (Windows)

  $CATALINA_HOME/bin/startup.sh           (Unix)

or

  %CATALINA_HOME%\bin\catalina.bat start  (Windows)

  $CATALINA_HOME/bin/catalina.sh start    (Unix)

Multiple Tomcat Instances

In many circumstances, it is desirable to have a single copy of a Tomcat binary distribution shared among multiple users on the same server. To make this possible, you can set the CATALINA_BASE environment variable to the directory that contains the files for your 'personal' Tomcat instance.

When running with a separate CATALINA_HOME and CATALINA_BASE, the files and directories are split as following:

In CATALINA_BASE:

  • bin - Only: setenv.sh (*nix) or setenv.bat (Windows), tomcat-juli.jar
  • conf - Server configuration files (including server.xml)
  • lib - Libraries and classes, as explained below
  • logs - Log and output files
  • webapps - Automatically loaded web applications
  • work - Temporary working directories for web applications
  • temp - Directory used by the JVM for temporary files>

In CATALINA_HOME:

  • bin - Startup and shutdown scripts
  • lib - Libraries and classes, as explained below
  • endorsed - Libraries that override standard "Endorsed Standards". By default it's absent.

How to check

The easiest way to check what's your CATALINA_BASE and CATALINA_HOME is by running startup.sh, for example:

$ /usr/share/tomcat7/bin/startup.sh
Using CATALINA_BASE:   /usr/share/tomcat7
Using CATALINA_HOME:   /usr/share/tomcat7

You may also check where the Tomcat files are installed, by dpkg tool as below (Debian/Ubuntu):

dpkg -L tomcat7-common

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

React: "this" is undefined inside a component function

You should notice that this depends on how function is invoked ie: when a function is called as a method of an object, its this is set to the object the method is called on.

this is accessible in JSX context as your component object, so you can call your desired method inline as this method.

If you just pass reference to function/method, it seems that react will invoke it as independent function.

onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined

onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object

How to unpack and pack pkg file?

You might want to look into my fork of pbzx here: https://github.com/NiklasRosenstein/pbzx

It allows you to stream pbzx files that are not wrapped in a XAR archive. I've experienced this with recent XCode Command-Line Tools Disk Images (eg. 10.12 XCode 8).

pbzx -n Payload | cpio -i

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x

With Bootstrap 4 (and Font Awesome), we still can use the input-group wrapper around our form-control element, and now we can use an input-group-append (or input-group-prepend) wrapper with an input-group-text to get the job done:

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
  <div class="input-group-append">
    <span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
  </div>
</div>

It will look something like this (thanks to KyleMit for the screenshot):

enter image description here

Learn more by visiting the Input group documentation.

What is the difference between require_relative and require in Ruby?

Just look at the docs:

require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement.

For example, if you have unit test classes in the "test" directory, and data for them under the test "test/data" directory, then you might use a line like this in a test case:

require_relative "data/customer_data_1"

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

How to add a Java Properties file to my Java Project in Eclipse

To create a property class please select your package where you wants to create your property file.

Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

Is there any method to get the URL without query string?

Here's an approach using the URL() interface:

new URL(location.pathname, location.href).href

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Check the path of the file to be read. My code kept on giving me errors until I changed the path name to present working directory. The error was:

newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

How do I call paint event?

The Invalidate() Method will cause a repaint.

MSDN Link

LOAD DATA INFILE Error Code : 13

for Ubuntu users

I'm running mysql 5.6.28 on Ubuntu 15.10 and I just ran into the exact same problem, I had all the necessary flags in my.cnf tmpdir = /tmp local-infile=1 restarted mysql and I would still get LOAD DATA INFILE Error Code : 13

Just like Nelson mentionned the issue was "apparmor", sort of patronising mysql about permissions, I then found the solution thanks to this quick & easy tutorial.

basically, assuming your tmp dir would be /tmp :

Add new tmpdir entries to /etc/apparmor.d/local/usr.sbin.mysqld

sudo nano /etc/apparmor.d/local/usr.sbin.mysqld

*add this

/tmp/ r,
/mnt/foo/tmp/** rw,

Reload AppArmor

sudo service apparmor reload

Restart MySQL

sudo service mysql restart

I hope that'll help few Ubuntu-ers

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

The backgroundTint attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

The backgroundTintMode on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop, etc.

Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint attribute and the description along with various attributes will be available.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Maintaining href "open in new tab" with an onClick handler in React

Above answers are correct. But simply this worked for me

target={"_blank"}

How to change the project in GCP using CLI commands

I do prefer aliases, and for things that might need multiple commands, based on your project needs, I prefer functions...

Example

function switchGCPProject() {
        gcloud config set project [Project Name]
        // if you are using GKE use the following
        gcloud config set container/cluster [Cluster Name]
        // if you are using GCE use the following
        gcloud config set compute/zone [Zone]
        gcloud config set compute/region [region]
        // if you are using GKE use the following
        gcloud container clusters get-credentials [cluster name] --zone [Zone] --project [project name]
        export GOOGLE_APPLICATION_CREDENTIALS=path-to-credentials.json
}

When to use 'npm start' and when to use 'ng serve'?

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

How to set a Postgresql default value datestamp like 'YYYYMM'?

Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.

However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:

    CREATE TABLE my_table
    (
    id serial PRIMARY KEY not null,
    my_date date not null default CURRENT_DATE
    );

(CURRENT_DATE is basically a synonym for now() and a cast to date).

(Edited to use to_char).

Then you can get your output like:

SELECT id, to_char(my_date, 'yyyymm') FROM my_table;

Now, if you did really need to store that field as a string and ensure the format you could always do:

CREATE TABLE my_other_table
(
id serial PRIMARY KEY not null,
my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
);

Replace all occurrences of a String using StringBuilder?

Use the following:

/**
* Utility method to replace the string from StringBuilder.
* @param sb          the StringBuilder object.
* @param toReplace   the String that should be replaced.
* @param replacement the String that has to be replaced by.
* 
*/
public static void replaceString(StringBuilder sb,
                                 String toReplace,
                                 String replacement) {      
    int index = -1;
    while ((index = sb.lastIndexOf(toReplace)) != -1) {
        sb.replace(index, index + toReplace.length(), replacement);
    }
}

Is there a "not equal" operator in Python?

Use != or <>. Both stands for not equal.

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent. [Reference: Python language reference]

Parsing JSON giving "unexpected token o" error

Using JSON.stringify(data);:

$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});

CSS flex, how to display one item on first line and two on the next line

You can do something like this:

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.flex>div {_x000D_
  flex: 1 0 50%;_x000D_
}_x000D_
_x000D_
.flex>div:first-child {_x000D_
  flex: 0 1 100%;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div>Hi</div>_x000D_
  <div>Hello</div>_x000D_
  <div>Hello 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is a demo: http://jsfiddle.net/73574emn/1/

This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basis to be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;

How to get a microtime in Node.js?

Get hrtime as single number in one line:

const begin = process.hrtime();
// ... Do the thing you want to measure
const nanoSeconds = process.hrtime(begin).reduce((sec, nano) => sec * 1e9 + nano)

Array.reduce, when given a single argument, will use the array's first element as the initial accumulator value. One could use 0 as the initial value and this would work as well, but why do the extra * 0.

How to copy marked text in notepad++

It would be a great feature to have in Notepad++. I use the following technique to extract all the matches out of a file:

powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]*" -AllMatches | % { $_.Matches } | select-object Value > output.txt

And if you'd like only the distinct matches in a sorted list:

powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]" -AllMatches | % { $_.Matches } | select-object Value -unique | sort-object Value > output.txt

Date Format in Swift

To convert 2016-02-29 12:24:26 into a date, use this date formatter:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

Edit: To get the output Feb 29, 2016 use this date formatter:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"

Set a button background image iPhone programmatically

Code for background image of a Button in Swift 3.0

buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)

Hope this will help someone.

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

Gson library in Android Studio

Gradle:

dependencies {
   implementation 'com.google.code.gson:gson:2.8.5'
}

Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version> 
</dependency>

Gson jar downloads are available from Maven Central.

Secure random token in Node.js

0. Using nanoid third party library [NEW!]

A tiny, secure, URL-friendly, unique string ID generator for JavaScript

https://github.com/ai/nanoid

import { nanoid } from "nanoid";
const id = nanoid(48);


1. Base 64 Encoding with URL and Filename Safe Alphabet

Page 7 of RCF 4648 describes how to encode in base 64 with URL safety. You can use an existing library like base64url to do the job.

The function will be:

var crypto = require('crypto');
var base64url = require('base64url');

/** Sync */
function randomStringAsBase64Url(size) {
  return base64url(crypto.randomBytes(size));
}

Usage example:

randomStringAsBase64Url(20);
// Returns 'AXSGpLVjne_f7w5Xg-fWdoBwbfs' which is 27 characters length.

Note that the returned string length will not match with the size argument (size != final length).


2. Crypto random values from limited set of characters

Beware that with this solution the generated random string is not uniformly distributed.

You can also build a strong random string from a limited set of characters like that:

var crypto = require('crypto');

/** Sync */
function randomString(length, chars) {
  if (!chars) {
    throw new Error('Argument \'chars\' is undefined');
  }

  var charsLength = chars.length;
  if (charsLength > 256) {
    throw new Error('Argument \'chars\' should not have more than 256 characters'
      + ', otherwise unpredictability will be broken');
  }

  var randomBytes = crypto.randomBytes(length);
  var result = new Array(length);

  var cursor = 0;
  for (var i = 0; i < length; i++) {
    cursor += randomBytes[i];
    result[i] = chars[cursor % charsLength];
  }

  return result.join('');
}

/** Sync */
function randomAsciiString(length) {
  return randomString(length,
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
}

Usage example:

randomAsciiString(20);
// Returns 'rmRptK5niTSey7NlDk5y' which is 20 characters length.

randomString(20, 'ABCDEFG');
// Returns 'CCBAAGDGBBEGBDBECDCE' which is 20 characters length.

.htaccess rewrite to redirect root URL to subdirectory

I'll answer the original question not by pointing out another possible syntax (there are many amongst the other answers) but by pointing out something I have once had to deal with, that took me a while to figure out:

What am I doing wrong?

There is a possibility that %{HTTP_HOST} is not being populated properly, or at all. Although, I've only seen that occur in only one machine on a shared host, with some custom patched apache 2.2, it's a possibility nonetheless.

Clone private git repo with dockerfile

You often do not want to perform a git clone of a private repo from within the docker build. Doing the clone there involves placing the private ssh credentials inside the image where they can be later extracted by anyone with access to your image.

Instead, the common practice is to clone the git repo from outside of docker in your CI tool of choice, and simply COPY the files into the image. This has a second benefit: docker caching. Docker caching looks at the command being run, environment variables it includes, input files, etc, and if they are identical to a previous build from the same parent step, it reuses that previous cache. With a git clone command, the command itself is identical, so docker will reuse the cache even if the external git repo is changed. However, a COPY command will look at the files in the build context and can see if they are identical or have been updated, and use the cache only when it's appropriate.


If you are going to add credentials into your build, consider doing so with a multi-stage build, and only placing those credentials in an early stage that is never tagged and pushed outside of your build host. The result looks like:

FROM ubuntu as clone

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git
# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
COPY id_rsa /root/.ssh/id_rsa

# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

FROM ubuntu as release
LABEL maintainer="Luke Crooks <[email protected]>"

COPY --from=clone /repo /repo
...

More recently, BuildKit has been testing some experimental features that allow you to pass an ssh key in as a mount that never gets written to the image:

# syntax=docker/dockerfile:experimental
FROM ubuntu as clone
LABEL maintainer="Luke Crooks <[email protected]>"

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git

# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN --mount=type=secret,id=ssh_id,target=/root/.ssh/id_rsa \
    git clone [email protected]:User/repo.git

And you can build that with:

$ DOCKER_BUILDKIT=1 docker build -t your_image_name \
  --secret id=ssh_id,src=$(pwd)/id_rsa .

Note that this still requires your ssh key to not be password protected, but you can at least run the build in a single stage, removing a COPY command, and avoiding the ssh credential from ever being part of an image.


BuildKit also added a feature just for ssh which allows you to still have your password protected ssh keys, the result looks like:

# syntax=docker/dockerfile:experimental
FROM ubuntu as clone
LABEL maintainer="Luke Crooks <[email protected]>"

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git

# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN --mount=type=ssh \
    git clone [email protected]:User/repo.git

And you can build that with:

$ eval $(ssh-agent)
$ ssh-add ~/.ssh/id_rsa
(Input your passphrase here)
$ DOCKER_BUILDKIT=1 docker build -t your_image_name \
  --ssh default=$SSH_AUTH_SOCK .

Again, this is injected into the build without ever being written to an image layer, removing the risk that the credential could accidentally leak out.


To force docker to run the git clone even when the lines before have been cached, you can inject a build ARG that changes with each build to break the cache. That looks like:

# inject a datestamp arg which is treated as an environment variable and
# will break the cache for the next RUN command
ARG DATE_STAMP
# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

Then you inject that changing arg in the docker build command:

date_stamp=$(date +%Y%m%d-%H%M%S)
docker build --build-arg DATE_STAMP=$date_stamp .

How to vertically align elements in a div?

<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

Browser Coverage

Padding is invalid and cannot be removed?

I had the same problem trying to port a Go program to C#. This means that a lot of data has already been encrypted with the Go program. This data must now be decrypted with C#.

The final solution was PaddingMode.None or rather PaddingMode.Zeros.

The cryptographic methods in Go:

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha1"
    "encoding/base64"
    "io/ioutil"
    "log"

    "golang.org/x/crypto/pbkdf2"
)

func decryptFile(filename string, saltBytes []byte, masterPassword []byte) (artifact string) {

    const (
        keyLength         int = 256
        rfc2898Iterations int = 6
    )

    var (
        encryptedBytesBase64 []byte // The encrypted bytes as base64 chars
        encryptedBytes       []byte // The encrypted bytes
    )

    // Load an encrypted file:
    if bytes, bytesErr := ioutil.ReadFile(filename); bytesErr != nil {
        log.Printf("[%s] There was an error while reading the encrypted file: %s\n", filename, bytesErr.Error())
        return
    } else {
        encryptedBytesBase64 = bytes
    }

    // Decode base64:
    decodedBytes := make([]byte, len(encryptedBytesBase64))
    if countDecoded, decodedErr := base64.StdEncoding.Decode(decodedBytes, encryptedBytesBase64); decodedErr != nil {
        log.Printf("[%s] An error occur while decoding base64 data: %s\n", filename, decodedErr.Error())
        return
    } else {
        encryptedBytes = decodedBytes[:countDecoded]
    }

    // Derive key and vector out of the master password and the salt cf. RFC 2898:
    keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
    keyBytes := keyVectorData[:keyLength/8]
    vectorBytes := keyVectorData[keyLength/8:]

    // Create an AES cipher:
    if aesBlockDecrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
        log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
        return
    } else {

        // CBC mode always works in whole blocks.
        if len(encryptedBytes)%aes.BlockSize != 0 {
            log.Printf("[%s] The encrypted data's length is not a multiple of the block size.\n", filename)
            return
        }

        // Reserve memory for decrypted data. By definition (cf. AES-CBC), it must be the same lenght as the encrypted data:
        decryptedData := make([]byte, len(encryptedBytes))

        // Create the decrypter:
        aesDecrypter := cipher.NewCBCDecrypter(aesBlockDecrypter, vectorBytes)

        // Decrypt the data:
        aesDecrypter.CryptBlocks(decryptedData, encryptedBytes)

        // Cast the decrypted data to string:
        artifact = string(decryptedData)
    }

    return
}

... and ...

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha1"
    "encoding/base64"
    "github.com/twinj/uuid"
    "golang.org/x/crypto/pbkdf2"
    "io/ioutil"
    "log"
    "math"
    "os"
)

func encryptFile(filename, artifact string, masterPassword []byte) (status bool) {

    const (
        keyLength         int = 256
        rfc2898Iterations int = 6
    )

    status = false
    secretBytesDecrypted := []byte(artifact)

    // Create new salt:
    saltBytes := uuid.NewV4().Bytes()

    // Derive key and vector out of the master password and the salt cf. RFC 2898:
    keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
    keyBytes := keyVectorData[:keyLength/8]
    vectorBytes := keyVectorData[keyLength/8:]

    // Create an AES cipher:
    if aesBlockEncrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
        log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
        return
    } else {

        // CBC mode always works in whole blocks.
        if len(secretBytesDecrypted)%aes.BlockSize != 0 {
            numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
            enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
            copy(enhanced, secretBytesDecrypted)
            secretBytesDecrypted = enhanced
        }

        // Reserve memory for encrypted data. By definition (cf. AES-CBC), it must be the same lenght as the plaintext data:
        encryptedData := make([]byte, len(secretBytesDecrypted))

        // Create the encrypter:
        aesEncrypter := cipher.NewCBCEncrypter(aesBlockEncrypter, vectorBytes)

        // Encrypt the data:
        aesEncrypter.CryptBlocks(encryptedData, secretBytesDecrypted)

        // Encode base64:
        encodedBytes := make([]byte, base64.StdEncoding.EncodedLen(len(encryptedData)))
        base64.StdEncoding.Encode(encodedBytes, encryptedData)

        // Allocate memory for the final file's content:
        fileContent := make([]byte, len(saltBytes))
        copy(fileContent, saltBytes)
        fileContent = append(fileContent, 10)
        fileContent = append(fileContent, encodedBytes...)

        // Write the data into a new file. This ensures, that at least the old version is healthy in case that the
        // computer hangs while writing out the file. After a successfully write operation, the old file could be
        // deleted and the new one could be renamed.
        if writeErr := ioutil.WriteFile(filename+"-update.txt", fileContent, 0644); writeErr != nil {
            log.Printf("[%s] Was not able to write out the updated file: %s\n", filename, writeErr.Error())
            return
        } else {
            if renameErr := os.Rename(filename+"-update.txt", filename); renameErr != nil {
                log.Printf("[%s] Was not able to rename the updated file: %s\n", fileContent, renameErr.Error())
            } else {
                status = true
                return
            }
        }

        return
    }
}

Now, decryption in C#:

public static string FromFile(string filename, byte[] saltBytes, string masterPassword)
{
    var iterations = 6;
    var keyLength = 256;
    var blockSize = 128;
    var result = string.Empty;
    var encryptedBytesBase64 = File.ReadAllBytes(filename);

    // bytes -> string:
    var encryptedBytesBase64String = System.Text.Encoding.UTF8.GetString(encryptedBytesBase64);

    // Decode base64:
    var encryptedBytes = Convert.FromBase64String(encryptedBytesBase64String);
    var keyVectorObj = new Rfc2898DeriveBytes(masterPassword, saltBytes.Length, iterations);
    keyVectorObj.Salt = saltBytes;
    Span<byte> keyVectorData = keyVectorObj.GetBytes(keyLength / 8 + blockSize / 8);
    var key = keyVectorData.Slice(0, keyLength / 8);
    var iv = keyVectorData.Slice(keyLength / 8);

    var aes = Aes.Create();
    aes.Padding = PaddingMode.Zeros;
    // or ... aes.Padding = PaddingMode.None;
    var decryptor = aes.CreateDecryptor(key.ToArray(), iv.ToArray());
    var decryptedString = string.Empty;

    using (var memoryStream = new MemoryStream(encryptedBytes))
    {
        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
        {
            using (var reader = new StreamReader(cryptoStream))
            {
                decryptedString = reader.ReadToEnd();
            }
        }
    }

    return result;
}

How can the issue with the padding be explained? Just before encryption the Go program checks the padding:

// CBC mode always works in whole blocks.
if len(secretBytesDecrypted)%aes.BlockSize != 0 {
    numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
    enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
    copy(enhanced, secretBytesDecrypted)
    secretBytesDecrypted = enhanced
}

The important part is this:

enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
copy(enhanced, secretBytesDecrypted)

A new array is created with an appropriate length, so that the length is a multiple of the block size. This new array is filled with zeros. The copy method then copies the existing data into it. It is ensured that the new array is larger than the existing data. Accordingly, there are zeros at the end of the array.

Thus, the C# code can use PaddingMode.Zeros. The alternative PaddingMode.None just ignores any padding, which also works. I hope this answer is helpful for anyone who has to port code from Go to C#, etc.

Splitting a list into N parts of approximately equal length

Let's say you want to split a list [1, 2, 3, 4, 5, 6, 7, 8] into 3 element lists

like [[1,2,3], [4, 5, 6], [7, 8]], where if the last remaining elements left are less than 3, they are grouped together.

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_list2 = [my_list[i:i+3] for i in range(0, len(my_list), 3)]
print(my_list2)

Output: [[1,2,3], [4, 5, 6], [7, 8]]

Where length of one part is 3. Replace 3 with your own chunk size.

How do I prevent Conda from activating the base environment by default?

The answer depends a little bit on the version of conda that you have installed. For versions of conda >= 4.4, it should be enough to deactivate the conda environment after the initialization, so add

conda deactivate

right underneath

# <<< conda initialize <<<

How to copy file from one location to another location?

Using Stream

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Using Channel

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Using Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Using Java SE 7 Files class:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Or try Googles Guava :

https://github.com/google/guava

docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

Compare time:

    File source = new File("/Users/sidikov/tmp/source.avi");
    File dest = new File("/Users/sidikov/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
     
    //copy files using java.nio FileChannel
    source = new File("/Users/sidikov/tmp/sourceChannel.avi");
    dest = new File("/Users/sidikov/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
     
    //copy files using apache commons io
    source = new File("/Users/sidikov/tmp/sourceApache.avi");
    dest = new File("/Users/sidikov/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
     
    //using Java 7 Files class
    source = new File("/Users/sidikov/tmp/sourceJava7.avi");
    dest = new File("/Users/sidikov/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

Hunk #1 FAILED at 1. What's that mean?

Debugging Tips

  1. Add crlf to the end of the patch file and test if it works
  2. try the --ignore-whitespace command like in: markus@ubuntu:~$ patch -Np1 --ignore-whitespace -d software-1.0 < fix-bug.patch see tutorial by markus

What is the proper way to comment functions in Python?

While I agree that this should not be a comment, but a docstring as most (all?) answers suggest, I want to add numpydoc (a docstring style guide).

If you do it like this, you can (1) automatically generate documentation and (2) people recognize this and have an easier time to read your code.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

Delete ActionLink with confirm dialog

Try this :

<button> @Html.ActionLink(" ", "DeletePhoto", "PhotoAndVideo", new { id = item.Id }, new { @class = "modal-link1", @OnClick = "return confirm('Are you sure you to delete this Record?');" })</button>

jQuery Datepicker onchange event issue

I know this is an old question. But i couldnt get the jquery $(this).change() event to fire correctly onSelect. So i went with the following approach to fire the change event via vanilla js.

$('.date').datepicker({
     showOn: 'focus',
     dateFormat: 'mm-dd-yy',
     changeMonth: true,
     changeYear: true,
     onSelect: function() {
         var event;
         if(typeof window.Event == "function"){
             event = new Event('change');
             this.dispatchEvent(event);
         }   else {
             event = document.createEvent('HTMLEvents');
             event.initEvent('change', false, false);
             this.dispatchEvent(event);
         }
     }
});

iframe to Only Show a Certain Part of the Page

<div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 575px;">

Importing packages in Java

In Java you can only import class Names, or static methods/fields.

To import class use

import full.package.name.of.SomeClass;

We can also import static methods/fields in Java and this is how to import

import static full.package.nameOfClass.staticMethod;
import static full.package.nameOfClass.staticField;

When should I use nil and NULL in Objective-C?

nil is an empty value bound/corresponding with an object (the id type in Objective-C). nil got no reference/address, just an empty value.

NSString *str = nil;

So nil should be used, if we are dealing with an object.

if(str==nil)
    NSLog("str is empty");

Now NULL is used for non-object pointer (like a C pointer) in Objective-C. Like nil , NULL got no value nor address.

char *myChar = NULL;
struct MyStruct *dStruct = NULL;

So if there is a situation, when I need to check my struct (structure type variable) is empty or not then, I will use:

if (dStruct == NULL)
    NSLog("The struct is empty");

Let’s have another example, the

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

Of key-value observing, the context should be a C pointer or an object reference. Here for the context we can not use nil; we have to use NULL.

Finally the NSNull class defines a singleton object used to represent null values in collection objects(NSArray, NSDictionary). The [NSNull null] will returns the singleton instance of NSNull. Basically [NSNull null] is a proper object.

There is no way to insert a nil object into a collection type object. Let's have an example:

NSMutableArray *check = [[NSMutableArray alloc] init];
[check addObject:[NSNull null]];
[check addObject:nil];

On the second line, we will not get any error, because it is perfectly fair to insert a NSNull object into a collection type object. On the third line, we will get "object cannot be nil" error. Because nil is not an object.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

SoapUI "failed to load url" error when loading WSDL

I have had the same problem. I resolved it by disabling the proxy in the SoapUI preferences. (source : http://www.eviware.com/forum/viewtopic.php?f=13&t=12460)

What is the purpose of willSet and didSet in Swift?

The willSet and didSet observers for the properties whenever the property is assigned a new value. This is true even if the new value is the same as the current value.

And note that willSet needs a parameter name to work around, on the other hand, didSet does not.

The didSet observer is called after the value of property is updated. It compares against the old value. If the total number of steps has increased, a message is printed to indicate how many new steps have been taken. The didSet observer does not provide a custom parameter name for the old value, and the default name of oldValue is used instead.

Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();

How do you set the title color for the new Toolbar?

With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

<com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>

You can also use a custom style:

<com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>

or (extending the Widget.MaterialComponents.Toolbar style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>

enter image description here

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

or (using the Widget.MaterialComponents.Toolbar style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

Rotate label text in seaborn factorplot

I had a problem with the answer by @mwaskorn, namely that

g.set_xticklabels(rotation=30)

fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add

plt.xticks(rotation=45)

passing argument to DialogFragment

Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:

so you have to create a companion objet to create new newInstance function

you can set the paremter of the function whatever you want. using

 val args = Bundle()

you can set your args.

You can now use args.putSomthing to add you args which u give as a prameter in your newInstance function. putString(key:String,str:String) to add string for example and so on

Now to get the argument you can use arguments.getSomthing(Key:String)=> like arguments.getString("1")

here is a full example

class IntervModifFragment : DialogFragment(), ModContract.View
{
    companion object {
        fun newInstance(  plom:String,type:String,position: Int):IntervModifFragment {
            val fragment =IntervModifFragment()
            val args = Bundle()
            args.putString( "1",plom)
            args.putString("2",type)
            args.putInt("3",position)
            fragment.arguments = args
            return fragment
        }
    }

...
    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fillSpinerPlom(view,arguments.getString("1"))
         fillSpinerType(view, arguments.getString("2"))
        confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})


        val dateSetListener = object : DatePickerDialog.OnDateSetListener {
            override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
                                   dayOfMonth: Int) {
                val datep= DateT(year,monthOfYear,dayOfMonth)
                updateDateInView(datep.date)
            }
        }

    }
  ...
}

Now how to create your dialog you can do somthing like this in another class

  val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)

like this for example

class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
   ... 
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        ...
        holder.btn_update!!.setOnClickListener {
           val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
           val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
            dialog.show(ft, ContentValues.TAG)
        }
        ...
    }
..

}

What is the meaning of "this" in Java?

In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.

public class MyDialog extends JDialog implements ActionListener
{
    public MyDialog()
    {
        JButton myButton = new JButton("Hello");
        myButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Hurdy Gurdy!");
    }

}

How to fix Subversion lock error

svn help unlock

And find locker after all - lock isn't needed in most cases

How to npm install to a specified directory?

As of npm version 3.8.6, you can use

npm install --prefix ./install/here <package>

to install in the specified directory. NPM automatically creates node_modules folder even when a node_modules directory already exists in the higher up hierarchy. You can also have a package.json in the current directory and then install it in the specified directory using --prefix option:

npm install --prefix ./install/here

As of npm 6.0.0, you can use

npm install --prefix ./install/here ./

to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.

NOTE: NPM honours the path that you've specified through the --prefix option. It resolves as per npm documentation on folders, only when npm install is used without the --prefix option.

How can I create a temp file with a specific extension with .NET?

Based on answers I found from the internet, I come to my code as following:

public static string GetTemporaryFileName()
{       
    string tempFilePath = Path.Combine(Path.GetTempPath(), "SnapshotTemp");
    Directory.Delete(tempFilePath, true);
    Directory.CreateDirectory(tempFilePath);
    return Path.Combine(tempFilePath, DateTime.Now.ToString("MMddHHmm") + "-" + Guid.NewGuid().ToString() + ".png");
}

And as C# Cookbook by Jay Hilyard, Stephen Teilhet pointed in Using a Temporary File in Your Application:

  • you should use a temporary file whenever you need to store information temporarily for later retrieval.

  • The one thing you must remember is to delete this temporary file before the application that created it is terminated.

  • If it is not deleted, it will remain in the user’s temporary directory until the user manually deletes it.

Change icon on click (toggle)

If your icon is based on the text in the block (ligatures) rather the class of the block then the following will work. This example uses the Google Material Icons '+' and '-' icons as part of MaterializeCSS.

<a class="btn-class"><i class="material-icons">add</i></a>

$('.btn-class').on('click',function(){
    if ($(this).find('i').text() == 'add'){
        $(this).find('i').text('remove');
    } else {
        $(this).find('i').text('add');
    }
});

Edit: Added missing ); needed for this to function properly.

It also works for JQuery post 1.9 where toggling of functions was deprecated.

CSS hide scroll bar if not needed

Set overflow-y property to auto, or remove the property altogether if it is not inherited.

How to list only files and not directories of a directory Bash?

Just adding on to carlpett's answer. For a much useful view of the files, you could pipe the output to ls.

find . -maxdepth 1 -type f|ls -lt|less

Shows the most recently modified files in a list format, quite useful when you have downloaded a lot of files, and want to see a non-cluttered version of the recent ones.

Imported a csv-dataset to R but the values becomes factors

Both the data import function (here: read.csv()) as well as a global option offer you to say stringsAsFactors=FALSE which should fix this.

Execute php file from another php

exec('wget http://<url to the php script>') worked for me.

It enable me to integrate two php files that were designed as web pages and run them as code to do work without affecting the calling page

Adding minutes to date time in PHP

Use strtotime("+5 minute", $date);


Example:

$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);

How to submit a form when the return key is pressed?

Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.

So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.

But even then, there are still 2 conditions to be met for this to work without JS:

a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php

b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden. What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.

<form action="hello.php" method="get">
  Name: <input type="text" name="name"/><br/>
  Pwd: <input type="password" name="password"/><br/>
  <div class="yourCustomDiv"/>
  <input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>

How to measure time in milliseconds using ANSI C?

Under windows:

SYSTEMTIME t;
GetLocalTime(&t);
swprintf_s(buff, L"[%02d:%02d:%02d:%d]\t", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);

Checking for empty queryset in Django

I disagree with the predicate

if not orgs:

It should be

if not orgs.count():

I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.

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

Most of these answers are "rounding" the radius of the earth. If you check these against other distance calculators (such as geopy), these functions will be off.

This works well:

from math import radians, cos, sin, asin, sqrt

def haversine(lat1, lon1, lat2, lon2):

      R = 3959.87433 # this is in miles.  For Earth radius in kilometers use 6372.8 km

      dLat = radians(lat2 - lat1)
      dLon = radians(lon2 - lon1)
      lat1 = radians(lat1)
      lat2 = radians(lat2)

      a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
      c = 2*asin(sqrt(a))

      return R * c

# Usage
lon1 = -103.548851
lat1 = 32.0004311
lon2 = -103.6041946
lat2 = 33.374939

print(haversine(lat1, lon1, lat2, lon2))

Better way to sum a property value in an array

I was already using jquery. But I think its intuitive enough to just have:

var total_amount = 0; 
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });

This is basically just a short-hand version of @akhouri's answer.

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

Convert pandas dataframe to NumPy array

Try this:

a = numpy.asarray(df)

What is the difference between <section> and <div>?

<section></section>

The HTML <section> element represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading. Each <section> should be identified, typically by including a heading (<h1>-<h6> element) as a child of the <section> element. For Details Please following link.

References :


<div></div>

The HTML <div> element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

References: - http://www.w3schools.com/tags/tag_div.asp - https://developer.mozilla.org/en/docs/Web/HTML/Element/div


Here are some links that discuss more about the differences between them:

How to loop through elements of forms with JavaScript?

You can use getElementsByTagName function, it returns a HTMLCollection of elements with the given tag name.

var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
    if(elements[i].value == "") {
        alert('empty');
        //Do something here
    }
}

DEMO

You can also use document.myform.getElementsByTagName provided you have given a name to yoy form

DEMO with form Name

TypeError: 'list' object cannot be interpreted as an integer

In playSound(), instead of

for i in range(myList):

try

for i in myList:

This will iterate over the contents of myList, which I believe is what you want. range(myList) doesn't make any sense.

How to implement WiX installer upgrade?

I read the WiX documentation, downloaded examples, but I still had plenty of problems with upgrades. Minor upgrades don't execute uninstall of the previous products despite of possibility to specify those uninstall. I spent more that a day for investigations and found that WiX 3.5 intoduced a new tag for upgrades. Here is the usage:

<MajorUpgrade Schedule="afterInstallInitialize"
        DowngradeErrorMessage="A later version of [ProductName] is already installed. Setup will now exit." 
        AllowDowngrades="no" />

But the main reason of problems was that documentation says to use the "REINSTALL=ALL REINSTALLMODE=vomus" parameters for minor and small upgrades, but it doesn't say that those parameters are FORBIDDEN for major upgrades - they simply stop working. So you shouldn't use them with major upgrades.

ComboBox: Adding Text and Value to an Item (no Binding Source)

This is a very simple solution for windows forms if all is needed is the final value as a (string). The items' names will be displayed on the Combo Box and the selected value can be easily compared.

List<string> items = new List<string>();

// populate list with test strings
for (int i = 0; i < 100; i++)
            items.Add(i.ToString());

// set data source
testComboBox.DataSource = items;

and on the event handler get the value (string) of the selected value

string test = testComboBox.SelectedValue.ToString();

How to check if a value exists in a dictionary (python)

In Python 3 you can use the values() function of the dictionary. It returns a view object of the values. This, in turn, can be passed to the iter function which returns an iterator object. The iterator can be checked using in, like this,

'one' in iter(d.values())

Or you can use the view object directly since it is similar to a list

'one' in d.values()

How to disable <br> tags inside <div> by css?

You could alter your CSS to render them less obtrusively, e.g.

div p,
div br {
    display: inline;
}

http://jsfiddle.net/zG9Ax/

or - as my commenter points out:

div br {
    display: none;
}

but then to achieve the example of what you want, you'll need to trim the p down, so:

div br {
    display: none;
}
div p {
    padding: 0;
    margin: 0;
}

http://jsfiddle.net/zG9Ax/1

Use own username/password with git and bitbucket

The prompt:

Password for 'https://[email protected]':

suggests, that you are using https not ssh. SSH urls start with git@, for example:

[email protected]:beginninggit/alias.git

Even if you work alone, with a single repo that you own, the operation:

git push

will cause:

Password for 'https://[email protected]':

if the remote origin starts with https.

Check your remote with:

git remote -v

The remote depends on git clone. If you want to use ssh clone the repo using its ssh url, for example:

git clone [email protected]:user/repo.git

I suggest you to start with git push and git pull for your private repo.

If that works, you have two joices suggested by Lazy Badger:

  • Pull requests
  • Team work

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

Surprisingly, not all of the necessary pieces are documented here, at least for Xcode 8.

My case was a custom-built framework as part of the same workspace. It turns out it was being built incorrectly. Based on jeremyhu's last response to this thread:

https://forums.developer.apple.com/thread/4687

I had to set Dynamic Library Install Name Base (DYLIB_INSTALL_NAME_BASE) under Build Settings of the Framework Project and then rebuild it. It was incorrectly set to $(LOCAL_LIBRARY_DIR) and I had to change it to @rpath.

So in the link processing stage in the App Project, it was instructing the host App to dynamically load the framework at runtime from /Library/Frameworks/fw.Framework/fw (as in, the root of the runtime filesystem) rather than path-to-App/Frameworks/fw.Framework/fw

Regarding all the other settings: it does have to be in 3 places in Build Phases, but these are all set at once when you just add it to the Embedded Binaries setting of the General tab of the hosting App.

I did not have to set up an extra Copy Files phase, which seems intuitively redundant with respect to the embedding stage anyway. By checking the tail end of the build transcript we can assure that that's not necessary.

PBXCp /Users/xyz/Library/Developer/Xcode/DerivedData/MyApp-cbcnqafhywqkjufwsvbzckecmjjs/Build/Products/Debug-iphoneos/MyFramework.framework

[Many verbose lines removed, but it's clear from the simplified transcript in the Xcode UI.]

I still have no idea why Xcode set the DYLIB_INSTALL_NAME_BASE value incorrectly on me.

Constructor of an abstract class in C#

I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents

abstract classes are normal classes with A few exceptions

  1. You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
  2. It may has abstract function.

Python: Get HTTP headers from urllib2.urlopen call?

urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).

Windows command for file size only

This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir:

> dir Microsoft.WindowsAzure.Storage.xml

Results in:

Directory of C:\PathToTheFile

08/10/2015  10:57 AM         2,905,897 Microsoft.WindowsAzure.Storage.xml
               1 File(s)      2,905,897 bytes
               0 Dir(s)  759,192,064,000 bytes free

How to len(generator())

The conversion to list that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:

sum(1 for x in generator)

Of course, be aware that this might be slower than len(list(generator)) in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).

Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.

How do I convert datetime.timedelta to minutes, hours in Python?

I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.

def format_timedelta(td):
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    hours, minutes, seconds = int(hours), int(minutes), int(seconds)
    if hours < 10:
        hours = '0%s' % int(hours)
    if minutes < 10:
        minutes = '0%s' % minutes
    if seconds < 10:
        seconds = '0%s' % seconds
    return '%s:%s:%s' % (hours, minutes, seconds)

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Overall:You persist entity that is violating database rules like as saving entity that has varchar field over 250 chars ,something like that.

In my case it was a squishy problem with TestEntityManager ,because it use HSQL database /in memory database/ and it persist the user but when you try to find it ,it drops the same exception :/

@RunWith(SpringRunner.class)
@ContextConfiguration(classes= Application.class)
@DataJpaTest
@ActiveProfiles("test")
public class UserServicesTests {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private UserRepository userRepository;

@Test
public void oops() {
    User user = new User();
    user.setUsername("Toshko");
    //EMAIL IS REQUIRED:
    //user.setEmail("OPS");
    this.testEntityManager.persist(user);

    //HERE COMES TE EXCEPTION BECAUSE THE EMAIL FIELD IN TE DATABASE IS REQUIRED :
    this.userRepository.findUserByUsername("Toshko");

    System.out.println();
}
}

HTML.ActionLink method

I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.

Just to clarify things, this is the version that works (adaption of Joseph's example):

Html.ActionLink(article.Title, 
    "Login",  // <-- ActionMethod
    "Item",   // <-- Controller Name
    new { id = article.ArticleID }, // <-- Route arguments.
    null  // <-- htmlArguments .. which are none
    )

How to use NULL or empty string in SQL

SELECT *
FROM   Table
WHERE  column like '' or column IS NULL OR LEN(column) = 0

How to get the part of a file after the first line that matches a regular expression?

Alternatives to the excellent sed answer by jfgagne, and which don't include the matching line :

What is the difference between substr and substring?

As hinted at in yatima2975's answer, there is an additional difference:

substr() accepts a negative starting position as an offset from the end of the string. substring() does not.

From MDN:

If start is negative, substr() uses it as a character index from the end of the string.

So to sum up the functional differences:

substring(begin-offset, end-offset-exclusive) where begin-offset is 0 or greater

substr(begin-offset, length) where begin-offset may also be negative

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

How to convert a string into double and vice versa?

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

Doing a cleanup action just before Node.js exits

function fnAsyncTest(callback) {
    require('fs').writeFile('async.txt', 'bye!', callback);
}

function fnSyncTest() {
    for (var i = 0; i < 10; i++) {}
}

function killProcess() {

    if (process.exitTimeoutId) {
        return;
    }

    process.exitTimeoutId = setTimeout(() => process.exit, 5000);
    console.log('process will exit in 5 seconds');

    fnAsyncTest(function() {
        console.log('async op. done', arguments);
    });

    if (!fnSyncTest()) {
        console.log('sync op. done');
    }
}

// https://nodejs.org/api/process.html#process_signal_events
process.on('SIGTERM', killProcess);
process.on('SIGINT', killProcess);

process.on('uncaughtException', function(e) {

    console.log('[uncaughtException] app will be terminated: ', e.stack);

    killProcess();
    /**
     * @https://nodejs.org/api/process.html#process_event_uncaughtexception
     *  
     * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process. 
     * It is not safe to resume normal operation after 'uncaughtException'. 
     * If you do use it, restart your application after every unhandled exception!
     * 
     * You have been warned.
     */
});

console.log('App is running...');
console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

process.stdin.resume();
// just for testing

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Web link to specific whatsapp contact

I tried all combination for swiss numbers on my webpage. Below my results:

Doesn't work for Android and iOS

https://wa.me/0790000000/?text=myText

Works for iOS but doesn't work for Android

https://wa.me/0041790000000/?text=myText
https://wa.me/+41790000000/?text=myText

Works for Android and iOS:

https://wa.me/41790000000/?text=myText
https://wa.me/041790000000/?text=myText

Hope this information helps somebody!

SQL to find the number of distinct values in a column

select Count(distinct columnName) as columnNameCount from tableName 

no target device found android studio 2.1.1

This happened to me on android studio version 4 after doing an update to the IDE. The "invalidate caches and restart" option fixed it.

Format number to 2 decimal places

When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.

Examples:

Without rounding:

TRUNCATE(0.166, 2)
-- will be evaluated to 0.16

TRUNCATE(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php

With rounding:

ROUND(0.166, 2)
-- will be evaluated to 0.17

ROUND(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-round-function.php

Parsing Query String in node.js

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

Could not resolve this reference. Could not locate the assembly

Maybe it will help someone, but sometimes Name tag might be missing for a reference and it leads that assembly cannot be found when building with MSBuild. Make sure that Name tag is available for particular reference csproj file, for example,

    <ProjectReference Include="..\MyDependency1.csproj">
      <Project>{9A2D95B3-63B0-4D53-91F1-5EFB99B22FE8}</Project>
      <Name>MyDependency1</Name>
    </ProjectReference>

NLTK and Stopwords Fail #lookuperror

I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:

Open your terminal/command-line and type python then

>>> import nltk .>>> nltk.download("stopwords")

This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords.

If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.

How do I remove all null and empty string values from an object?

Here is the optimized code snippet to remove empty arrays/objects as well:

function removeNullsInObject(obj) {
    if( typeof obj === 'string' ){ return; }
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if ($.isArray(value)) {
            if( value.length === 0 ){ delete obj[key]; return; }
            $.each(value, function (k,v) {
                removeNullsInObject(v);
            });
        } else if (typeof value === 'object') {
            if( Object.keys(value).length === 0 ){ 
                delete obj[key]; return; 
            }
            removeNullsInObject(value);
        }
    }); 
 }

Thanks @Alexis king :)

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

How to remove class from all elements jquery

The best to remove a class in jquery from all the elements is to target via element tag. e.g.,

$("div").removeClass("highlight");

Groovy Shell warning "Could not open/create prefs root node ..."

If anyone is trying to solve this on a 64-bit version of Windows, you might need to create the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

What does the explicit keyword mean?

The explicit-keyword can be used to enforce a constructor to be called explicitly.

class C{
public:
    explicit C(void) = default;
};

int main(void){
    C c();
    return 0;
}

the explicit-keyword in front of the constructor C(void) tells the compiler that only explicit call to this constructor is allowed.

The explicit-keyword can also be used in user-defined type cast operators:

class C{
public:
    explicit inline operator bool(void) const{
        return true;
    }
};

int main(void){
    C c;
    bool b = static_cast<bool>(c);
    return 0;
}

Here, explicit-keyword enforces only explicit casts to be valid, so bool b = c; would be an invalid cast in this case. In situations like these explicit-keyword can help programmer to avoid implicit, unintended casts. This usage has been standardized in C++11.

Remove last character from string. Swift language

The easiest way to trim the last character of the string is:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]

Detecting input change in jQuery?

With HTML5 and without using jQuery, you can using the input event:

var input = document.querySelector('input');

input.addEventListener('input', function()
{
    console.log('input changed to: ', input.value);
});

This will fire each time the input's text changes.

Supported in IE9+ and other browsers.

Try it live in a jsFiddle here.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Override standard close (X) button in a Windows Form

The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.ApplicationExitCall)
        {
            return;
        }
        else
        {
            e.Cancel = true;
            WindowState = FormWindowState.Minimized;
        }            
    }

This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.

Querying data by joining two tables in two database on different servers

You could try the following:

select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId

Reading from text file until EOF repeats last line

I like this example, which for now, leaves out the check which you could add inside the while block:

ifstream iFile("input.txt");        // input.txt has integers, one per line
int x;

while (iFile >> x) 
{
    cerr << x << endl;
}

Not sure how safe it is...

Getting GET "?" variable in laravel

It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.

There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):

Mode 1

Route:

Route::get('computers={id}', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers=500

Controler - You can access the {id} paramter in the Controlller by:

public function index(Request $request, $id){
   return $id;
}

Mode 2

Route:

Route::get('computers', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers?id=500

Controler - You can access the ?id paramter in the Controlller by:

public function index(Request $request){
   return $request->input('id');
}

How do I use spaces in the Command Prompt?

If double quotes do not solve the issue then try e.g.

dir /X ~1 c:\

to get a list of alternative file or directory names. Example output:

11/09/2014 12:54 AM             8,065  DEFAUL~1.XML Default Desktop Policy.xml
06/12/2014  03:49 PM    <DIR>          PROGRA~1     Program Files 
10/12/2014  12:46 AM    <DIR>          PROGRA~2     Program Files (x86)

Now use the short 8 character file or folder name in the 5th column, e.g. PROGRA~1 or DEFAUL~1.XML, in your commands. For instance:

set JAVA_HOME=c:\PROGRA~1\Java\jdk1.6.0_45 

XmlWriter to Write to a String Instead of to a File

Well I think the simplest and fastest solution here would be just to:

StringBuilder sb = new StringBuilder();

using (var writer = XmlWriter.Create(sb, settings))
{
    ... // Whatever code you have/need :)

    sb = sb.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\""); //Or whatever uft you want/use.
    //Before you finally save it:
    File.WriteAllText("path\\dataName.xml", sb.ToString());
}

SQL Query To Obtain Value that Occurs more than once

For postgresql:

SELECT * AS rec 
FROM (
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1;

jQuery toggle CSS?

For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):

$('#user_button').toggle(function () {
    $("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
    $("#user_button").css({borderBottomLeftRadius: "5px"});
});

Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.

$('#user_button').toggle(function () {
    $("#user_button").addClass("active");
}, function () {
    $("#user_button").removeClass("active");
});