Programs & Examples On #Directory.delete

Cannot delete directory with Directory.Delete(path, true)

I had the very same problem under Delphi. And the end result was that my own application was locking the directory I wanted to delete. Somehow the directory got locked when I was writing to it (some temporary files).

The catch 22 was, I made a simple change directory to it's parent before deleting it.

How do I fix the indentation of selected lines in Visual Studio

For the Mac users.

For selecting all of the code in the document => cmd+A

For formatting selected code => cmd+K, cmd+F

Vertically align text next to an image?

The technique used in the accepted answer works only for single-lined text (demo), but not multi-line text (demo) - as noted there.

If anyone needs to vertically center multi-lined text to an image, here are a few ways (Methods 1 and 2 inspired by this CSS-Tricks article)

Method #1: CSS tables (FIDDLE) (IE8+ (caniuse))

CSS:

div {
    display: table;
}
span {
    vertical-align: middle;
    display: table-cell;
}

Method #2: Pseudo element on container (FIDDLE) (IE8+)

CSS:

div {
   height: 200px; /* height of image */
}

div:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

img {
    position: absolute;
}

span {
  display: inline-block;
  vertical-align: middle;
  margin-left: 200px;  /* width of image */
}

Method #3: Flexbox (FIDDLE) (caniuse)

CSS (The above fiddle contains vendor prefixes):

div {   
    display: flex; 
    align-items: center;    
}
img {
    min-width: 200px; /* width of image */
}

Observable.of is not a function

I am using Angular 5.2 and RxJS 5.5.6

This code did not work:

     import { Observable,of } from 'rxjs/Observable';

     getHeroes(): Observable<Hero[]> {
        return of(Hero[]) HEROES;

      }

Below code worked:

    import { Observable } from 'rxjs/Observable';
    import { Subscriber } from 'rxjs/Subscriber';

     getHeroes(): Observable<Hero[]> 
     {
          return Observable.create((observer: Subscriber<any>) => {
              observer.next(HEROES);
              observer.complete();
          });

      }

Calling method:

this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);

I think they might moved/changed of() functionality in RxJS 5.5.2

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

What's the best way to use R scripts on the command line (terminal)?

Miguel Sanchez's response is the way it should be. The other way executing Rscript could be 'env' command to run the system wide RScript.

#!/usr/bin/env Rscript

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?

If not please let me know where you get stuck.

Install Common Dependencies

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

Install NumArray 1.5.2

wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install

Install Numeric 23.8

wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install

Install HDF5 1.6.5

wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make 
sudo make install

Install Nanoengineer

git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install

Troubleshooting

On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc is inserted in CFLAGS and gcc will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...

touch sim/src/x86_64-linux-gnu-gcc

If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...

output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);

If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running

export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install

If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:

#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";

If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files

/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py

that look like this:

from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB

to look like this:

from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB

I also found an additional troubleshooting text file that has been removed, but you can find it here

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

This is a straightforward example Ravi Wallau's solution:

public String buildSafeURL(String partialURL, String documentName)
        throws ScriptException {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager
            .getEngineByName("JavaScript");

    String urlSafeDocumentName = String.valueOf(scriptEngine
            .eval("encodeURIComponent('" + documentName + "')"));
    String safeURL = partialURL + urlSafeDocumentName;

    return safeURL;
}

public static void main(String[] args) {
    EncodeURIComponentDemo demo = new EncodeURIComponentDemo();
    String partialURL = "https://www.website.com/document/";
    String documentName = "Tom & Jerry Manuscript.pdf";

    try {
        System.out.println(demo.buildSafeURL(partialURL, documentName));
    } catch (ScriptException se) {
        se.printStackTrace();
    }
}

Output: https://www.website.com/document/Tom%20%26%20Jerry%20Manuscript.pdf

It also answers the hanging question in the comments by Loren Shqipognja on how to pass a String variable to encodeURIComponent(). The method scriptEngine.eval() returns an Object, so it can converted to String via String.valueOf() among other methods.

How can I enable MySQL's slow query log without restarting MySQL?

Find log enabled or not?

SHOW VARIABLES LIKE '%log%';

Set the logs:-

SET GLOBAL general_log = 'ON'; 

SET GLOBAL slow_query_log = 'ON'; 

Pass element ID to Javascript function

This'll work:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            function myFunc(id)
            {
                alert(id);
            }
        </script>
    </head>

    <body>
        <button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
        <button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
        <button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
        <button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
    </body>
</html>

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

MetadataException: Unable to load the specified metadata resource

I got this error when my emdx file was deleted by a prebuild command, quite simply. Took me a while before realizing it was that simple.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data I'm looking through has a 10 as the first value, then numbers[i]<smallest will be true (because 10 is < Integer.MAX_VALUE) and we'll update smallest to be 10. Similarly, numbers[i]>largest will be true because 10 is > Integer.MIN_VALUE and we'll update largest. And so on.

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest and largest.


Note the point Onome Sotu makes in the comments:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

Which is true; here's a simpler example demonstrating the problem (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = Integer.MAX_VALUE;
        int largest  = Integer.MIN_VALUE;
        for (int value : values) {
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
    }
}

To fix it, either:

  1. Don't use else, or

  2. Start with smallest and largest equal to the first element, and then loop the remaining elements, keeping the else if.

Here's an example of that second one (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = values[0];
        int largest  = values[0];
        for (int n = 1; n < values.length; ++n) {
            int value = values[n];
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 5
    }
}

Initialize class fields in constructor or at declaration?

What if I told you, it depends?

I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain.

If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.

In a real time system, I question if I even need the variable or constant at all.

And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

How do I add a newline to a windows-forms TextBox?

You can try this :

"This is line-1 \r\n This is line-2"

Ansible: Store command's stdout in new variable?

If you want to go further and extract the exact information you want from the Playbook results, use JSON query language like jmespath, an example:

  - name: Sample Playbook
    // Fill up your task
    no_log: True
    register: example_output

  - name: Json Query
    set_fact:
      query_result:
        example_output:"{{ example_output | json_query('results[*].name') }}"

Visual Studio: How to break on handled exceptions?

