Programs & Examples On #Jibx

JiBX is a tool for binding XML data to Java objects. http://jibx.sourceforge.net/

Is floating point math broken?

A lot of good answers have been posted, but I'd like to append one more.

Not all numbers can be represented via floats/doubles For example, the number "0.2" will be represented as "0.200000003" in single precision in IEEE754 float point standard.

Model for store real numbers under the hood represent float numbers as

enter image description here

Even though you can type 0.2 easily, FLT_RADIX and DBL_RADIX is 2; not 10 for a computer with FPU which uses "IEEE Standard for Binary Floating-Point Arithmetic (ISO/IEEE Std 754-1985)".

So it is a bit hard to represent such numbers exactly. Even if you specify this variable explicitly without any intermediate calculation.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I was getting the same error even after adding no-arg constructor,Then I figured out that I was missing several JARs.I am posting this so that if anyone gets the error like I got, make sure you have added these JARs in your lib folder :

activation-1.0.2.jar
antlr-2.7.6.jar
aopalliance.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
cglib-2.1_3.jar
commons-beanutils-1.7.0.jar
commons-collections-2.1.1.jar
commons-digester-1.8.jar
commons-email-1.0.jar
commons-fileupload-1.1.1.jar
commons-io-1.1.jar
commons-lang-2.5.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
dumbster-1.6.jar
ehcache-1.2.3.jar
ejb3-persistence-3.3.1.jar
hibernate-commons-annotations-4.0.4.Final.jar
hibernate-core-4.2.8.Final.jar
icu4j-2.6.1.jar
javassist-3.4.GA.jar
javax.persistence_2.0.3.v201010191057.jar
javax.servlet.jsp.jstl-1.2.1.jar
jaxb-api-2.1.jar
jaxb-impl-2.1.3.jar
jaxen-1.1.1.jar
jboss-logging-3.1.3.GA.jar
jdom-1.0.jar
jstl-1.2.jar
jta-1.1.jar
lucene-core-2.3.2.jar
lucene-highlighter-2.0.0.jar
mail-1.4.jar
mysql-connector-java-5.0.8-bin.jar
org.springframework.orm.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.5.6.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE-javadoc.jar
spring-beans-4.0.0.RELEASE.jar
spring-build-src-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-framework-bom-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
stax-api-1.0-2.jar
validation-api-1.0.0.GA.jar
xalan-2.6.0.jar
xercesImpl-2.6.2.jar
xml-apis-1.3.02.jar
xmlParserAPIs-2.6.2.jar
xom-1.0.jar

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

I tried this simple thing and it seems to be working.

file.setWritable(true);
file.delete();

It works for me.

If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.

How to read a CSV file from a URL with Python?

To increase performance when downloading a large file, the below may work a bit more efficiently:

import requests
from contextlib import closing
import csv

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
    for row in reader:
        # Handle each row here...
        print row   

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

Enum "Inheritance"

This is what I did. What I've done differently is use the same name and the new keyword on the "consuming" enum. Since the name of the enum is the same, you can just mindlessly use it and it will be right. Plus you get intellisense. You just have to manually take care when setting it up that the values are copied over from the base and keep them sync'ed. You can help that along with code comments. This is another reason why in the database when storing enum values I always store the string, not the value. Because if you are using automatically assigned increasing integer values those can change over time.

// Base Class for balls 
public class BaseBall
{
    // keep synced with subclasses!
    public enum Sizes
    {
        Small,
        Medium,
        Large
    }
}

public class VolleyBall : BaseBall
{
    // keep synced with base class!
    public new enum Sizes
    {
        Small = BaseBall.Sizes.Small,
        Medium = BaseBall.Sizes.Medium,
        Large = BaseBall.Sizes.Large,
        SmallMedium,
        MediumLarge,
        Ginormous
    }
}

how to set start page in webconfig file in asp.net c#

I think this will help

    <directoryBrowse enabled="false" />
    <defaultDocument>
      <files>
        <clear />
        <add value="index.aspx" />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.html" />
        <add value="iisstart.htm" />
        <add value="default.aspx" />
        <add value="index.php" />
      </files>
    </defaultDocument>
  </system.webServer>

How to convert a 3D point into 2D perspective projection?

You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.

Example for Java Swing.

import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;


Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX

void drawPoint(Graphics2D g2, Vector3D v) {
    g2.drawLine(0, 0,
            (int) (world.unit * planeX.getOffset(v)),
            (int) (world.unit * planeY.getOffset(v)));
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    drawPoint(g2, new Vector3D(2, 1, 0));
    drawPoint(g2, new Vector3D(0, 2, 0));
    drawPoint(g2, new Vector3D(0, 0, 2));
    drawPoint(g2, new Vector3D(1, 1, 1));
}

Now you only needs update the planeX and planeY to change the perspective-projection, to get things like this:

enter image description hereenter image description here

Java Object Null Check for method

You can add a guard condition to the method to ensure books is not null and then check for null when iterating the array:

public static double calculateInventoryTotal(Book[] books)
{
    if(books == null){
        throw new IllegalArgumentException("Books cannot be null");
    }

    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        if(books[i] != null){
            total += books[i].getPrice();
        }
    }

    return total;
}

How do I load a PHP file into a variable?

If your file has a return statement like this:

<?php return array(
  'AF' => 'Afeganistão',
  'ZA' => 'África do Sul',
  ...
  'ZW' => 'Zimbabué'
);

You can get this to a variable like this:

$data = include $filePath;

Convert integer to hexadecimal and back again

Print integer in hex-value with zero-padding (if needed) :

int intValue = 1234;

Console.WriteLine("{0,0:D4} {0,0:X3}", intValue); 

https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

how to configuring a xampp web server for different root directory

If you are running xampp on linux based image, to change root directory open:

/opt/lampp/etc/httpd.conf

Change default document root: DocumentRoot "/opt/lampp/htdocs" and <Directory "/opt/lampp/htdocs"

to your folder DocumentRoot "/opt/lampp/htdocs/myFolder" and <Directory "/opt/lampp/htdocs/myFolder">

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

How to start Spyder IDE on Windows

I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.

I installed PyQt5 (pip install pyqt5) and Spyder (pip install spyder) which both installed w/out error and included all of the necessary dependencies.

To launch Spyder, I created a simple Python script (Spyder.py):

# Spyder Start Script
from spyder.app import start
start.main()

Then I created a Windows batch file (Spyder.bat):

@echo off
python c:\<path_to_Spyder_py>\Spyder.py

Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.

Works like a charm for me.

Get the previous month's first and last day dates in c#

An approach using extension methods:

class Program
{
    static void Main(string[] args)
    {
        DateTime t = DateTime.Now;

        DateTime p = t.PreviousMonthFirstDay();
        Console.WriteLine( p.ToShortDateString() );

        p = t.PreviousMonthLastDay();
        Console.WriteLine( p.ToShortDateString() );


        Console.ReadKey();
    }
}


public static class Helpers
{
    public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
    {
        DateTime d = currentDate.PreviousMonthLastDay();

        return new DateTime( d.Year, d.Month, 1 );
    }

    public static DateTime PreviousMonthLastDay( this DateTime currentDate )
    {
        return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
    }
}

See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions.

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

How to delete a line from a text file in C#?

string fileIN = @"C:\myTextFile.txt";
string fileOUT = @"C:\myTextFile_Out.txt";
if (File.Exists(fileIN))
{
    string[] data = File.ReadAllLines(fileIN);
    foreach (string line in data)
        if (!line.Equals("my line to remove"))
            File.AppendAllText(fileOUT, line);
    File.Delete(fileIN);
    File.Move(fileOUT, fileIN);
}

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf. Look for the lines that read:

# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true

Just remove the # in front of httpinterface and restart the mongod service:

sudo restart mongod

Note: You can also enable the rest interface by adding a line that reads rest=true right below the httpinterface line mentioned above.

How to select the first, second, or third element with a given class name?

In the future (perhaps) you will be able to use :nth-child(an+b of s)

Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.

https://css-tricks.com/almanac/selectors/n/nth-child/

How to unit test abstract classes: extend with stubs?

I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.

As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.

How to format a number as percentage in R?