With a solution open, go to the Debug - Exceptions (Ctrl+D,E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.

EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?

Efficient evaluation of a function at every cell of a NumPy array

You could just vectorize the function and then apply it directly to a Numpy array each time you need it:

import numpy as np

def f(x):
    return x * x + 3 * x - 2 if x > 0 else x * 5 + 8

f = np.vectorize(f)  # or use a different name if you want to keep the original f

result_array = f(A)  # if A is your Numpy array

It's probably better to specify an explicit output type directly when vectorizing:

f = np.vectorize(f, otypes=[np.float])

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Get the item doubleclick event of listview

Was having a similar issue with a ListBox wanting to open a window (Different View) with the SelectedItem as the context (in my case, so I can edit it).

The three options I've found are: 1. Code Behind 2. Using Attached Behaviors 3. Using Blend's i:Interaction and EventToCommand using MVVM-Light.

I went with the 3rd option, and it looks something along these lines:

<ListBox x:Name="You_Need_This_Name"  
ItemsSource="{Binding Your_Collection_Name_Here}"
SelectedItem="{Binding Your_Property_Name_Here, UpdateSourceTrigger=PropertyChanged}"
... rest of your needed stuff here ...
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
    <Command:EventToCommand Command="{Binding Your_Command_Name_Here}" 
        CommandParameter="{Binding ElementName=You_Need_This_Name,Path=SelectedItem}"     />
    </i:EventTrigger>
</i:Interaction.Triggers>

That's about it ... when you double click on the item you want, your method on the ViewModel will be called with the SelectedItem as parameter, and you can do whatever you want there :)

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

How to save a Seaborn plot into a file

This works for me

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

Android XXHDPI resources

The DPI of the screen of the Nexus 10 is ±300, which is in the unofficial xhdpi range of 280-400.

Usually, devices use resources designed for their density. But there are exceptions, and exceptions might be added in the future. The Nexus 10 uses xxhdpi resources when it comes to launcher icons.

The standard quantised DPI for xxhdpi is 480 (which means screens with a DPI somewhere in the range of 400-560 are probably xxhdpi).

Using AND/OR in if else PHP statement

AND is && and OR is || like in C.

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

How do I separate an integer into separate digits in an array in JavaScript?

I ended up solving it as follows:

_x000D_
_x000D_
const n = 123456789;_x000D_
let toIntArray = (n) => ([...n + ""].map(Number));_x000D_
console.log(toIntArray(n));
_x000D_
_x000D_
_x000D_

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Is there a css cross-browser value for "width: -moz-fit-content;"?

width: intrinsic;           /* Safari/WebKit uses a non-standard name */
width: -moz-max-content;    /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */

RESTful URL design for search

Justin's answer is probably the way to go, although in some applications it might make sense to consider a particular search as a resource in its own right, such as if you want to support named saved searches:

/search/{searchQuery}

or

/search/{savedSearchName}

JavaScript open in a new window, not tab

I may be wrong, but from what I understand, this is controlled by the user's browser preferences, and I do not believe that this can be overridden.

How to get time (hour, minute, second) in Swift 3 using NSDate?

This might be handy for those who want to use the current date in more than one class.

extension String {


func  getCurrentTime() -> String {

    let date = Date()
    let calendar = Calendar.current


    let year = calendar.component(.year, from: date)
    let month = calendar.component(.month, from: date)
    let day = calendar.component(.day, from: date)
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)

    let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"

    return realTime
}

}

Usage

        var time = ""
        time = time.getCurrentTime()
        print(time)   // 1900-12-09-12-59

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

6.5.3.4 The sizeof operator:

3 When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

6.7.2.1 Structure and union specifiers:

13 ... There may be unnamed padding within a structure object, but not at its beginning.

and:

15 There may be unnamed padding at the end of a structure or union.

The new C99 flexible array member feature (struct S {int is[];};) may also affect padding:

16 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

Annex J Portability Issues reiterates:

The following are unspecified: ...

  • The value of padding bytes when storing values in structures or unions (6.2.6.1)

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

5.3.3 Sizeof:

2 When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

9.2 Class members:

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ]

I only know enough C++ to understand the note :-)

What is the difference between Normalize.css and Reset CSS?

This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:

  • Normalize.css - as the name suggests, it normalizes styles in the browsers for their user agents, i.e. makes them the same across all browsers due to the reason by default they're slightly different.

Example: <h1> tag inside <section> by default Google Chrome will make smaller than the "expected" size of <h1> tag. Microsoft Edge on the other hand is making the "expected" size of <h1> tag. Normalize.css will make it consistent.

Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.

  • Reset CSS - as the name suggests, it resets all styles, i.e. it removes all browser's user agent styles.

Example: it would do something like that below:

html, body, div, span, ..., audio, video {  
   margin: 0;  
   padding: 0;  
   border: 0;  
   font-size: 100%;  
   font: inherit;  
   vertical-align: baseline; 
}

Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.

The supported functionality:

  • multiple databases which can be selected at connection definition
  • CRUD operations like query tables
  • scheme operations
  • basic modelling support: show tables without pk, fk, connections

Not supported functionalities:

  • no table or field completion
  • no indexes are shown in a tab
  • no constraints are shown in a tab like: fk, pk-s, unique, or others
  • no table or field completions in the editor
  • no functions, packages,triggers, views are shown

The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;

How do I make a column unique and index it in a Ruby on Rails migration?

You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.

To add name for your index just use the name: option. The migration query might look something like this -

add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'

More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

Is it possible to cherry-pick a commit from another git repository?

Here are the steps to add a remote, fetch branches, and cherry-pick a commit

# Cloning our fork
$ git clone [email protected]:ifad/rest-client.git

# Adding (as "endel") the repo from we want to cherry-pick
$ git remote add endel git://github.com/endel/rest-client.git

# Fetch their branches
$ git fetch endel

# List their commits
$ git log endel/master

# Cherry-pick the commit we need
$ git cherry-pick 97fedac

Source: https://coderwall.com/p/sgpksw

How to apply box-shadow on all four sides?

The most simple solution and easiest way is to add shadow for all four side. CSS

box-shadow: 0 0 2px 2px #ccc; /* with blur shadow*/
box-shadow: 0 0 0 2px #ccc; /* without blur shadow*/

How do I do word Stemming or Lemmatization?

The most current version of the stemmer in NLTK is Snowball.

You can find examples on how to use it here:

http://nltk.googlecode.com/svn/trunk/doc/api/nltk.stem.snowball2-pysrc.html#demo

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

How to scroll to top of long ScrollView layout?

runOnUiThread( new Runnable(){
   @Override
   public void run(){
      mainScrollView.fullScroll(ScrollView.FOCUS_UP);
   }
}

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:

os.popen(command).read()

fastest MD5 Implementation in JavaScript

Much faster hashing should be possible by calculating on graphic card (implement hashing algorithm in WebGL), as discussed there about SHA256: Is it possible to calculate sha256 hashes in the browser using the user's video card, eg. by using WebGL or Flash?

uint8_t vs unsigned char

The whole point is to write implementation-independent code. unsigned char is not guaranteed to be an 8-bit type. uint8_t is (if available).

Using RegEX To Prefix And Append In Notepad++

Regular Expression that can be used:

Find: \w.+
Replace: able:"$&"

As, $& will give you the string you search for.

Refer: regexr

Pass correct "this" context to setTimeout callback?

NOTE: This won't work in IE

var ob = {
    p: "ob.p"
}

var p = "window.p";

setTimeout(function(){
    console.log(this.p); // will print "window.p"
},1000); 

setTimeout(function(){
    console.log(this.p); // will print "ob.p"
}.bind(ob),1000);

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

How to find out if an installed Eclipse is 32 or 64 bit version?

Help -> About Eclipse -> Installation Details -> tab Configuration

Look for -arch, and below it you'll see either x86_64 (meaning 64bit) or x86 (meaning 32bit).

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.

Is there a simple way to increment a datetime object one month in Python?

Note: This answer shows how to achieve this using only the datetime and calendar standard library (stdlib) modules - which is what was explicitly asked for. The accepted answer shows how to better achieve this with one of the many dedicated non-stdlib libraries. If you can use non-stdlib libraries, by all means do so for these kinds of date/time manipulations!

How about this?

def add_one_month(orig_date):
    # advance year and month by one month
    new_year = orig_date.year
    new_month = orig_date.month + 1
    # note: in datetime.date, months go from 1 to 12
    if new_month > 12:
        new_year += 1
        new_month -= 12

    new_day = orig_date.day
    # while day is out of range for month, reduce by one
    while True:
        try:
            new_date = datetime.date(new_year, new_month, new_day)
        except ValueError as e:
            new_day -= 1
        else:
            break

    return new_date

EDIT:

Improved version which:

  1. keeps the time information if given a datetime.datetime object
  2. doesn't use try/catch, instead using calendar.monthrange from the calendar module in the stdlib:
import datetime
import calendar

def add_one_month(orig_date):
    # advance year and month by one month
    new_year = orig_date.year
    new_month = orig_date.month + 1
    # note: in datetime.date, months go from 1 to 12
    if new_month > 12:
        new_year += 1
        new_month -= 12

    last_day_of_month = calendar.monthrange(new_year, new_month)[1]
    new_day = min(orig_date.day, last_day_of_month)

    return orig_date.replace(year=new_year, month=new_month, day=new_day)

What is a segmentation fault?

There are enough definitions of segmentation fault, i would like to quote few examples which i came across while programming, which might seem silly mistakes, but will waste a lot of time.

  1. you can get segmentation fault in below case while argumet type mismatch in printf

    #include<stdio.h> int main(){
    int a = 5; printf("%s",a); return 0; }

output : Segmentation Fault (SIGSEGV)

  1. when you forgot to allocate memory to a pointer, but trying to use it.

     #include<stdio.h> 
     typedef struct{
       int a;
     }myStruct;   
    int main(){
      myStruct *s;
      /* few lines of code */
      s->a = 5;
      return 0;
    }
    

output : Segmentation Fault (SIGSEGV)

How to ignore certain files in Git

1) Create a .gitignore file. To do that, you just create a .txt file and change the extension as follows:

Enter image description here

Then you have to change the name, writing the following line in a cmd window:

 rename git.txt .gitignore

Where git.txt is the name of the file you've just created.

Then you can open the file and write all the files you don’t want to add on the repository. For example, mine looks like this:

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

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

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

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Once you have this, you need to add it to your Git repository. You have to save the file where your repository is.

Then in Git Bash you have to write the following line:

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

If the repository already exists then you have to do the following:

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

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

Detect browser or tab closing

I found a way, that works on all of my browsers.

Tested on following versions: Firefox 57, Internet Explorer 11, Edge 41, one of the latested Chrome (it won't show my version)

Note: onbeforeunload fires if you leave the page in any way possible (refresh, close browser, redirect, link, submit..). If you only want it to happen on browser close, simply bind the event handlers.

  $(document).ready(function(){         

        var validNavigation = false;

        // Attach the event keypress to exclude the F5 refresh (includes normal refresh)
        $(document).bind('keypress', function(e) {
            if (e.keyCode == 116){
                validNavigation = true;
            }
        });

        // Attach the event click for all links in the page
        $("a").bind("click", function() {
            validNavigation = true;
        });

        // Attach the event submit for all forms in the page
        $("form").bind("submit", function() {
          validNavigation = true;
        });

        // Attach the event click for all inputs in the page
        $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        }); 

        window.onbeforeunload = function() {                
            if (!validNavigation) {     
                // ------->  code comes here
            }
        };

  });

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

Update TensorFlow

For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge. Then simply do:

conda update -f -c conda-forge tensorflow

This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.

<HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

      <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            //xml code
      </ScrollView>
</HorizontalScrollView>

jquery ajax get responsetext from http url

First you have to download a JQuery plugin to allow Cross-domain requests. Download it here: https://github.com/padolsey/jQuery-Plugins/downloads

Import the file called query.xdomainsajax.js into your project and include it with this code:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

To get the html of an external web page in text form you can write this:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});

How to change the commit author for one specific commit?

Changing Your Committer Name & Email Globally:

$ git config --global user.name "John Doe"
$ git config --global user.email "[email protected]"

Changing Your Committer Name & Email per Repository:

$ git config user.name "John Doe"
$ git config user.email "[email protected]"

Changing the Author Information Just for the Next Commit:

$ git commit --author="John Doe <[email protected]>"

Hint: For other situation and read more information read the post reference.

Regular Expressions and negating a whole character group

In this case I might just simply avoid regular expressions altogether and go with something like:

if (StringToTest.IndexOf("ab") < 0)
  //do stuff

This is likely also going to be much faster (a quick test vs regexes above showed this method to take about 25% of the time of the regex method). In general, if I know the exact string I'm looking for, I've found regexes are overkill. Since you know you don't want "ab", it's a simple matter to test if the string contains that string, without using regex.

Interview Question: Merge two sorted singly linked lists without creating new nodes

Look ma, no recursion!

struct llist * llist_merge(struct llist *one, struct llist *two, int (*cmp)(struct llist *l, struct llist *r) )
{
struct llist *result, **tail;

for (result=NULL, tail = &result; one && two; tail = &(*tail)->next ) {
        if (cmp(one,two) <=0) { *tail = one; one=one->next; }
        else { *tail = two; two=two->next; }
        }
*tail = one ? one: two;
return result;
}

How can I change the font-size of a select option?

Add a CSS class to the <option> tag to style it: http://jsfiddle.net/Ahreu/

Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?

How do I remove the "extended attributes" on a file in Mac OS X?

Use the xattr command. You can inspect the extended attributes:

$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine

and use the -d option to delete one extended attribute:

$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms

you can also use the -c option to remove all extended attributes:

$ xattr -c s.7z
$ xattr s.7z

xattr -h will show you the command line options, and xattr has a man page.

Escaping regex string

Please give a try:

\Q and \E as anchors

Put an Or condition to match either a full word or regex.

Ref Link : How to match a whole word that includes special characters in regex

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I found this can also occur if the most of the data plotted is outside of the axis limits. In that case, adjust the axis scales accordingly.

Swift: Convert enum value to String?

One more way