Even later:

As pointed out by @DzimitryM, percent() has been "retired" in favor of label_percent(), which is a synonym for the old percent_format() function.

label_percent() returns a function, so to use it, you need an extra pair of parentheses.

library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%"   "0%"      "10%"     "56%"     "100%"    "10 000%"

Customize this by adding arguments inside the first set of parentheses.

label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent"   "0 percent"      "10 percent"    
## [4] "56 percent"     "100 percent"    "10,000 percent"

An update, several years later:

These days there is a percent function in the scales package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.


Try something like

percent <- function(x, digits = 2, format = "f", ...) {
  paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}

With usage, e.g.,

x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)

(If you prefer, change the format from "f" to "g".)

.Contains() on a list of custom class objects

If you want to have control over this you need to implement the [IEquatable interface][1]

[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).

How to resize datagridview control when form resizes

For me, anchoring works only if I set it to all four sides:

Anchoring: Top, Bottom, Left, Right

Setting anchoring just to Left, Bottom moves the whole object when the form is resized in bottom, left side. Setting all four sizes really resizes the object, when parent is resized.

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

ArrayList filter

Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:

// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[] 
                                  {"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
    if (!it.next().contains("How"))
        it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);

OUTPUT:

List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Adobe Flash Builder 4.6 Read Me.pdf recommendeds that you edit the eclipse.ini file for your Eclipse instance, so that it includes the following settings:

-vmargs -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:PermSize=64m

python xlrd unsupported format, or corrupt file.

Open in google sheets and then download from sheets as CSV and then reupload to drive. Then you can Open CSV file from python.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

just add:

int main()
{
    //you can leave it empty
    return 0;
}

to your project and everything will work its causes because of visual studio try to find the main function to start the project and didn't found it

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

Bash syntax error: unexpected end of file

I think file.sh is with CRLF line terminators.

run

dos2unix file.sh

then the problem will be fixed.

You can install dos2unix in ubuntu with this:

sudo apt-get install dos2unix

Python Remove last 3 characters of a string

  1. split
  2. slice
  3. concentrate

This is a good workout for beginners and it's easy to achieve.

Another advanced method is a function like this:

def trim(s):
    return trim(s[slice])

And for this question, you just want to remove the last characters, so you can write like this:

def trim(s):
    return s[ : -3] 

I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!

If you want to remove some specific characters, you can add some if judgements:

def trim(s):
    if [conditions]:   ### for some cases, I recommend using isinstance().
        return trim(s[slice])

IndentationError: unindent does not match any outer indentation level

I had a function defined, but it did not had any content apart from its function comments...

def foo(bar):
    # Some awesome temporary comment.
    # But there is actually nothing in the function!
    # D'Oh!

It yelled :

  File "foobar.py", line 69

                                ^
IndentationError: expected an indented block

(note that the line the ^ mark points to is empty)

--

Multiple solutions:

1: Just comment out the function

2: Add function comment

def foo(bar):
    '' Some awesome comment. This comment could be just one space.''

3: Add line that does nothing

def foo(bar):
    0

In any case, make sure to make it obvious why it is an empty function - for yourself, or for your peers that will use your code

Can I access constants in settings.py from templates in Django?

Django provides access to certain, frequently-used settings constants to the template such as settings.MEDIA_URL and some of the language settings if you use django's built in generic views or pass in a context instance keyword argument in the render_to_response shortcut function. Here's an example of each case:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template

def my_generic_view(request, template='my_template.html'):
    return direct_to_template(request, template)

def more_custom_view(request, template='my_template.html'):
    return render_to_response(template, {}, context_instance=RequestContext(request))

These views will both have several frequently used settings like settings.MEDIA_URL available to the template as {{ MEDIA_URL }}, etc.

If you're looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you're using in your view function, like so:

from django.conf import settings
from django.shortcuts import render_to_response

def my_view_function(request, template='my_template.html'):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render_to_response(template, context)

Now you can access settings.FAVORITE_COLOR on your template as {{ favorite_color }}.

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

Can't access object property, even though it shows up in a console log

I faced the same problem today. In my case the keys were nested, i.e key1.key2. I split the keys using split() and then used the square bracket notation, which did work for me.

var data = {
    key1: {
          key2: "some value"
       }
}

I split the keys and used it like this, data[key1][key2] which did the job for me.

How do I escape a single quote ( ' ) in JavaScript?

Since the values are actually inside of an HTML attribute, you should use &apos;

"<img src='something' onmouseover='change(&apos;ex1&apos;)' />";

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

Can I disable a CSS :hover effect via JavaScript?

You can manipulate the stylesheets and stylesheet rules themselves with javascript

var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
    ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
    ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

offsetting an html anchor to adjust for fixed header

Here's the solution that we use on our site. Adjust the headerHeight variable to whatever your header height is. Add the js-scroll class to the anchor that should scroll on click.

// SCROLL ON CLICK
// --------------------------------------------------------------------------
$('.js-scroll').click(function(){
    var headerHeight = 60;

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight
    }, 500);
    return false;
});

How to force cp to overwrite without confirmation

-n is "not to overwrite" but his question is totally opposite what you replied for.

To avoid this confirmation you can simply run the cp command wiht absolute path, it will avoid the alias.

/bin/cp sourcefile destination

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

Load text file as strings using numpy.loadtxt()

Use genfromtxt instead. It's a much more general method than loadtxt:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

Using the file col.txt:

foo bar
cat dog
man wine

This gives:

[['foo' 'bar']
 ['cat' 'dog']
 ['man' 'wine']]

If you expect that each row has the same number of columns, read the first row and set the attribute filling_values to fix any missing rows.

How to link to a named anchor in Multimarkdown?

Here is my solution (derived from SaraubhM's answer)

**Jump To**: [Hotkeys & Markers](#hotkeys-markers) / [Radii](#radii) / [Route Wizard 2.0](#route-wizard-2-0)

Which gives you:

Jump To: Hotkeys & Markers / Radii / Route Wizard 2.0

Note the changes from and . to - and also the loss of the & in the links.

How to pass an ArrayList to a varargs method parameter?

A shorter version of the accepted answer using Guava:

.getMap(Iterables.toArray(locations, WorldLocation.class));

can be shortened further by statically importing toArray:

import static com.google.common.collect.toArray;
// ...

    .getMap(toArray(locations, WorldLocation.class));

How to remove/delete a large file from commit history in Git repository?

According to GitHub Documentation, just follow these steps:

  1. Get rid of the large file

Option 1: You don't want to keep the large file:

rm path/to/your/large/file        # delete the large file

Option 2: You want to keep the large file into an untracked directory

mkdir large_files                       # create directory large_files
touch .gitignore                        # create .gitignore file if needed
'/large_files/' >> .gitignore           # untrack directory large_files
mv path/to/your/large/file large_files/ # move the large file into the untracked directory
  1. Save your changes
git add path/to/your/large/file   # add the deletion to the index
git commit -m 'delete large file' # commit the deletion
  1. Remove the large file from all commits
git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch path/to/your/large/file" \
  --prune-empty --tag-name-filter cat -- --all
git push <remote> <branch>

Print to the same line and not a new line?

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

How to create exe of a console application

an EXE file is created as long as you build the project. you can usually find this on the debug folder of you project.

C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug

Checkbox for nullable boolean

I got it to work with

@Html.EditorFor(model => model.Foo) 

and then making a file at Views/Shared/EditorTemplates/Boolean.cshtml with the following:

@model bool?

@Html.CheckBox("", Model.GetValueOrDefault())

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

How to parse JSON boolean value?

A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:

boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));

or serialize the ints as booleans from the start.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I was getting this when the app deployed. In my case, I chose "This is a full trust application" on the project security tab, and that fixed it.

error: command 'gcc' failed with exit status 1 on CentOS

" error: command 'gcc' failed with exit status 1 ". the installation failed because of missing python-devel and some dependencies.

the best way to correct gcc problem:

You need to reinstall gcc , gcc-c++ and dependencies.

For python 2.7

$ sudo yum -y install gcc gcc-c++ kernel-devel
$ sudo yum -y install python-devel libxslt-devel libffi-devel openssl-devel
$ pip install "your python packet"