public enum HTTP{
case get
case put
case delete
case patch
var value: String? {
return String(describing: self)
}

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

Open another application from your own (intent)

Alternatively you can also open the intent from your app in the other app with:

Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

where uri is the deeplink to the other app

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

What does HTTP/1.1 302 mean exactly?

In the term of SEO , 301 and 302 both are good it is depend on situation,

If only one version can be returned (i.e., the other redirects to it), that’s great! This behavior is beneficial because it reduces duplicate content. In the particular case of redirects to trailing slash URLs, our search results will likely show the version of the URL with the 200 response code (most often the trailing slash URL) -- regardless of whether the redirect was a 301 or 302.

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Limit number of characters allowed in form input text field

Make it simpler

<input type="text" maxlength="3" />

and use an alert to show that max chars have been used.

Protect image download

First realise that you will never be able to completely stop an image being downloaded because if the user is viewing the image they have already downloaded it (temporarily) on their browser.

Also bear in mind the majority of users will probably not be web developers but they may still examine the source code.


I really discourage disabling right click, this can be extremely frustrating for the end user and is not safe anyway since the image can still be dragged into a new window and downloaded.

I would suggest the method used by CampSafari i.e.

img {
    pointer-events: none;
}

but with an improvement:

So first lets remove the url of your image and add an id attributes to it. Like so:

<img id="cutekitten">

Next we need to add some JavaScript to actually show the image. Keep this well away from the <img> tag you are trying to protect:

document.getElementById("cutekitten").src = "http://placekitten.com/600/450";

Now we need to use the CSS:

#cutekitten {
    pointer-events: none;
}

The image cannot be dragged into a new window as well downloaded via right click.

JSFiddle


Yet another method you could use is the embed tag:

<embed src="http://placekitten.com/600/450"></embed>

This will prevent the right click.

Is mongodb running?

I find:

ps -ax | grep mongo

To be a lot more consistent. The value returned can be used to detect how many instances of mongod there are running

document.getElementById(id).focus() is not working for firefox or chrome

Try location.href='#yourId'

Like this:

<button onclick="javascript:location.href='#yourId'">Show</button>

How to load image (and other assets) in Angular an project?

Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes. For example :

  • 'my-image-name.png' should be 'myImageName.png'
  • 'my image name.png' should be 'myImageName.png'

If you put the image in the assets/img folder, then this line of code should work in your templates :

<img alt="My image name" src="./assets/img/myImageName.png">

If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.

Why does Firebug say toFixed() is not a function?

In a function, use as

render: function (args) {
    if (args.value != 0)
        return (parseFloat(args.value).toFixed(2));


},

How to create a function in SQL Server

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END

Create a folder and sub folder in Excel VBA

There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function

Likewise,

Function FileExists(FileName As String) As Boolean
     If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this - I slightly changed the above answers:

var getAttributes = function(attribute) {
    var allElements = document.getElementsByTagName('*'),
        allElementsLen = allElements.length,
        curElement,
        i,
        results = [];

    for(i = 0; i < allElementsLen; i += 1) {
        curElement = allElements[i];

        if(curElement.getAttribute(attribute)) {
            results.push(curElement);
        }
    }

    return results;
};

Then,

getAttributes('data-foo');

jQuery - hashchange event

I think Chris Coyier has solution for that hashing problem, have a look at his screencast:

Best Practices with Dynamic Content

C# Timer or Thread.Sleep

class Program
{
    static void Main(string[] args)
    {
        Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000);
        Console.Read();
        timer.Dispose();
    }

    public static void TimeCallBack(object o)
    {
      curMinute = DateTime.Now.Minute;
      if (lastMinute < curMinute) {
       // do your once-per-minute code here
       lastMinute = curMinute;
    }
}

The code could resemble something like the one above

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Table border left and bottom

you can use these styles:

style="border-left: 1px solid #cdd0d4;"  
style="border-bottom: 1px solid #cdd0d4;"
style="border-top: 1px solid #cdd0d4;"
style="border-right: 1px solid #cdd0d4;"

with this you want u must use

<td style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;">  

or

<img style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;"> 

Playing mp3 song on python

Grab the VLC Python module, vlc.py, which provides full support for libVLC and pop that in site-packages. Then:

>>> import vlc
>>> p = vlc.MediaPlayer("file:///path/to/track.mp3")
>>> p.play()

And you can stop it with:

>>> p.stop()

That module offers plenty beyond that (like pretty much anything the VLC media player can do), but that's the simplest and most effective means of playing one MP3.

You could play with os.path a bit to get it to find the path to the MP3 for you, given the filename and possibly limiting the search directories.

Full documentation and pre-prepared modules are available here. Current versions are Python 3 compatible.

View HTTP headers in Google Chrome?

I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.

Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.

It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.

https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb

Enjoy!

Getting attributes of Enum's value

Here is code to get information from a Display attribute. It uses a generic method to retrieve the attribute. If the attribute is not found it converts the enum value to a string with pascal/camel case converted to title case (code obtained here)

public static class EnumHelper
{
    // Get the Name value of the Display attribute if the   
    // enum has one, otherwise use the value converted to title case.  
    public static string GetDisplayName<TEnum>(this TEnum value)
        where TEnum : struct, IConvertible
    {
        var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
        return attr == null ? value.ToString().ToSpacedTitleCase() : attr.Name;
    }

    // Get the ShortName value of the Display attribute if the   
    // enum has one, otherwise use the value converted to title case.  
    public static string GetDisplayShortName<TEnum>(this TEnum value)
        where TEnum : struct, IConvertible
    {
        var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
        return attr == null ? value.ToString().ToSpacedTitleCase() : attr.ShortName;
    }

    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="TEnum">The enum type</typeparam>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="value">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    private static T GetAttributeOfType<TEnum, T>(this TEnum value)
        where TEnum : struct, IConvertible
        where T : Attribute
    {

        return value.GetType()
                    .GetMember(value.ToString())
                    .First()
                    .GetCustomAttributes(false)
                    .OfType<T>()
                    .LastOrDefault();
    }
}

And this is the extension method for strings for converting to title case:

    /// <summary>
    /// Converts camel case or pascal case to separate words with title case
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ToSpacedTitleCase(this string s)
    {
        //https://stackoverflow.com/a/155486/150342
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;
        return textInfo
           .ToTitleCase(Regex.Replace(s, 
                        "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 "));
    }

Is there a float input type in HTML5?

The number type has a step value controlling which numbers are valid (along with max and min), which defaults to 1. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step).

Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:

<input type="number" step="0.01">

(I'd also set min=0 if it can only be positive)

If you'd prefer to allow any number of decimal places, you can use step="any" (though for currencies, I'd recommend sticking to 0.01). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any. (thanks to Michal Stefanow's answer for pointing out any, and see the relevant spec here)

Here's a playground showing how various steps affect various input types:

_x000D_
_x000D_
<form>_x000D_
  <input type=number step=1 /> Step 1 (default)<br />_x000D_
  <input type=number step=0.01 /> Step 0.01<br />_x000D_
  <input type=number step=any /> Step any<br />_x000D_
  <input type=range step=20 /> Step 20<br />_x000D_
  <input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
  <input type=datetime-local step=1 /> Step 1<br />_x000D_
  <input type=datetime-local step=any /> Step any<br />_x000D_
  <input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
  <input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
  <input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
  <input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
_x000D_
_x000D_


As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!

Function for 'does matrix contain value X?'

If you need to check whether the elements of one vector are in another, the best solution is ismember as mentioned in the other answers.

ismember([15 17],primes(20))

However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf

It gives a very practical example:

[tf, loc]=ismember(0.3, 0:0.1:1) % returns false 
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true

Though the default tolerance should normally be sufficient, it gives you more flexibility

ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true

I want to multiply two columns in a pandas DataFrame and add the result into a new column

I think an elegant solution is to use the where method (also see the API docs):

In [37]: values = df.Prices * df.Amount

In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)

In [39]: df
Out[39]: 
   Prices  Amount Action  Values
0       3      57   Sell     171
1      89      42   Sell    3738
2      45      70    Buy   -3150
3       6      43   Sell     258
4      60      47   Sell    2820
5      19      16    Buy    -304
6      56      89   Sell    4984
7       3      28    Buy     -84
8      56      69   Sell    3864
9      90      49    Buy   -4410

Further more this should be the fastest solution.

What is a Question Mark "?" and Colon ":" Operator Used for?

Maybe It can be perfect example for Android, For example:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}

Using SELECT result in another SELECT

NewScores is an alias to Scores table - it looks like you can combine the queries as follows:

SELECT 
    ROW_NUMBER() OVER( ORDER BY NETT) AS Rank, 
    Name, 
    FlagImg, 
    Nett, 
    Rounds 
FROM (
    SELECT 
        Members.FirstName + ' ' + Members.LastName AS Name, 
        CASE 
            WHEN MenuCountry.ImgURL IS NULL THEN 
                '~/images/flags/ismygolf.png' 
            ELSE 
                MenuCountry.ImgURL 
        END AS FlagImg, 
        AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett, 
        COUNT(Score.ScoreID) AS Rounds 
    FROM 
        Members 
        INNER JOIN 
        Score NewScores
            ON Members.MemberID = NewScores.MemberID 
        LEFT OUTER JOIN MenuCountry 
            ON Members.Country = MenuCountry.ID 
    WHERE 
        Members.Status = 1 
        AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
    GROUP BY 
        Members.FirstName + ' ' + Members.LastName, 
        MenuCountry.ImgURL
    ) AS Dertbl 
ORDER BY;

C: scanf to array

Use

scanf("%d", &array[0]);

and use == for comparision instead of =

SQL Last 6 Months

In MySQL

where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month

SQLFiddle demo

In SQL Server

where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)

SQLFiddle demo

Rename column SQL Server 2008

Since I often come here and then wondering how to use the brackets, this answer might be useful for those like me.

EXEC sp_rename '[DB].[dbo].[Tablename].OldColumnName', 'NewColumnName', 'COLUMN'; 
  • The OldColumnName must not be in []. It will not work.
  • Don't put NewColumnName into [], it will result into [[NewColumnName]].

postgresql duplicate key violates unique constraint

For future searchs, use ON CONFLICT DO NOTHING.

How to insert tab character when expandtab option is on in Vim

You can use <CTRL-V><Tab> in "insert mode". In insert mode, <CTRL-V> inserts a literal copy of your next character.

If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:

:inoremap <S-Tab> <C-V><Tab>

Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q> rather than <CTRL-V>.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To fix this issue you need to remove your Google account, then add it again. To do this follow these instructions:

http://support.google.com/android/bin/answer.py?hl=en&answer=1663649

(Or just find the account under Settings > Personal > Accounts and Sync > Click the Google Account > Click Menu button > Click Remove Account > Confirm deletion.)

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

PHP - define constant inside a class

class Foo {
    const BAR = 'baz';
}

echo Foo::BAR;

This is the only way to make class constants. These constants are always globally accessible via Foo::BAR, but they're not accessible via just BAR.

To achieve a syntax like Foo::baz()->BAR, you would need to return an object from the function baz() of class Foo that has a property BAR. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.

Is embedding background image data into CSS as Base64 good or bad practice?

One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.

You have to include the base stylesheet before the image stylesheet of course.

This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Get all directories within directory nodejs

Another recursive approach

Thanks to Mayur for knowing me about withFileTypes. I written following code for getting files of particular folder recursively. It can be easily modified to get only directories.

const getFiles = (dir, base = '') => readdirSync(dir, {withFileTypes: true}).reduce((files, file) => {
    const filePath = path.join(dir, file.name)
    const relativePath = path.join(base, file.name)
    if(file.isDirectory()) {
        return files.concat(getFiles(filePath, relativePath))
    } else if(file.isFile()) {
        file.__fullPath = filePath
        file.__relateivePath = relativePath
        return files.concat(file)
    }
}, [])

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Force DOM redraw/refresh on Chrome/Mac

call window.getComputedStyle() should force a reflow

nodeJS - How to create and read session with express

It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for socket.io that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a socket.io connection, send session cookie over socket.io from browser to server
  4. Store the session id in a socket.io connection, and use it to access session data from redis.

What are the lengths of Location Coordinates, latitude and longitude?

I am aware there are already several answers, but I added this, as this adds substantial information about the decimal places and hence the asked maximum length.

The length of latitude and langitude depend on precision. The absolute maximum length for each is:

  • Latitude: 12 characters (example: -90.00000001)
  • Longitude: 13 characters (example: -180.00000001)

For both holds: a maximum of 8 decial places is possible (though not commonly used).

Explanation for the dependency on precision:

enter image description here

See the full table at Decimal degrees article on Wikipedia

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

Ignore python multiple return value

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Plot multiple lines (data series) each with unique color in R

I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well

By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.

ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))    

and

geom_line() 

Line Graph with Multiple colors

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

IsNothing versus Is Nothing

Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.

What's the fastest way to read a text file line-by-line?

To find the fastest way to read a file line by line you will have to do some benchmarking. I have done some small tests on my computer but you cannot expect that my results apply to your environment.

Using StreamReader.ReadLine

This is basically your method. For some reason you set the buffer size to the smallest possible value (128). Increasing this will in general increase performance. The default size is 1,024 and other good choices are 512 (the sector size in Windows) or 4,096 (the cluster size in NTFS). You will have to run a benchmark to determine an optimal buffer size. A bigger buffer is - if not faster - at least not slower than a smaller buffer.