For python 3.4

$ sudo apt-get install python3-dev
$ pip install "your python packet"

Hope this will help.

Difference between maven scope compile and provided for JAR packaging

  • compile

Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)

  • provided

Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

NoClassDefFoundError on Maven dependency

By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.

You could manually specify the libraries on the classpath with the -cp parameter, but that quickly becomes tiresome.

A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package.

To simply bundle all required libraries, add the following to your POM:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Once this is done, you can rerun the commands you used above:

$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App

If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Get the string representation of a DOM node

Use element.outerHTML to get full representation of element, including outer tags and attributes.

Force "git push" to overwrite remote files

Another option (to avoid any forced push which can be problematic for other contributors) is to:

  • put your new commits in a dedicated branch
  • reset your master on origin/master
  • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch).
    See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs.

That way, you can push master to remote without having to force anything.

Get random sample from list while maintaining ordering of items?

Apparently random.sample was introduced in python 2.3

so for version under that, we can use shuffle (example for 4 items):

myRange =  range(0,len(mylist)) 
shuffle(myRange)
coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]

How to schedule a task to run when shutting down windows

I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.

Tips for using Vim as a Java IDE?

I have just uploaded this Vim plugin for the development of Java Maven projects.

And don't forget to set the highlighting if you haven't already:

enter image description here https://github.com/sentientmachine/erics_vim_syntax_and_color_highlighting

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

Check if value is in select list with JQuery

Why not use a filter?

var thevalue = 'foo';    
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;

Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use

if(exists){
    // it is in the dropdown
}

Or combine it:

if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
    // found
}

Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:

var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

Make sure that the column names are the same. They are case sensitive. Here, in my case, i got this error when the column names of my model are in capitalzed and i used all the lower case letters in the data of ajax request.

So,i resolved by matching the column names exactly the same way as the existing model names.

DataTable Binding

$("#Customers").DataTable({
            ajax: {
                url: "/api/customers/",
                dataSrc: ""
            },
            columns: [
                {
                    data: "Name",
                    render: function (data, type, customer) {
                        return "<a href='/customers/edit/" + customer.Id + "'>" + customer.Name + "</a>";


                    }

                },
                {
                    data: "Name"
                },
                {
                    data: "Id",
                    render: function (data) {
                        return "<button class='btn-link js-delete' data-customer-id=" + data + ">Delete</button>";
                    }
                }
            ]
        });

Web API Method:

  public IEnumerable<Customer> GetCustomers()
        {
            return _context.Customers.ToList();

        }

My Model:-

 public class Customer
    {
        public int Id { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }        

        [Display(Name="Date Of Birth")]        
        public DateTime? BirthDate { get; set; }


        public bool isSubscribedToNewsLetter { get; set; }

        public MembershipType MembershipType { get; set; }

        [Display(Name="Membership Type")]
        [Required]
        public byte MembershipTypeId { get; set; }
    }

so here in my case, iam populating datatable with columns(Name,Name,Id).. iam duplicating the second column name to test.

Set CSS property in Javascript?

For most styles do this:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

How to fire an event on class change using jQuery?

You could replace the original jQuery addClass and removeClass functions with your own that would call the original functions and then trigger a custom event. (Using a self-invoking anonymous function to contain the original function reference)

(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('classChanged'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument

(function( func ) {
    $.fn.removeClass = function() {
        func.apply( this, arguments );
        this.trigger('classChanged');
        return this;
    }
})($.fn.removeClass);

Then the rest of your code would be as simple as you'd expect.

$(selector).on('classChanged', function(){ /*...*/ });

Update:

This approach does make the assumption that the classes will only be changed via the jQuery addClass and removeClass methods. If classes are modified in other ways (such as direct manipulation of the class attribute through the DOM element) use of something like MutationObservers as explained in the accepted answer here would be necessary.

Also as a couple improvements to these methods:

  • Trigger an event for each class being added (classAdded) or removed (classRemoved) with the specific class passed as an argument to the callback function and only triggered if the particular class was actually added (not present previously) or removed (was present previously)
  • Only trigger classChanged if any classes are actually changed

    (function( func ) {
        $.fn.addClass = function(n) { // replace the existing function on $.fn
            this.each(function(i) { // for each element in the collection
                var $this = $(this); // 'this' is DOM element in this context
                var prevClasses = this.getAttribute('class'); // note its original classes
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString(); // retain function-type argument support
                $.each(classNames.split(/\s+/), function(index, className) { // allow for multiple classes being added
                    if( !$this.hasClass(className) ) { // only when the class is not already present
                        func.call( $this, className ); // invoke the original function to add the class
                        $this.trigger('classAdded', className); // trigger a classAdded event
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged'); // trigger the classChanged event
            });
            return this; // retain jQuery chainability
        }
    })($.fn.addClass); // pass the original function as an argument
    
    (function( func ) {
        $.fn.removeClass = function(n) {
            this.each(function(i) {
                var $this = $(this);
                var prevClasses = this.getAttribute('class');
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString();
                $.each(classNames.split(/\s+/), function(index, className) {
                    if( $this.hasClass(className) ) {
                        func.call( $this, className );
                        $this.trigger('classRemoved', className);
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged');
            });
            return this;
        }
    })($.fn.removeClass);
    

With these replacement functions you can then handle any class changed via classChanged or specific classes being added or removed by checking the argument to the callback function:

$(document).on('classAdded', '#myElement', function(event, className) {
    if(className == "something") { /* do something */ }
});

Get day of week using NSDate

extension Date {

var weekdayName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "E"
    return formatter.string(from: self as Date)
}

var weekdayNameFull: String {
    let formatter = DateFormatter(); formatter.dateFormat = "EEEE"
    return formatter.string(from: self as Date)
}
var monthName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "MMM"
    return formatter.string(from: self as Date)
}
var OnlyYear: String {
    let formatter = DateFormatter(); formatter.dateFormat = "YYYY"
    return formatter.string(from: self as Date)
}
var period: String {
    let formatter = DateFormatter(); formatter.dateFormat = "a"
    return formatter.string(from: self as Date)
}
var timeOnly: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm"
    return formatter.string(from: self as Date)
}
var timeWithPeriod: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm a"
    return formatter.string(from: self as Date)
}

var DatewithMonth: String {
    let formatter = DateFormatter(); formatter.dateStyle = .medium ;        return formatter.string(from: self as Date)
}
}

usage let weekday = Date().weekdayName

Convert multiple rows into one with comma as separator

In SQLite this is simpler. I think there are similar implementations for MySQL, MSSql and Orable

CREATE TABLE Beatles (id integer, name string );
INSERT INTO Beatles VALUES (1, "Paul");
INSERT INTO Beatles VALUES (2, "John");
INSERT INTO Beatles VALUES (3, "Ringo");
INSERT INTO Beatles VALUES (4, "George");
SELECT GROUP_CONCAT(name, ',') FROM Beatles;

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should always use semicolons. Why? Because if you end up using a JavaScript compressor, all your code will be on one line, which will break your code.

Try http://www.jslint.com/; it will hurt your feelings, but show you many ways to write better JavaScript (and one of the ways is to always use semicolons).

C: convert double to float, preserving decimal point precision

Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:

http://en.wikipedia.org/wiki/Floating_point

Posting raw image data as multipart/form-data in curl

CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA

// files to upload

$filename = "https://example.s3.amazonaws.com/0.jpg";       

// URL to upload to (Destination server)

$url = "https://otherserver/image";

AND

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => file_get_contents($filename),
        CURLOPT_HTTPHEADER => array(
            //"Authorization: Bearer $TOKEN",
            "Content-Type: multipart/form-data",
            "Content-Length: " . strlen(file_get_contents($filename)),
            "API-Key: abcdefghi" //Optional if required
        ),
    ));

   $response = curl_exec($curl);

    $info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

    var_dump($response);
    $err = curl_error($curl);

    echo "error";
    var_dump($err);
    curl_close($curl);

ActionLink htmlAttributes

The problem is that your anonymous object property data-icon has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:

Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new {@class="ui-btn-right", data_icon="gear"})

Use the overload that takes in a dictionary:

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });

How can I format a number into a string with leading zeros?

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I have found a great work-around for this. It really only works practically if you want to be able to select up to 4 or so options from your drop down list but here it is:

For each "item" create as many rows as drop-down items you'd like to be able to select. So if you want to be able to select up to 3 characteristics from a given drop down list for each person on your list, create a total of 3 rows for each person. Then merge A:1-A:3, B:1-B:3, C:1-C:3 etc until you reach the column that you'd like your drop-down list to be. Don't merge those cells, instead place the your Data Validation drop-down in each of those cells.

enter image description here

Hope this is clear!!

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

python
>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code

#!<path_from_which_python_command>

How can I dynamically add items to a Java array?

Look at java.util.LinkedList or java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

Disable Tensorflow debugging information

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

PLS-00201 - identifier must be declared

The procedure name should be in caps while creating procedure in database. You may use small letters for your procedure name while calling from Java class like:

String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";

In database the name of procedure should be:

GETDBUSERBYUSERID    -- (all letters in caps only)

This serves as one of the solutions for this problem.

How to refresh Android listview?

i got some problems with dynamic refresh of my listview.

Call notifyDataSetChanged() on your Adapter.

Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.

notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.

In my second class i used

Runnable run = new Runnable(){
     public void run(){
         contactsActivity.update();
     }
};
contactsActivity.runOnUiThread(run);

to acces the update() from my Activity. This update includes

myAdapter.notifyDataSetChanged();

to tell the Adapter to refresh the view. Worked fine as far as I can say.

How to set environment variables in Jenkins?

There is Build Env Propagator Plugin which lets you add new build environment variables, e.g.

Jenkins Build - Propagate build environment variables

Any successive Propagate build environment variables step will override previously defined environment variable values.

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Sort Dictionary by keys

For Swift 3, the following sort returnes sorted dictionary by keys:

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]

let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })

print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

How to install Jdk in centos

There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:

OpenJDK Runtime Environment (Java SE 6)

yum install java-1.6.0-openjdk

OpenJDK Runtime Environment (Java SE 7)

yum install java-1.7.0-openjdk

OpenJDK Development Environment (Java SE 7)

yum install java-1.7.0-openjdk-devel

OpenJDK Development Environment (Java SE 6)

yum install java-1.6.0-openjdk-devel

Update for Java 8

In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:

OpenJDK Runtime Environment (Java SE 8)

yum install java-1.8.0-openjdk

OpenJDK Development Environment (Java SE 8)

yum install java-1.8.0-openjdk-devel

There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:

OpenJDK Runtime Environment - Headless (Java SE 8)

yum install java-1.8.0-openjdk-headless

How to identify numpy types in python?

Old question but I came up with a definitive answer with an example. Can't hurt to keep questions fresh as I had this same problem and didn't find a clear answer. The key is to make sure you have numpy imported, and then run the isinstance bool. While this may seem simple, if you are doing some computations across different data types, this small check can serve as a quick test before your start some numpy vectorized operation.

##################
# important part!
##################

import numpy as np

####################
# toy array for demo
####################

arr = np.asarray(range(1,100,2))

########################
# The instance check
######################## 

isinstance(arr,np.ndarray)

DataTables: Cannot read property style of undefined

Make sure that in your input data, response[i] and response[i][j], are not undefined/null.

If so, replace them with "".

Use own username/password with git and bitbucket

The prompt:

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

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

[email protected]:beginninggit/alias.git

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

git push

will cause:

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

if the remote origin starts with https.

Check your remote with:

git remote -v

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

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

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

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

  • Pull requests
  • Team work

How to embed a PDF viewer in a page?

PDF.js is an HTML5 technology experiment that explores building a faithful and efficient Portable Document Format (PDF) renderer without native code assistance. It is community-driven and supported by Mozilla Labs.

You can see the demo here.

How to display my application's errors in JSF?

I tried this as a best guess, but no luck:

It looks right to me. Have you tried setting a message severity explicitly? Also I believe the ID needs to be the same as that of a component (i.e., you'd need to use newPassword1 or newPassword2, if those are your IDs, and not newPassword as you had in the example).

FacesContext.getCurrentInstance().addMessage("newPassword1", 
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Message"));

Then use <h:message for="newPassword1" /> to display the error message on the JSF page.

How to request Administrator access inside a batch file

@echo off and title can come before this code:

net session>nul 2>&1
if %errorlevel%==0 goto main
echo CreateObject("Shell.Application").ShellExecute "%~f0", "", "", "runas">"%temp%/elevate.vbs"
"%temp%/elevate.vbs"
del "%temp%/elevate.vbs"
exit

:main
    <code goes here>
exit

A lot of the other answers are overkill if you don't need to worry about the following:

  • Parameters
  • Working Directory (cd %~dp0 will change to the directory containing the batch file)

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

I havent tried this scenario yet - I was scared off by the (unanswered) comments below the GA announcement blog post:

https://blogs.msdn.microsoft.com/ssdt/2017/04/19/announcing-the-general-availability-ga-release-of-ssdt-17-0-april-2017/

I'll be staying on VS15 for a while ...

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

JQuery: dynamic height() with window resize()

To see the window height while (or after) it is resized, try it:

$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});

Clear data in MySQL table with PHP?

MySQLI example where $con is the database connection variable and table name is: mytable.

mysqli_query($con,'TRUNCATE TABLE mytable');

SSL Proxy/Charles and Android trouble

The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html

Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Hope this will help to setup Charles inside your app project not on every single Android device.

powershell - extract file name and extension

If the file is coming off the disk and as others have stated, use the BaseName and Extension properties:

PS C:\> dir *.xlsx | select BaseName,Extension

BaseName                                Extension
--------                                ---------
StackOverflow.com Test Config           .xlsx  

If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension and GetExtension static methods from the System.IO.Path class:

PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to store token in Local or Session Storage in Angular 2?

var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Styling Form with Label above Inputs

There is no need to add any extra div wrapper as others suggest.

The simplest way is to wrap your input element inside a related label tag and set input style to display:block.

Bonus point earned: now you don't need to set the labels for attribute. Because every label target the nested input.

<form name="message" method="post">
    <section>
        <label class="left">
            Name
            <input id="name" type="text" name="name">
        </label>
        <label class="right">
            Email
            <input id="email" type="text" name="email">
        </label>
    </section>
</form>

https://jsfiddle.net/Tomanek1/sguh5k17/15/

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

Create a <ul> and fill it based on a passed array

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo. You might also want to note that set0 and set1 are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

makeUL(options.set0);

How to generate a Dockerfile from an image?

To understand how a docker image was built, use the docker history --no-trunc command.

You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.

The following script should work for you:

#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"

I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase

The Dockerfile is mainly useful if you want to be able to repackage an image.

The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

Change label text using JavaScript

Using .innerText should work.

document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';

Get cursor position (in characters) within a text Input field

There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.

var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;

// and if you want to know if there is a selection or not inside your input:

if (input.selectionStart != input.selectionEnd)
{
    var selectionValue =
    input.value.substring(input.selectionStart, input.selectionEnd);
}

What is the easiest way to get current GMT time in Unix timestamp format?

Python 3 seconds with microsecond decimal resolution:

from datetime import datetime
print(datetime.now().timestamp())

Python 3 integer seconds:

print(int(datetime.now().timestamp()))

WARNING on datetime.utcnow().timestamp()!

datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

For something like 1am UTC:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!

In-place edits with sed on OS X

This creates backup files. E.g. sed -i -e 's/hello/hello world/' testfile for me, creates a backup file, testfile-e, in the same dir.

Code for Greatest Common Divisor in Python

def gcdIter(a, b):
gcd= min (a,b)
for i in range(0,min(a,b)):
    if (a%gcd==0 and b%gcd==0):
        return gcd
        break
    gcd-=1

GET URL parameter in PHP

$Query_String  = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)

Array ( [ 0] => link=www.google.com )

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

How to use JavaScript to change div backgroundColor

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.

Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.

Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.

So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.

One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.

In conclusion, here is the code which I would use for such tasks:

//for adding a css class
function onOver(node){
   node.className = node.className + ' Hover';
}