const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
  using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) {
    String line;
    while ((line = streamReader.ReadLine()) != null)
      // Process line
  }

The FileStream constructor allows you to specify FileOptions. For example, if you are reading a large file sequentially from beginning to end, you may benefit from FileOptions.SequentialScan. Again, benchmarking is the best thing you can do.

Using File.ReadLines

This is very much like your own solution except that it is implemented using a StreamReader with a fixed buffer size of 1,024. On my computer this results in slightly better performance compared to your code with the buffer size of 128. However, you can get the same performance increase by using a larger buffer size. This method is implemented using an iterator block and does not consume memory for all lines.

var lines = File.ReadLines(fileName);
foreach (var line in lines)
  // Process line

Using File.ReadAllLines

This is very much like the previous method except that this method grows a list of strings used to create the returned array of lines so the memory requirements are higher. However, it returns String[] and not an IEnumerable<String> allowing you to randomly access the lines.

var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i += 1) {
  var line = lines[i];
  // Process line
}

Using String.Split

This method is considerably slower, at least on big files (tested on a 511 KB file), probably due to how String.Split is implemented. It also allocates an array for all the lines increasing the memory required compared to your solution.

using (var streamReader = File.OpenText(fileName)) {
  var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  foreach (var line in lines)
    // Process line
}

My suggestion is to use File.ReadLines because it is clean and efficient. If you require special sharing options (for example you use FileShare.ReadWrite), you can use your own code but you should increase the buffer size.

Custom domain for GitHub project pages

Short answer

These detailed explanations are great, but the OP's (and my) confusion could be resolved with one sentence: "Direct DNS to your GitHub username or organization, ignoring the specific project, and add the appropriate CNAME files in your project repositories: GitHub will send the right DNS to the right project based on files in the respository."

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In Visual Studio:

  1. project properties (right click on your project)
  2. Debug -> Start Options
  3. Make sure "Command line arguments" is empty

White spaces are required between publicId and systemId

If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.

  • Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)
  • Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)
  • At the top of the page that appears there is a drop down, select "Manual."
  • Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.
  • Enter in the proxy url and port you need to connect to the internet in your web browser normally.
  • Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

Convert ascii char[] to hexadecimal char[] in C

replace this

printf("%c",word[i]);

by

printf("%02X",word[i]);

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Which concurrent Queue implementation should I use in Java?

Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

MySQL config file location - redhat linux server

From the header of '/etc/mysql/my.cnf':

MariaDB programs look for option files in a set of
locations which depend on the deployment platform.
[...] For information about these locations, do:
'my_print_defaults --help' and see what is printed under
"Default options are read from the following files in the given order:"
More information at: http://dev.mysql.com/doc/mysql/en/option-files.html

Ruby: Can I write multi-line string with no concatenation?

conn.exec [
  "select attr1, attr2, attr3, ...",
  "from table1, table2, table3, ...",
  "where ..."
].join(' ')

This suggestion has the advantage over here-documents and long strings that auto-indenters can indent each part of the string appropriately. But it comes at an efficiency cost.

Go Back to Previous Page

We can navigate to the previous page by using any of the below.

window.location.href="give url you want to go";

or

window.history.back();

or

window.history.go(-1);

or

window.history.back(-1);

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

Explode PHP string by new line

Try "\n\r" (double quotes) or just "\n".

If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".

View the change history of a file using Git versioning

If you're using the git GUI (on Windows) under the Repository menu you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.

bootstrap responsive table content wrapping

The behaviour is on purpose:

Create responsive tables by wrapping any .table in .table-responsive to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Which means tables are responsive by default (are adjusting their size). But only if you wish to not break your table's lines and add scrollbar when there is not enough room use .table-responsive class.

If you take a look at bootstrap's source you will notice there is media query that only activates on XS screen size and it sets text of table to white-space: nowrap which causes it to not breaking.

TL;DR; Solution

Simply remove .table-responsive element/class from your html code.

Get random integer in range (x, y]?

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

Find value in an array

Use:

myarray.index "valuetoFind"

That will return you the index of the element you want or nil if your array doesn't contain the value.

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

Viewing all `git diffs` with vimdiff

Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool. 

git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge

Merge PDF files

You can use PyPdf2s PdfMerger class.

File Concatenation

You can simply concatenate files by using the append method.

from PyPDF2 import PdfFileMerger

pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']

merger = PdfFileMerger()

for pdf in pdfs:
    merger.append(pdf)

merger.write("result.pdf")
merger.close()

You can pass file handles instead file paths if you want.

File Merging

If you want more fine grained control of merging there is a merge method of the PdfMerger, which allows you to specify an insertion point in the output file, meaning you can insert the pages anywhere in the file. The append method can be thought of as a merge where the insertion point is the end of the file.

e.g.

merger.merge(2, pdf)

Here we insert the whole pdf into the output but at page 2.

Page Ranges

If you wish to control which pages are appended from a particular file, you can use the pages keyword argument of append and merge, passing a tuple in the form (start, stop[, step]) (like the regular range function).

e.g.

merger.append(pdf, pages=(0, 3))    # first 3 pages
merger.append(pdf, pages=(0, 6, 2)) # pages 1,3, 5

If you specify an invalid range you will get an IndexError.

Note: also that to avoid files being left open, the PdfFileMergers close method should be called when the merged file has been written. This ensures all files are closed (input and output) in a timely manner. It's a shame that PdfFileMerger isn't implemented as a context manager, so we can use the with keyword, avoid the explicit close call and get some easy exception safety.

You might also want to look at the pdfcat script provided as part of pypdf2. You can potentially avoid the need to write code altogether.

The PyPdf2 github also includes some example code demonstrating merging.

Redis: Show database size/size for keys

I usually prefer the key sampling method to troubleshoot such scenarios.

redis-cli -p 6379 -n db_number --bigkeys

Eg:-

redis-cli -p 6370 -n 0 --bigkeys

How to use Greek symbols in ggplot2?

Here is a link to an excellent wiki that explains how to put greek symbols in ggplot2. In summary, here is what you do to obtain greek symbols

  1. Text Labels: Use parse = T inside geom_text or annotate.
  2. Axis Labels: Use expression(alpha) to get greek alpha.
  3. Facet Labels: Use labeller = label_parsed inside facet.
  4. Legend Labels: Use bquote(alpha == .(value)) in legend label.

You can see detailed usage of these options in the link

EDIT. The objective of using greek symbols along the tick marks can be achieved as follows

require(ggplot2);
data(tips);
p0 = qplot(sex, data = tips, geom = 'bar');
p1 = p0 + scale_x_discrete(labels = c('Female' = expression(alpha),
                                      'Male'   = expression(beta)));
print(p1);

For complete documentation on the various symbols that are available when doing this and how to use them, see ?plotmath.

GitHub: invalid username or password

In case you get this error message in this situation:

  • using github for entreprise
  • using credential.helper=wincred in git config
  • using your windows credentials which you changed recently

Then look at this answer: https://stackoverflow.com/a/39608906/521257

Windows stores credentials in a credentials manager, clear it or update it.

TypeError: no implicit conversion of Symbol into Integer

You probably meant this:

require 'active_support/core_ext' # for titleize

myHash = {company_name:"MyCompany", street:"Mainstreet", postcode:"1234", city:"MyCity", free_seats:"3"}

def cleanup string
  string.titleize
end

def format(hash)
  output = {}
  output[:company_name] = cleanup(hash[:company_name])
  output[:street] = cleanup(hash[:street])
  output
end

format(myHash) # => {:company_name=>"My Company", :street=>"Mainstreet"}

Please read documentation on Hash#each

Javamail Could not convert socket to TLS GMail

Make sure your antivirus program isn't interfering and be sure to add an exclusion to your firewall.

How to fix error with xml2-config not found when installing PHP from sources?

Ubuntu, Debian:

sudo apt install libxml2-dev

Centos:

sudo yum install libxml2-devel

How do I download/extract font from chrome developers tools?

Right-click, then "Open link in new tab"

edit : you can also double-click, it has the same effect

Asking the user for input until they give a valid response

Yeah I'm 6 years late from the but this question deserves more up-to-date answer.

Separation of concerns

I am a big fan of Unix philosophy "Do one thing and do it well". In this type of problem, it is better practice to split the problem to

  • Ask input with get_input until the input is ok.
  • Validate in validator function. You could write different validators for different input queries.

Asking for input

It can be kept as simple as (Python 3+)

def myvalidator(value):
    try:
        value = int(value)
    except ValueError:
        return False
    return value >= 0

def get_input(prompt, validator, on_validationerror):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(on_validationerror)

Example

In [2]: get_input('Give a positive number: ', myvalidator, 'Please, try again')
Give a positive number: foobar
Please, try again
Give a positive number: -10
Please, try again
Give a positive number: 42
Out[2]: '42'

Python 3.8+ Note

In Python 3.8+ you could use the walrus operator

def get_input(prompt, validator, on_validationerror):
    while not validator(value := input(prompt)):
        print(on_validationerror)
    return value 

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

This happened to me because I was using a Tomcat 5.5 catalina.sh file with a Tomcat 7 installation. Using the catalina.sh that came with the Tomcat 7 install fixed the problem.

SQL Server: Examples of PIVOTing String data

From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:

SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO

Why do I get "'property cannot be assigned" when sending an SMTP email?

First go to https://myaccount.google.com/lesssecureapps and make Allow less secure apps true.

Then use the below code. This below code will work only if your from email address is from gmail.

static void SendEmail()
    {
        string mailBodyhtml =
            "<p>some text here</p>";
        var msg = new MailMessage("[email protected]", "[email protected]", "Hello", mailBodyhtml);
        msg.To.Add("[email protected]");
        msg.IsBodyHtml = true;
        var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "[email protected]" then host should be "smtp.hotmail.com"**
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential("[email protected]", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Send(msg);
        Console.WriteLine("Email Sent Successfully");
    }

Use JSTL forEach loop's varStatus as an ID

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1

Debugging JavaScript in IE7

If you still need to Debug IE 7, the emulation mode of IE 11 is working pretty well.

Go to menu: Dev Tools, then to emulation and set it. It also gives error line information.

EditText onClickListener in Android

The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:

<EditText
    ...
    android:focusable="false"
    ... />

This behavior can vary on different manufacturers' Android OS flavors, but on the devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:

myEditText.setText("My text");    // instead of this...
myEditText.setHint("My text");    // try this

Once you've done this, your on click listener should work as desired:

myEditText.setOnClickListener(new OnClickListener() {...});

How to read data From *.CSV file using javascript?

Actually you can use a light-weight library called any-text.

  • install dependencies
npm i -D any-text
  • use custom command to read files
var reader = require('any-text');
 
reader.getText(`path-to-file`).then(function (data) {
  console.log(data);
});

or use async-await :

var reader = require('any-text');
 
const chai = require('chai');
const expect = chai.expect;
 
describe('file reader checks', () => {
  it('check csv file content', async () => {
    expect(
      await reader.getText(`${process.cwd()}/test/files/dummy.csv`)
    ).to.contains('Lorem ipsum');
  });
});

psql: command not found Mac

If Postgresql was downloaded from official website. After installation, running these commands helped me resolve the psql issue.

Go to your home directory with cd ~

In your home directory, run ls -a. Edit the .bash_profile file with vim

vi .bash_profile opens the vim editor.

Insert by pressing i on the editor.

Add export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/<Version Number>/bin

The Version Number refers to the version number of the postgresql installed on your local machine. In my case, version 12 was installed, so I inputed

export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/12/bin .

Press the esc key and press :wq to exit the editor.

Enter source .bash_profile in your terminal to read and execute the content of a file just passed as an argument in the current shell script.

Run psql

terminal result

In summary:

  • cd ~
  • vi .bash_profile
  • export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/12/bin Take note of the version number
  • exit vim
  • source .bash_profile
  • psql Works

Combine two data frames by rows (rbind) when they have different sets of columns

rbind.fill from the package plyr might be what you are looking for.

"unmappable character for encoding" warning in Java

This helped for me:

All you need to do, is to specify a envirnoment variable called JAVA_TOOL_OPTIONS. If you set this variable to -Dfile.encoding=UTF8, everytime a JVM is started, it will pick up this information.

Source: http://whatiscomingtomyhead.wordpress.com/2012/01/02/get-rid-of-unmappable-character-for-encoding-cp1252-once-and-for-all/

Do I need <class> elements in persistence.xml?

Not necessarily in all cases.

I m using Jboss 7.0.8 and Eclipselink 2.7.0. In my case to load entities without adding the same in persistence.xml, I added the following system property in Jboss Standalone XML:

<property name="eclipselink.archive.factory" value="org.jipijapa.eclipselink.JBossArchiveFactoryImpl"/>

When to use single quotes, double quotes, and backticks in MySQL

Besides all of the (well-explained) answers, there hasn't been the following mentioned and I visit this Q&A quite often.

In a nutshell; MySQL thinks you want to do math on its own table/column and interprets hyphens such as "e-mail" as e minus mail.


Disclaimer: So I thought I would add this as an "FYI" type of answer for those who are completely new to working with databases and who may not understand the technical terms described already.

Extract directory path and filename

You can simply do:

base=$(basename "$fspec")

Strings in C, how to get subString

#include <stdio.h>
#include <string.h>

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.

'uint32_t' does not name a type

I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h> or <cstdint.h> to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h> which worked well for me!

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

How to print like printf in Python3?

Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):

print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')

PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

Load arrayList data into JTable