//for removing a css class
function onOut(node){
    node.className = node.className.replace('Hover','');
}

function connect(node,event,fnc){
    if(node.addEventListener){
        node.addEventListener(event.substring(2,event.length),function(){
            fnc(node);
        },false);
    }else if(node.attachEvent){
        node.attachEvent(event,function(){
            fnc(node);
        });
    }
}

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
    if(div.className.match('content')){
        connect(div,'onmouseover',onOver);
        connect(div,'onmouseout',onOut);
    }
}

And you CSS whould be like this:

.content {
    background-color: blue;
}

.content.Hover{
    background-color: red;
}

.content.Hover h2{
    background-color : yellow;
}

Watch multiple $scope attributes

Why not simply wrap it in a forEach?

angular.forEach(['a', 'b', 'c'], function (key) {
  scope.$watch(key, function (v) {
    changed();
  });
});

It's about the same overhead as providing a function for the combined value, without actually having to worry about the value composition.

How to access /storage/emulated/0/

https://productforums.google.com/forum/#!msg/nexus/WIcHUNQfRLU/ALpViG86AwAJ

Mr Expensive Toys said: Am amazed that this problem is still showing up as it started happening as far back as Honeycomb.

So, the /storage/emulated/0/DCIM/Camera is the same folder as your normal DCIM/Camera folder. Its just a symlink. So the files are actually in the right location you just have an app that put bad data into the MediaStore Database.

When accessing files from your PC your are actually enumerating the MediaStorage database for files. Its not pulling a traditional directory lists. So what you see is based on what is in that database and the path entries in the database. Files in the database pointing to emulated directories aren't shown as they are assumed to be duplicates as its the same physical directory as your normal DCIM/Camera. What is going on is that some poorly written third party apps are inserting entries into the database with the /storage/emulated/0/DCIM/Camera path instead of the proper root path to DCIM/Camera. Which means that the MTP service can't see them when you are hooked up to your PC.

Usually the easiest way to fix the problem is to just clear the MediaStore databases to get the bad entries out of the MediaStore Database and let the system reindex the files and put into the database with the proper paths.

Settings->apps Hit 3 dot menu in top right and select Show System Find Media Storage, Select it, Select Storage, then Clear Data Find External Storage, Select it , Select Storage, then Clear Data Turn phone off, turn phone back on, wait for indexer service to rebuild the data.

When you are done the files should show up with proper directory tree and be visible from the PC. Depending on amount of files on the phone it can take as 10-20 minutes to rebuild the media database as the service walks the phone directories, getting meta data, creating thumbnails, etc.

What is "android:allowBackup"?

For this lint warning, as for all other lint warnings, note that you can get a fuller explanation than just what is in the one line error message; you don't have to search the web for more info.

If you are using lint via Eclipse, either open the lint warnings view, where you can select the lint error and see a longer explanation, or invoke the quick fix (Ctrl-1) on the error line, and one of the suggestions is "Explain this issue", which will also pop up a fuller explanation. If you are not using Eclipse, you can generate an HTML report from lint (lint --html <filename>) which includes full explanations next to the warnings, or you can ask lint to explain a particular issue. For example, the issue related to allowBackup has the id AllowBackup (shown at the end of the error message), so the fuller explanation is:

$ ./lint --show AllowBackup
AllowBackup
-----------
Summary: Ensure that allowBackup is explicitly set in the application's
manifest

Priority: 3 / 10
Severity: Warning
Category: Security

The allowBackup attribute determines if an application's data can be backed up and restored, as documented here.

By default, this flag is set to true. When this flag is set to true, application data can be backed up and restored by the user using adb backup and adb restore.

This may have security consequences for an application. adb backup allows users who have enabled USB debugging to copy application data off of the device. Once backed up, all application data can be read by the user. adb restore allows creation of application data from a source specified by the user. Following a restore, applications should not assume that the data, file permissions, and directory permissions were created by the application itself.

Setting allowBackup="false" opts an application out of both backup and restore.

To fix this warning, decide whether your application should support backup and explicitly set android:allowBackup=(true|false)

Click here for More information

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How can I execute Shell script in Jenkinsfile?

Based on the number of views this question has, it looks like a lot of people are visiting this to see how to set up a job that executes a shell script.

These are the steps to execute a shell script in Jenkins:

  • In the main page of Jenkins select New Item.
  • Enter an item name like "my shell script job" and chose Freestyle project. Press OK.
  • On the configuration page, in the Build block click in the Add build step dropdown and select Execute shell.
  • In the textarea you can either paste a script or indicate how to run an existing script. So you can either say:

    #!/bin/bash
    
    echo "hello, today is $(date)" > /tmp/jenkins_test
    

    or just

    /path/to/your/script.sh
    
  • Click Save.

Now the newly created job should appear in the main page of Jenkins, together with the other ones. Open it and select Build now to see if it works. Once it has finished pick that specific build from the build history and read the Console output to see if everything happened as desired.

You can get more details in the document Create a Jenkins shell script job in GitHub.

Fluid width with equally spaced DIVs

Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between property fails (see the end of the post)

To date, the only clean solution for this is with the

CSS Grid Layout Module (Codepen demo)

Basically the relevant code necessary boils down to this:

ul {
  display: grid; /* (1) */
  grid-template-columns: repeat(auto-fit, 120px); /* (2) */
  grid-gap: 1rem; /* (3) */
  justify-content: space-between; /* (4) */
  align-content: flex-start; /* (5) */
}

1) Make the container element a grid container

2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit (as apposed to auto-fill) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) and 5) - Similar to flexbox.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fit, 120px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  /* boring properties: */_x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen demo (Resize to see the effect)


Browser Support - Caniuse

Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)


NB:

Flexbox's space-between property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap) - fails, because you have no control over the alignment of the last row of items; the last row will always be justified (usually not what you want)

To demonstrate:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-wrap: wrap;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
  _x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  width: 110px;_x000D_
  height: 80px;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen (Resize to see what i'm talking about)


Further reading on CSS grids:

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.


An Analogy...

Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. Give me a ring back when you've got the information!

At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.


Imagine if the conversation had gone like this instead;

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. I'll wait.

And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.


This is asynchronous vs. synchronous behavior

This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).

Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.

var outerScopeVar;    
var img = document.createElement('img');

// Here we register the callback function.
img.onload = function() {
    // Code within this function will be executed once the image has loaded.
    outerScopeVar = this.width;
};

// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';
alert(outerScopeVar);

In the code above, we're asking JavaScript to load lolcat.png, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar).

This is why we see the alert showing undefined; since the alert() is processed immediately, rather than after the image has been loaded.

In order to fix our code, all we have to do is move the alert(outerScopeVar) code into the callback function. As a consequence of this, we no longer need the outerScopeVar variable declared as a global variable.

var img = document.createElement('img');

img.onload = function() {
    var localScopeVar = this.width;
    alert(localScopeVar);
};

img.src = 'lolcat.png';

You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.

Therefore, in all of our examples, the function() { /* Do something */ } is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!

* Technically you can use eval() as well, but eval() is evil for this purpose


How do I keep my caller waiting?

You might currently have some code similar to this;

function getWidthOfImage(src) {
    var outerScopeVar;

    var img = document.createElement('img');
    img.onload = function() {
        outerScopeVar = this.width;
    };
    img.src = src;
    return outerScopeVar;
}

var width = getWidthOfImage('lolcat.png');
alert(width);

However, we now know that the return outerScopeVar happens immediately; before the onload callback function has updated the variable. This leads to getWidthOfImage() returning undefined, and undefined being alerted.

To fix this, we need to allow the function calling getWidthOfImage() to register a callback, then move the alert'ing of the width to be within that callback;

function getWidthOfImage(src, cb) {     
    var img = document.createElement('img');
    img.onload = function() {
        cb(this.width);
    };
    img.src = src;
}

getWidthOfImage('lolcat.png', function (width) {
    alert(width);
});

... as before, note that we've been able to remove the global variables (in this case width).

How to Consolidate Data from Multiple Excel Columns All into One Column

Best and Simple solution to follow:

Select the range of the columns you want to be copied to single column

Copy the range of cells (multiple columns)

Open Notepad++

Paste the selected range of cells

Press Ctrl+H, replace \t by \n and click on replace all

all the multiple columns fall under one single column

now copy the same and paste in excel

Simple and effective solution for those who dont want to waste time coding in VBA

How to use jQuery Plugin with Angular 4?

If you have the need to use other libraries in projects --typescript-- not just in projects - angle - you can look for tds's (TypeScript Declaration File) that are depares and that have information of methods, types, functions, etc. , which can be used by TypeScript, usually without the need for import. declare var is the last resource

npm install @types/lib-name --save-dev

How to scanf only integer and repeat reading if the user enters non-numeric characters?

Use scanf("%d",&rows) instead of scanf("%s",input)

This allow you to get direcly the integer value from stdin without need to convert to int.

If the user enter a string containing a non numeric characters then you have to clean your stdin before the next scanf("%d",&rows).

your code could look like this:

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

int clean_stdin()
{
    while (getchar()!='\n');
    return 1;
}

int main(void)  
{ 
    int rows =0;  
    char c;
    do
    {  
        printf("\nEnter an integer from 1 to 23: ");

    } while (((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) || rows<1 || rows>23);

    return 0;  
}

Explanation

1)

scanf("%d%c", &rows, &c)

This means expecting from the user input an integer and close to it a non numeric character.

Example1: If the user enter aaddk and then ENTER, the scanf will return 0. Nothing capted

Example2: If the user enter 45 and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting \n

Example3: If the user enter 45aaadd and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting a

2)

(scanf("%d%c", &rows, &c)!=2 || c!='\n')

In the example1: this condition is TRUE because scanf return 0 (!=2)

In the example2: this condition is FALSE because scanf return 2 and c == '\n'

In the example3: this condition is TRUE because scanf return 2 and c == 'a' (!='\n')

3)

((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())

clean_stdin() is always TRUE because the function return always 1

In the example1: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

In the example2: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is FALSE so the condition after the && will not checked (because what ever its result is the whole condition will be FALSE ) so the clean_stdin() will not be executed and the whole condition is FALSE

In the example3: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

So you can remark that clean_stdin() will be executed only if the user enter a string containing non numeric character.

And this condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) will return FALSE only if the user enter an integer and nothing else

And if the condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) is FALSE and the integer is between and 1 and 23 then the while loop will break else the while loop will continue

PHP Array to CSV