You probably need to use a TableModel (Oracle's tutorial here)

How implements your own TableModel

public class FootballClubTableModel extends AbstractTableModel {
  private List<FootballClub> clubs ;
  private String[] columns ; 

  public FootBallClubTableModel(List<FootballClub> aClubList){
    super();
    clubs = aClubList ;
    columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
  }

  // Number of column of your table
  public int getColumnCount() {
    return columns.length ;
  }

  // Number of row of your table
  public int getRowsCount() {
    return clubs.size();
  }

  // The object to render in a cell
  public Object getValueAt(int row, int col) {
    FootballClub club = clubs.get(row);
    switch(col) {
      case 0: return club.getPosition();
      // to complete here...
      default: return null;
    }
  }

  // Optional, the name of your column
  public String getColumnName(int col) {
    return columns[col] ;
  }

}

You maybe need to override anothers methods of TableModel, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this

List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);

Hope it help !

Ignore parent padding

Easy fix, just do

margin:-10px

on the hr.

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

Had the same error when installing PhantomJS on Ubuntu 14.04 64bit with gcc-4.8 (CXXABI_1.3.7)

Upgrading to gcc-4.9 (CXXABI_1.3.8) fixed the issue. HOWTO: https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04

How to search images from private 1.0 registry in docker?

List all images

docker search <registry_host>:<registry_port>/

List images like 'vcs'

docker search <registry_host>:<registry_port>/vcs

Change div width live with jQuery

Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});

How do I make a MySQL database run completely in memory?

In place of the Memory storage engine, one can consider MySQL Cluster. It is said to give similar performance but to support disk-backed operation for durability. I've not tried it, but it looks promising (and been in development for a number of years).

You can find the official MySQL Cluster documentation here.

How to solve the memory error in Python

Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError.

Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).

If that's not enough, consider converting to a sqlite3 database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.

Html attributes for EditorFor() in ASP.NET MVC

Now ASP.Net MVC 5.1 got a built in support for it.

From Release Notes

We now allow passing in HTML attributes in EditorFor as an anonymous object.

For example:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })

mysql extract year from date format

This should work if the date format is consistent:

select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table 

Pass arguments into C program from command line

Consider using getopt_long(). It allows both short and long options in any combination.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

Related:

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Edited the config file and changed bare = true to bare = false

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

I added TO_DATE and it resolved issue.

Before modification - due to below condition i got this error

record_update_dt>='05-May-2017'

After modification - after adding to_date, issue got resolved.

record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')

How do I append one string to another in Python?

it really depends on your application. If you're looping through hundreds of words and want to append them all into a list, .join() is better. But if you're putting together a long sentence, you're better off using +=.

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

AngularJS sorting by property

I will add my upgraded version of filter which able to supports next syntax:

ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'

app.filter('orderObjectBy', function(){

         function byString(o, s) {
            s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
            s = s.replace(/^\./, '');           // strip a leading dot
            var a = s.split('.');
            for (var i = 0, n = a.length; i < n; ++i) {
                var k = a[i];
                if (k in o) {
                    o = o[k];
                } else {
                    return;
                }
            }
            return o;
        }

        return function(input, attribute, direction) {
            if (!angular.isObject(input)) return input;

            var array = [];
            for(var objectKey in input) {
                if (input.hasOwnProperty(objectKey)) {
                    array.push(input[objectKey]);
                }
            }

            array.sort(function(a, b){
                a = parseInt(byString(a, attribute));
                b = parseInt(byString(b, attribute));
                return direction == 'asc' ? a - b : b - a;
            });
            return array;
        }
    })

Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.

Print the contents of a DIV

In Opera, try:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();

How can I set focus on an element in an HTML form using JavaScript?

Usually when we focus on a textbox, we should also scroll into view

function setFocusToTextBox(){
    var textbox = document.getElementById("yourtextbox");
    textbox.focus();
    textbox.scrollIntoView();
}

Check if it helps.

use jQuery to get values of selected checkboxes

So all in one line:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"] , it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.

Transparent scrollbar with css

if you don't have any content with 100% width, you can set the background color of the track to the same color of the body's background

WPF TemplateBinding vs RelativeSource TemplatedParent

I thought TemplateBinding does not support Freezable types (which includes brush objects). To get around the problem. One can make use of TemplatedParent

How to install JDK 11 under Ubuntu?

In Ubuntu, you can simply install Open JDK by following commands.

sudo apt-get update    
sudo apt-get install default-jdk

You can check the java version by following the command.

java -version

If you want to install Oracle JDK 8 follow the below commands.

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If you want to switch java versions you can try below methods.

vi ~/.bashrc and add the following line export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_221 (path/jdk folder)

or

sudo vi /etc/profile and add the following lines

#JAVA_HOME=/usr/lib/jvm/jdk1.8.0_221
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME
export JRE_HOME
export PATH

You can comment on the other version. This needs to sign out and sign back in to use. If you want to try it on the go you can type the below command in the same terminal. It'll only update the java version for a particular terminal.

source /etc/profile

You can always check the java version by java -version command.

Fastest way to implode an associative array with keys

This is my solution for example for an div data-attributes:

<?

$attributes = array(
    'data-href'   => 'http://example.com',
    'data-width'  => '300',
    'data-height' => '250',
    'data-type'   => 'cover',
);

$dataAttributes = array_map(function($value, $key) {
    return $key.'="'.$value.'"';
}, array_values($attributes), array_keys($attributes));

$dataAttributes = implode(' ', $dataAttributes);

?>

<div class="image-box" <?= $dataAttributes; ?> >
    <img src="http://example.com/images/best-of.jpg" alt="">
</div>

How do I detect what .NET Framework versions and service packs are installed?

Enumerate the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP. Each subkey is a .NET version. It should have Install=1 value if it's present on the machine, an SP value that shows the service pack and an MSI=1 value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)

How to get the date from the DatePicker widget in Android?

Try this:

 DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
 int day = datePicker.getDayOfMonth();
 int month = datePicker.getMonth() + 1;
 int year = datePicker.getYear();

Convert list or numpy array of single element to float in python

You may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,

>>> a = np.asarray(1).view()
>>> a.item()  # correct
1

>>> a[0]  # breaks
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array


>>> a = np.asarray([[2]])
>>> a.item()  # correct
2

>>> a[0]  # bad result
array([2])

This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).

>>> a = np.asarray([1, 2])
>>> a[0]  # silently proceeds
1
>>> a.item()  # detects incorrect size
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar

How to check if a string is numeric?

Simple method:

public boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}


public boolean isOnlyNumber(String value) {
    boolean ret = false;
    if (!isBlank(value)) {
        ret = value.matches("^[0-9]+$");
    }
    return ret;
}

Python MySQLdb TypeError: not all arguments converted during string formatting

cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )

I do not why, but this works for me . rather than use '%s'.