It worked for me.

 $f=fopen('php://memory','w');
 $header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );      
 fputcsv($f,$header);
 fputcsv($f,$header);
 fputcsv($f,$header); 
 fseek($f,0);
 header('content-type:text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";');
 fpassthru($f);```

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Mailto: Body formatting

Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).

You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)

By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

Move branch pointer to different commit without checkout

The recommended solution git branch -f branch-pointer-to-move new-pointer in TortoiseGit:

  • "Git Show log"
  • Check "All Branches"
  • On the line you want the branch pointer to move to (new-pointer):
    • Right click, "Create Branch at this version"
    • Beside "Branch", enter the name of the branch to move (branch-pointer-to-move)
    • Under "Base On", check that the new pointer is correct
    • Check "Force"
    • Ok

enter image description here

enter image description here

How do the post increment (i++) and pre increment (++i) operators work in Java?

pre-increment and post increment are equivalent if not in an expression

int j =0;
int r=0         
for(int v = 0; v<10; ++v) { 
          ++r;
          j++;
          System.out.println(j+" "+r);
  }  
 1 1  
 2 2  
 3 3       
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
10 10

Mime type for WOFF fonts?

As of February 2017, RFC8081 is the proposed standard. It defines a top-level media type for fonts, therefore the standard media type for WOFF and WOFF2 are as follows:

font/woff
font/woff2

Chrome ignores autocomplete="off"

Up until just this last week, the two solutions below appeared to work for Chrome, IE and Firefox. But with the release of Chrome version 48 (and still in 49), they no longer work:

  1. The following at the top of the form:
<input style="display:none" type="text" name="fakeUsername"/>
<input style="display:none" type="password" name="fakePassword"/>
  1. The following in the password input element:

    autocomplete="off"

So to quickly fix this, at first I tried to use a major hack of initially setting the password input element to disabled and then used a setTimeout in the document ready function to enable it again.

setTimeout(function(){$('#PasswordData').prop('disabled', false);}, 50);

But this seemed so crazy and I did some more searching and found @tibalts answer in Disabling Chrome Autofill. His answer is to use autocomplete="new-password" in the passwords input and this appears to work on all browsers (I have kept my fix number 1 above at this stage).

Here is the link in the Google Chrome developer discussion: https://code.google.com/p/chromium/issues/detail?id=370363#c7

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

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

Two options:

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

Or

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

(code in playground)


Edit

String enums look different than regular ones, for example:

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

Compiles into:

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

Which just gives you this object:

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

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

Object.keys(MyEnum);

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

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

Or using Object.values():

Object.values(MyEnum)

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

Using Vim's tabs like buffers

This is an answer for those not familiar with Vim and coming from other text editors (in my case Sublime Text).

I read through all these answers and it still wasn't clear. If you read through them enough things begin to make sense, but it took me hours of going back and forth between questions.

The first thing is, as others have explained:

Tab Pages, sound a lot like tabs, they act like tabs and look a lot like tabs in most other GUI editors, but they're not. I think it's an a bad mental model that was built on in Vim, which unfortunately clouds the extra power that you have within a tab page.

The first description that I understood was from @crenate's answer is that they are the equivalent to multiple desktops. When seen in that regard you'd only ever have a couple of desktops open but have lots of GUI windows open within each one.

I would say they are similar to in other editors/browsers:

  1. Tab groupings
  2. Sublime Text workspaces (i.e. a list of the open files that you have in a project)

When you see them like that you realise the power of them that you can easily group sets of files (buffers) together e.g. your CSS files, your HTML files and your JS files in different tab pages. Which is actually pretty awesome.

Other descriptions that I find confusing

Viewport

This makes no sense to me. A viewport which although it does have a defined dictionary term, I've only heard referring to Vim windows in the :help window doc. Viewport is not a term I've ever heard with regards to editors like Sublime Text, Visual Studio, Atom, Notepad++. In fact I'd never heard about it for Vim until I started to try using tab pages.

If you view tab pages like multiple desktops, then referring to a desktop as a single window seems odd.

Workspaces

This possibly makes more sense, the dictionary definition is:

A memory storage facility for temporary use.

So it's like a place where you store a group of buffers.

I didn't initially sound like Sublime Text's concept of a workspace which is a list of all the files that you have open in your project:

the sublime-workspace file, which contains user specific data, such as the open files and the modifications to each.

However thinking about it more, this does actually agree. If you regard a Vim tab page like a Sublime Text project, then it would seem odd to have just one file open in each project and keep switching between projects. Hence why using a tab page to have open only one file is odd.

Collection of windows

The :help window refers to tab pages this way. Plus numerous other answers use the same concept. However until you get your head around what a vim window is, then that's not much use, like building a castle on sand.

As I referred to above, a vim window is the same as a viewport and quiet excellently explained in this linux.com article:

A really useful feature in Vim is the ability to split the viewable area between one or more files, or just to split the window to view two bits of the same file more easily. The Vim documentation refers to this as a viewport or window, interchangeably.

You may already be familiar with this feature if you've ever used Vim's help feature by using :help topic or pressing the F1 key. When you enter help, Vim splits the viewport and opens the help documentation in the top viewport, leaving your document open in the bottom viewport.

I find it odd that a tab page is referred to as a collection of windows instead of a collection of buffers. But I guess you can have two separate tab pages open each with multiple windows all pointing at the same buffer, at least that's what I understand so far.

How to connect Bitbucket to Jenkins properly

I had a similar problems, till I got it working. Below is the full listing of the integration:

  1. Generate public/private keys pair: ssh-keygen -t rsa
  2. Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console: enter image description here

  3. Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything: enter image description here

  4. run this command to test if you can get access to Bitbucket account: ssh -T [email protected]

  5. OPTIONAL: Now, you can use your git to to copy repo to your desk without passwjord git clone [email protected]:username/repo_name.git
  6. Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:

    1. Add an authentication token inside the job/project you configure, it can be anything: enter image description here

    2. In Bitbucket hooks: choose jenkins hooks, and fill the fields as below: enter image description here

Where:

**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project 

Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.

"Could not find bundler" error

Just in case, I had similar error with bundler 2.1.2 and solved it with:

sudo gem install bundler -v 1.17.3

If you have several bundler versions installed, then you can run specific version of bundle this way: bundle _1.17.3_ exec rspec

Though seems like later bundler versions are pretty buggy (had issues on 3 different projects on 2 operation systems), having one old bundler may work the best, at least this is what I have on my Ubuntu & MacOS

Latest bundler versions may override stable bundler -v 1.17.3. It can be not easy to remove latest bundler from system, here is what helped me:

How to open an Excel file in C#?

private void btnChoose2_Click(object sender, EventArgs e)
{
  OpenFileDialog openfileDialog1 = new OpenFileDialog();
  if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {
    this.btnChoose2.Text = openfileDialog1.FileName;
    String filename = DialogResult.ToString();

    var excelApp = new Excel.Application();
    excelApp.Visible = true;
    excelApp.Workbooks.Open(btnChoose2.Text);
  }
}

How to convert DateTime to VarChar

DECLARE @DateTime DATETIME
SET @DateTime = '2018-11-23 10:03:23'
SELECT CONVERT(VARCHAR(100),@DateTime,121 )

Is there a shortcut to make a block comment in Xcode?

i managed to get this working well via an automator task and have used shortcut to bind it to key combination ctrl+option+command+b. all i have to do is highlight the code i want block commented in xcode and press the above keys and the selected text is block commented out using /* ... */.

i use code folding a fair bit so the reason i wanted this functionality was so i could easily fold down a block of commented code ... code commented the usual way using // wont fold.

im not familiar with using mac automator but i simply followed the instrux in the following wwdc video

in the WWDC 2012 video Session 402 - Working Efficiently with Xcode ( from around 6 minutes in) there's a description of how to use the Mac OSX Automator to add a service to manipulate selected text. The example shown in the video is to remove duplicates in a selection of text using the shell commands sort and uniq. Using this approach you do the same but you enter the following command instead of what he does in the video

awk 'BEGIN{print "/"}{print $0}END{print "/"}'

(note there are meant to be 2 asterisks in the previous line that for some reason are not showing .... they do show up in the screenshot below so copy that as the correct command to enter)

you should end up running a shell script like this

screenshot

this will, for any given selected text, put the comment delimiters before and after.

when you save it you should get options to name it (i called it blockcomment) and also to assign a keyboard shortcut

then you should be able to open xcode, select some text, right click, the context menu, and the name you gave to this script should show near the bottom

simply click the name and the script will run and block comment the selected code or use the keyboard shortcut you assigned.

hope this helps

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

I had this issue on .net core 2.1, visual studio version 15.9.6. When i deleted the .vs folder, i reopened visual studio and the problem was still there. The solution that worked for me below:

  1. Delete .vs folder (it is a hidden folder).
  2. Restart Computer.

Other Solutions:

  • Close Visual Studio, delete bin and obj folders from the project folder. Open Project then rebuild solution.
  • Try running Visual Studio as Administrator.
  • Clean Solution then rebuild
  • 1) Clean Solution. 2) Exit Visual Studio. 3) delete .vs folder 4) Re-open Visual Studio

WCF gives an unsecured or incorrectly secured fault error

You have obviously a problem with the WCF security subsystem. What binding are you using? What authentication? Encryption? Signing? Do you have to cross domain boundaries?

A bit of goggling further reveals that others are experiencing this error if the clocks of client and server are out of sync (more than about five minutes) because some security schemata rely on synchronized clocks.

Any way to Invoke a private method?

You can invoke private method with reflection. Modifying the last bit of the posted code:

Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);

There are a couple of caveats. First, getDeclaredMethod will only find method declared in the current Class, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager can prevent use of the setAccessible method. So, it may need to run as a PrivilegedAction (using AccessController or Subject).

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

How do I execute a *.dll file

It should be mentioned that since it is entirely possible to run DLL's just as any other executable, it has long been considered a security issue. As such, there have been a number of security improvements and registry hacks (sorry no longer have ref-links) that prevents running DLL's from regular user space without extra privileges.

As a good example. I recall making these hacks, but since I no longer remember what exactly I did. I can no longer run any DLLs from normal user shell environment, even though starting various Win apps from GUI works just fine.

That said, one should definitely read "Dynamic-Link Library Security" and "Best Practices to Prevent DLL Hijacking".

Import Google Play Services library in Android Studio

Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"

Open File > Project Structure and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".

GMS dependency

This is a bug in Android Studio and fixed for the next release(0.4.3)

how to remove new lines and returns from php string?

To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.25.0-GA</version>
</dependency>

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

A table name as a variable

You'll need to generate the SQL content dynamically:

declare @tablename varchar(50)

set @tablename = 'test'

declare @sql varchar(500)

set @sql = 'select * from ' + @tablename

exec (@sql)

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

What is your single most favorite command-line trick using Bash?

Here's a couple of configuration tweaks:

~/.inputrc:

"\C-[[A": history-search-backward
"\C-[[B": history-search-forward

This works the same as ^R but using the arrow keys instead. This means I can type (e.g.) cd /media/ then hit up-arrow to go to the last thing I cd'd to inside the /media/ folder.

(I use Gnome Terminal, you may need to change the escape codes for other terminal emulators.)

Bash completion is also incredibly useful, but it's a far more subtle addition. In ~/.bashrc:

if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

This will enable per-program tab-completion (e.g. attempting tab completion when the command line starts with evince will only show files that evince can open, and it will also tab-complete command line options).

Works nicely with this also in ~/.inputrc:

set completion-ignore-case on
set show-all-if-ambiguous on
set show-all-if-unmodified on

Python Pandas Counting the Occurrences of a Specific value

An elegant way to count the occurrence of '?' or any symbol in any column, is to use built-in function isin of a dataframe object.

Suppose that we have loaded the 'Automobile' dataset into df object. We do not know which columns contain missing value ('?' symbol), so let do:

df.isin(['?']).sum(axis=0)

DataFrame.isin(values) official document says:

it returns boolean DataFrame showing whether each element in the DataFrame is contained in values

Note that isin accepts an iterable as input, thus we need to pass a list containing the target symbol to this function. df.isin(['?']) will return a boolean dataframe as follows.

    symboling   normalized-losses   make    fuel-type   aspiration-ratio ...
0   False       True                False   False       False
1   False       True                False   False       False
2   False       True                False   False       False
3   False       False               False   False       False
4   False       False               False   False       False
5   False       True                False   False       False
...

To count the number of occurrence of the target symbol in each column, let's take sum over all the rows of the above dataframe by indicating axis=0. The final (truncated) result shows what we expect:

symboling             0
normalized-losses    41
...
bore                  4
stroke                4
compression-ratio     0
horsepower            2
peak-rpm              2
city-mpg              0
highway-mpg           0
price                 4

Can I add and remove elements of enumeration at runtime in Java

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

Casting an int to a string in Python

Either:

"ME" + str(i)

Or:

"ME%d" % i

The second one is usually preferred, especially if you want to build a string from several tokens.

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Java LinkedHashMap get first or last entry

LinkedHashMap current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.

Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.

It could look like:

public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
  if (map.isEmpty()) return null;
  return map.entrySet().iterator().next();
}

public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
  try {
    if (map instanceof LinkedHashMap) return getLastViaReflection(map);
  } catch (Exception ignore) { }
  return getLastByIterating(map);
}

private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
  Entry<K, V> last = null;
  for (Entry<K, V> e : map.entrySet()) last = e;
  return last;
}

private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
  Field tail = map.getClass().getDeclaredField("tail");
  tail.setAccessible(true);
  return (Entry<K, V>) tail.get(map);
}

Can I stretch text using CSS?

The only way I can think of for short texts like "MENU" is to put every single letter in a span and justify them in a container afterwards. Like this:

<div class="menu-burger">
  <span></span>
  <span></span>
  <span></span>
  <div>
    <span>M</span>
    <span>E</span>
    <span>N</span>
    <span>U</span>
  </div>
</div>

And then the CSS:

.menu-burger {
  width: 50px;
  height: 50px;
  padding: 5px;
}

...

.menu-burger > div {
  display: flex;
  justify-content: space-between;
}

How do I clone a subdirectory only of a Git repository?

This looks far simpler:

git archive --remote=<repo_url> <branch> <path> | tar xvf -

print memory address of Python variable

According to the manual, in CPython id() is the actual memory address of the variable. If you want it in hex format, call hex() on it.

x = 5
print hex(id(x))

this will print the memory address of x.

How can I convert an image into a Base64 string?

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

What is a lambda (function)?

It refers to lambda calculus, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., ? : ? ? ?.

Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:

(lambda (x y) (* x y)) 

It can be applied in-line like this (evaluates to 50):

((lambda (x y) (* x y)) 5 10)

IOException: Too many open files

You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.

Radio/checkbox alignment in HTML/CSS

Below I will insert a checkbox dynamically. Style is included to align the checkbox and most important to make sure word wrap is straight. the most important thing here is display: table-cell; for the alignment

The visual basic code.

'the code to dynamically insert a checkbox

Dim tbl As Table = New Table()
Dim tc1 As TableCell = New TableCell()
tc1.CssClass = "tdCheckTablecell"

'get the data for this checkbox
Dim ds As DataSet
Dim Company As ina.VullenCheckbox
Company = New ina.VullenCheckbox
Company.IDVeldenperScherm = HETid
Company.IDLoginBedrijf = HttpContext.Current.Session("welkbedrijf")
ds = Company.GetsDataVullenCheckbox("K_GetS_VullenCheckboxMasterDDLOmschrijvingVC") 'ds6

'create the checkbox

Dim radio As CheckBoxList = New CheckBoxList
radio.DataSource = ds
radio.ID = HETid
radio.CssClass = "tdCheck"
radio.DataTextField = "OmschrijvingVC"
radio.DataValueField = "IDVullenCheckbox"
radio.Attributes.Add("onclick", "documentChanged();")
radio.DataBind()

'connect the checkbox

tc1.Controls.Add(radio)
tr.Cells.Add(tc1)
tbl.Rows.Add(tr)

'the style for the checkbox

input[type="checkbox"] {float: left;   width: 5%; height:20px; border: 1px solid black; }

.tdCheck label {     width: 90%;display: table-cell;    align:right;}

.tdCheck {width:100%;}

and the HTML output

<head id="HEAD1">
    <title>
        name
    </title>
    <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR" /><meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE" />
</head>
<style type='text/css'>
input[type="checkbox"] {float: left;   width: 20px; height:20px;  }
.tdCheck label {     width: 90%;display: table-cell;    align:right;}
.tdCheck {width:100%;}
.tdLabel {width:100px;}
.tdCheckTableCell {width:400px;}
TABLE
{

vertical-align:top;
border:1;border-style:solid;margin:0;padding:0;border-spacing:0;
border-color:red;
}
TD
{
vertical-align:top; /*labels ed en de items in het datagrid*/
border: 1;  border-style:solid;
border-color:green;
    font-size:30px  }
</style>
<body id="bodyInternet"  > 
    <form name="Form2" method="post" action="main.aspx?B" id="Form2">
        <table border="0">
            <tr>
                <td class="tdLabel">
                    <span id="ctl16_ID{A}" class="DynamicLabel">
                        TITLE
                    </span>
                </td>
                <td class="tdCheckTablecell">
                    <table id="ctl16_{A}" class="tdCheck" onclick="documentChanged();" border="0">
                        <tr>
                            <td>
                                <input id="ctl16_{A}_0" type="checkbox" name="ctl16${A}$0" />
                                <label for="ctl16_{A}_0">
                                    this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp  
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input id="ctl16_{A}_1" type="checkbox" name="ctl16${A}$1" />
                                <label for="ctl16_{A}_1">
                                    ITEM2
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input id="ctl16_{A}_2" type="checkbox" name="ctl16${A}$2" />
                                <label for="ctl16_{A}_2">
                                    ITEM3
                                </label>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
</form>
</body>

Difference between window.location.href and top.location.href

top refers to the window object which contains all the current frames ( father of the rest of the windows ). window is the current window.

http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific

so top.location.href can contain the "master" page link containing all the frames, while window.location.href just contains the "current" page link.

How to set True as default value for BooleanField on Django?

If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like

class MyForm(forms.Form):
    my_field = forms.BooleanField(initial=True)

If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like

class MyModel(models.Model):
    my_field = models.BooleanField(default=True)

Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:

form = MyForm(initial={'my_field':True})

Is it possible to use the SELECT INTO clause with UNION [ALL]?

For MS Access queries, this worked:

SELECT * INTO tmpFerdeen FROM( 
    SELECT top(100) *
    FROM Customers 
UNION All 
    SELECT top(100) *  
    FROM CustomerEurope 
UNION All 
    SELECT top(100) *  
    FROM CustomerAsia 
UNION All 
    SELECT top(100) *  
    FROM CustomerAmericas
) 

This did NOT work in MS Access

SELECT top(100) * 
  INTO tmpFerdeen
  FROM Customers
UNION All
  SELECT top(100) * 
  FROM CustomerEurope
UNION All
  SELECT top(100) * 
  FROM CustomerAsia
UNION All
  SELECT top(100) * 
  FROM CustomerAmericas

Should Jquery code go in header or footer?

Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.

In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

Git diff --name-only and copy that list

zip update.zip $(git diff --name-only commit commit)

How to delete a character from a string using Python

You can simply use list comprehension.

Assume that you have the string: my name is and you want to remove character m. use the following code:

"".join([x for x in "my name is" if x is not 'm'])

Best way to remove an event handler in jQuery?

maybe the unbind method will work for you

$("#myimage").unbind("click");

How to convert string to char array in C++?

Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;

  1. A constant char array is good enough for you so you go with,

    const char *array = tmp.c_str();
    
  2. Or you need to modify the char array so constant is not ok, then just go with this

    char *array = &tmp[0];
    

Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.

How can I display the current branch and folder path in terminal?

To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.

https://github.com/mathiasbynens/dotfiles


enter image description here


Installation is dead simple on OSX and Linux. Run the following command in Terminal.

git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh

This is going to:

  1. Git clone the repo.
  2. cd into the folder.
  3. Run the installation bash script.

How to remove folders with a certain name

Combining multiple answers, here's a command that works on both Linux and MacOS

rm -rf $(find . -type d -name __pycache__)

live output from subprocess command

Why not set stdout directly to sys.stdout? And if you need to output to a log as well, then you can simply override the write method of f.

import sys
import subprocess

class SuperFile(open.__class__):

    def write(self, data):
        sys.stdout.write(data)
        super(SuperFile, self).write(data)

f = SuperFile("log.txt","w+")       
process = subprocess.Popen(command, stdout=f, stderr=f)

React PropTypes : Allow different types of PropTypes for one prop

size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

Learn more: Typechecking With PropTypes

git: Your branch is ahead by X commits

git fetch will resolve this for you

If my understanding is correct, your local (cached) origin/master is out of date. This command will update the repository state from the server.

Correct modification of state arrays in React.js

This code work for me:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
    this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
  })

How to get rid of blank pages in PDF exported from SSRS

If the pages are blank coming from SSRS, you need to tweak your report layout. This will be far more efficient than running the output through and post process to repair the side effects of a layout problem.

SSRS is very finicky when it comes to pushing the boundaries of the margins. It is easy to accidentally widen/lengthen the report just by adjusting text box or other control on the report. Check the width and height property of the report surface carefully and squeeze them as much as possible. Watch out for large headers and footers.

How to run Unix shell script from Java code?

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

how to count the spaces in a java string?

please check the following code, it can help

 public class CountSpace {

    public static void main(String[] args) {

        String word = "S N PRASAD RAO";
        String data[];int k=0;
        data=word.split("");
        for(int i=0;i<data.length;i++){
            if(data[i].equals(" ")){
                k++;
            }

        }
        System.out.println(k);

    }
}