Programs & Examples On #Writeelementstring

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

Convert String into a Class Object

Continuing from my comment. toString is not the solution. Some good soul has written whole code for serialization and deserialization of an object in Java. See here: http://www.javabeginner.com/uncategorized/java-serialization

Suggested read:

  1. Old and good Java Technical Article on Serialization
  2. http://java.sun.com/developer/technicalArticles/ALT/serialization/
  3. http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/serial.html

Easiest way to convert int to string in C++

Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro uglyness.

// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
    std::ostringstream sstr;
    // fold expression
    ( sstr << std::dec << ... << args );
    return sstr.str();
}

Usage:

int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );

Original answer:

Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:

#include <sstream>

#define SSTR( x ) static_cast< std::ostringstream & >( \
        ( std::ostringstream() << std::dec << x ) ).str()

Usage is as easy as could be:

int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );

The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.

Builder Pattern in Effective Java

Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.

@Builder lets you automatically produce the code required to have your class be instantiable with code such as:

Person.builder()
  .name("Adam Savage")
  .city("San Francisco")
  .job("Mythbusters")
  .job("Unchained Reaction")
 .build(); 

Official documentation: https://www.projectlombok.org/features/Builder

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Use this snip : var IE = (navigator.userAgent.indexOf("Edge") > -1 || navigator.userAgent.indexOf("Trident/7.0") > -1) ? true : false;

Java Regex Capturing Groups

This is totally OK.

  1. The first group (m.group(0)) always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

How to debug Spring Boot application with Eclipse?

Easier solution:

Instead of typing mvn spring-boot:run, simply type mvnDebug spring-boot:run

You will still need to attach the debugger in Eclipse by making a new Debug Configuration for a "Remote Java Application" on the relevant port.

Get and set position with jQuery .offset()

Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

how to prevent adding duplicate keys to a javascript array

A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.

var array = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}

array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

Cast object to T

First check to see if it can be cast.

if (readData is T) {
    return (T)readData;
} 
try {
   return (T)Convert.ChangeType(readData, typeof(T));
} 
catch (InvalidCastException) {
   return default(T);
}

show more/Less text with just HTML and JavaScript

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                </div>
            </div>

SCRIPT:

    var showChar = 100;
    var ellipsestext = "[...]";
    $('.showmore').each(function () {
        $(this).find('.shorten_txt p').addClass('more_p').hide();
        $(this).find('.shorten_txt p:first').removeClass('more_p').show();
        $(this).find('.shorten_txt ul').addClass('more_p').hide();
        //you can do this above with every other element
        var teaser = $(this).find('.shorten_txt p:first').html();
        var con_length = parseInt(teaser.length);
        var c = teaser.substr(0, showChar);
        var h = teaser.substr(showChar, con_length - showChar);
        var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        if (con_length > showChar) {
            $(this).find(".shorten_txt p:first").html(html);
            $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
        }
    });
    $(".showmore").click(function () {
        if ($(this).hasClass("less")) {
            $(this).removeClass("less");
        } else {
            $(this).addClass("less");
        }
        $(this).find('.shorten_txt p:first span.moreelipses').toggle();
        $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
        $(this).find('.shorten_txt .more_p').toggle();
        return false;
    });

Importing a csv into mysql via command line

Most answers missing an important point like if you have created csv file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.

the correct syntax would be

load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'

here the difference is '\r\n' as against simply '\n

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

DataTrigger where value is NOT null?

Converter:

public class NullableToVisibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? Visibility.Collapsed : Visibility.Visible;
    }
}

Binding:

Visibility="{Binding PropertyToBind, Converter={StaticResource nullableToVisibilityConverter}}"

Using find to locate files that match one of multiple patterns

I had a similar need. This worked for me:

find ../../ \( -iname 'tmp' -o -iname 'vendor' \) -prune -o \( -iname '*.*rb' -o -iname '*.rjs' \) -print

Disabling the button after once click

Use modern Js events, with "once"!

const button = document.getElementById(btnId);
button.addEventListener("click", function() {
    // Submit form
}, {once : true});

// Disabling works too, but this is a more standard approach for general one-time events

Documentation, CanIUse

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

TNS Protocol adapter error while starting Oracle SQL*Plus

Try typing all of this on the command line:

sqlplus / as sysdba

As what you are doing is starting sqlplus and then using sys as sysdba as the user-name which is incorrect as that is not a valid user. By using the above command Oracle is using your system login credentials to access the db. Also, I would confirm that the sqlplus executable you are running is the correct one by checking your path - ensure it is in the bin of the server installation directories.

Indent starting from the second line of a paragraph with CSS

I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.

<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg> 
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
  • SVG's height and width determine area blocked out.
  • Y=36 is the depth to the SVG text baseline and same as font-size
  • margin-top's allow for best alignment of the SVG text and para text
  • Used first two words here to remind care needed for descenders

Yes it is cumbersome but it is also independent of the width of the containing div.

The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />

Android - save/restore fragment state

If you using bottombar and insted of viewpager you want to set custom fragment replacement logic with retrieve previously save state you can do using below code

 String current_frag_tag = null;
 String prev_frag_tag = null;



    @Override
    public void onTabSelected(TabLayout.Tab tab) {
   

        switch (tab.getPosition()) {
            case 0:

                replaceFragment(new Fragment1(), "Fragment1");
                break;

            case 1:
                replaceFragment(new Fragment2(), "Fragment2");
                break;

            case 2:
                replaceFragment(new Fragment3(), "Fragment3");
                break;

            case 3:
               replaceFragment(new Fragment4(), "Fragment4");
                break;

            default:
                replaceFragment(new Fragment1(), "Fragment1");
                break;

        }

    public void replaceFragment(Fragment fragment, String tag) {
        if (current_frag_tag != null) {
            prev_frag_tag = current_frag_tag;
        }

        current_frag_tag = tag;


        FragmentManager manager = null;
        try {
            manager = requireActivity().getSupportFragmentManager();
            FragmentTransaction ft = manager.beginTransaction();

            if (manager.findFragmentByTag(current_frag_tag) == null) { // No fragment in backStack with same tag..
                ft.add(R.id.viewpagerLayout, fragment, current_frag_tag);

                if (prev_frag_tag != null) {
                    try {
                        ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)));
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
//            ft.show(manager.findFragmentByTag(current_frag_tag));
                ft.addToBackStack(current_frag_tag);
                ft.commit();

            } else {

                try {
                    ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)))
                            .show(Objects.requireNonNull(manager.findFragmentByTag(current_frag_tag))).commit();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }




    }

Inside Child Fragments you can access fragment is visible or not using below method note: you have to implement below method in child fragment

@Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        try {
            if(hidden){
                adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onPause();
            }else{
                adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onResume();
            }
        }catch (Exception e){
       }

    }

How to revert the last migration?

Here is my solution, since the above solution do not really cover the use-case, when you use RunPython.

You can access the table via the ORM with

from django.db.migrations.recorder import MigrationRecorder

>>> MigrationRecorder.Migration.objects.all()
>>> MigrationRecorder.Migration.objects.latest('id')
Out[5]: <Migration: Migration 0050_auto_20170603_1814 for model>
>>> MigrationRecorder.Migration.objects.latest('id').delete()
Out[4]: (1, {u'migrations.Migration': 1})

So you can query the tables and delete those entries that are relevant for you. This way you can modify in detail. With RynPython migrations you also need to take care of the data that was added/changed/removed. The above example only displays, how you access the table via Djang ORM.

Return date as ddmmyyyy in SQL Server

CONVERT style 103 is dd/mm/yyyy. Then use the REPLACE function to eliminate the slashes.

SELECT REPLACE(CONVERT(CHAR(10), [MyDateTime], 103), '/', '')

Mac OS X and multiple Java versions

To install more recent versions of OpenJDK, I use this. Example for OpenJDK 14:

brew info adoptopenjdk
brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk14

See https://github.com/AdoptOpenJDK/homebrew-openjdk for current info.

How to align flexbox columns left and right?

You could add justify-content: space-between to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.

Updated Example

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: space-between;
}

_x000D_
_x000D_
#container {_x000D_
    width: 500px;_x000D_
    border: solid 1px #000;_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="a">_x000D_
        a_x000D_
    </div>_x000D_
    <div id="b">_x000D_
        b_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


You could also add margin-left: auto to the second element in order to align it to the right.

Updated Example

#b {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
    margin-left: auto;
}

_x000D_
_x000D_
#container {_x000D_
    width: 500px;_x000D_
    border: solid 1px #000;_x000D_
    display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    height: 200px;_x000D_
    margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="a">_x000D_
        a_x000D_
    </div>_x000D_
    <div id="b">_x000D_
        b_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

"could not find stored procedure"

You may need to check who the actual owner of the stored procedure is. If it is a specific different user then that could be why you can't access it.

When does Java's Thread.sleep throw InterruptedException?

Methods like sleep() and wait() of class Thread might throw an InterruptedException. This will happen if some other thread wanted to interrupt the thread that is waiting or sleeping.

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

When to use .First and when to use .FirstOrDefault with LINQ?

First:

  • Returns the first element of a sequence
  • Throws exception: There are no elements in the result
  • Use when: When more than 1 element is expected and you want only the first

FirstOrDefault:

  • Returns the first element of a sequence, or a default value if no element is found
  • Throws exception: Only if the source is null
  • Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

JavaScript split String with white space

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
    string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
    if(i != string.length-1){
        stringArray.push(" ");
    }
}

Update: Removed trailing space.

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Converting String to "Character" array in Java

This method take String as a argument and return the Character Array

/**
 * @param sourceString
 *            :String as argument
 * @return CharcterArray
 */
public static Character[] toCharacterArray(String sourceString) {
    char[] charArrays = new char[sourceString.length()];
    charArrays = sourceString.toCharArray();
    Character[] characterArray = new Character[charArrays.length];
    for (int i = 0; i < charArrays.length; i++) {
        characterArray[i] = charArrays[i];
    }
    return characterArray;
}

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

How to count lines in a document?

Use wc:

wc -l <filename>

This will output the number of lines in <filename>:

$ wc -l /dir/file.txt
3272485 /dir/file.txt

Or, to omit the <filename> from the result use wc -l < <filename>:

$ wc -l < /dir/file.txt
3272485

You can also pipe data to wc as well:

$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63

How to effectively work with multiple files in Vim

You can be an absolute madman and alias vim to vim -p by adding in your .bashrc:

alias vim="vim -p"

This will result in opening multiple files from the shell in tabs, without having to invoke :tab ball from within vim afterwards.

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

Hive insert query like SQL

Enter the following command to insert data into the testlog table with some condition:

INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;

How to submit an HTML form without redirection

See jQuery's post function.

I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.

Also, see the preventDefault function, of jQuery!

Is there a way to create multiline comments in Python?

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K should do it. Alternatively, go to product menu, press the option key, now the option "Clean" will change to "Clean Build Folder ..." select that option.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

I had this problem once, and this is how i resolved it:

  • Step-1 Clean your
    .m2/repository

  • Step-2 execute the maven command(for example mvn clean verify) from the terminal at the current project location(where your project's pom.xml file exist) instead of running maven from eclipse.
  • SQL Query - Concatenating Results into One String

    For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -

    declare @CodeNameString  nvarchar(max)
    select  @CodeNameString = COALESCE(@CodeNameString + ',', '')  + Cast(CodeName as varchar) from AccountCodes  ORDER BY Sort
    select  @CodeNameString
    

    Input type for HTML form for integer

    Prior to HTML5, input type="text" simply means a field to insert free text, regardless of what you want it be. that is the job of validations you would have to do in order to guarantee the user enters a valid number

    If you're using HTML5, you can use the new input types, one of which is number that automatically validates the text input, and forces it to be a number

    keep in mind though, that if you're building a server side app (php for example) you will still have to validate the input on that side (make sure it is really a number) since it's pretty easy to hack the html and change the input type, removing the browser validation

    Connecting to SQL Server Express - What is my server name?

    All of the following services should be running,for successful connectivity: SQL Full test filter Daemon, SQL server(SQLEXPRESS), SQL Server Agent(SQLEXPRESS), SQL Server Browser, SQL server reporting service and SQL Server VSS Writer

    Apply function to pandas groupby

    I saw a nested function technique for computing a weighted average on S.O. one time, altering that technique can solve your issue.

    def group_weight(overall_size):
        def inner(group):
            return len(group)/float(overall_size)
        inner.__name__ = 'weight'
        return inner
    
    d = {"my_label": pd.Series(['A','B','A','C','D','D','E'])}
    df = pd.DataFrame(d)
    print df.groupby('my_label').apply(group_weight(len(df)))
    
    
    
    my_label
    A    0.285714
    B    0.142857
    C    0.142857
    D    0.285714
    E    0.142857
    dtype: float64
    

    Here is how to do a weighted average within groups

    def wavg(val_col_name,wt_col_name):
        def inner(group):
            return (group[val_col_name] * group[wt_col_name]).sum() / group[wt_col_name].sum()
        inner.__name__ = 'wgt_avg'
        return inner
    
    
    
    d = {"P": pd.Series(['A','B','A','C','D','D','E'])
         ,"Q": pd.Series([1,2,3,4,5,6,7])
        ,"R": pd.Series([0.1,0.2,0.3,0.4,0.5,0.6,0.7])
         }
    
    df = pd.DataFrame(d)
    print df.groupby('P').apply(wavg('Q','R'))
    
    P
    A    2.500000
    B    2.000000
    C    4.000000
    D    5.545455
    E    7.000000
    dtype: float64
    

    File path for project files?

    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")
    

    base directory + your filename

    Regular expression: zero or more occurrences of optional character /

    /*
    

    If your delimiters are slash-based, escape it:

    \/*
    

    * means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

    How do I check if a variable is of a certain type (compare two types) in C?

    Getting the type of a variable is, as of now, possible in C11 with the _Generic generic selection. It works at compile-time.

    The syntax is a bit like that for switch. Here's a sample (from this answer):

        #define typename(x) _Generic((x),                                                 \
                _Bool: "_Bool",                  unsigned char: "unsigned char",          \
                 char: "char",                     signed char: "signed char",            \
            short int: "short int",         unsigned short int: "unsigned short int",     \
                  int: "int",                     unsigned int: "unsigned int",           \
             long int: "long int",           unsigned long int: "unsigned long int",      \
        long long int: "long long int", unsigned long long int: "unsigned long long int", \
                float: "float",                         double: "double",                 \
          long double: "long double",                   char *: "pointer to char",        \
               void *: "pointer to void",                int *: "pointer to int",         \
              default: "other")
    

    To actually use it for compile-time manual type checking, you can define an enum with all of the types you expect, something like this:

        enum t_typename {
            TYPENAME_BOOL,
            TYPENAME_UNSIGNED_CHAR,
            TYPENAME_CHAR,
            TYPENAME_SIGNED_CHAR,
            TYPENAME_SHORT_INT,
            TYPENAME_UNSIGNED_CHORT_INT,
            TYPENAME_INT,
            /* ... */
            TYPENAME_POINTER_TO_INT,
            TYPENAME_OTHER
        };
    

    And then use _Generic to match types to this enum:

        #define typename(x) _Generic((x),                                                       \
                _Bool: TYPENAME_BOOL,           unsigned char: TYPENAME_UNSIGNED_CHAR,          \
                 char: TYPENAME_CHAR,             signed char: TYPENAME_SIGNED_CHAR,            \
            short int: TYPENAME_SHORT_INT, unsigned short int: TYPENAME_UNSIGNED_SHORT_INT,     \
                  int: TYPENAME_INT,                     \
            /* ... */                                    \
                int *: TYPENAME_POINTER_TO_INT,          \
              default: TYPENAME_OTHER)
    

    How to detect scroll direction

    Following example will listen to MOUSE scroll only, no touch nor trackpad scrolls.

    It uses jQuery.on() (As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document).

    $('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) {
      if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
        //scroll down
        console.log('Down');
      } else {
        //scroll up
        console.log('Up');
      }
      //prevent page fom scrolling
      return false;
    });
    

    Works on all browsers.

    fiddle: http://jsfiddle.net/honk1/gWnNv/7/

    Razor-based view doesn't see referenced assemblies

    I was getting the same error while trying to use Smo objects in a Razor view. Apparently this is because Razor can't find the DLLs referenced in the project. I resolved this by setting "Copy Local" to true for all Smo dlls, however there might be a better solution (see Czechdude's link above) @using and web.config edits are useless because they are only needed if you wish to omit the namespace part from the type names (for instance Server instead of Microsoft.SqlServer.Management.Smo.Server)

    Android 5.0 - Add header/footer to a RecyclerView

    I had to add a footer to my RecyclerView and here I'm sharing my code snippet as I thought it might be useful. Please check the comments inside the code for better understanding of the overall flow.

    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import java.util.ArrayList;
    
    public class RecyclerViewWithFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    
        private static final int FOOTER_VIEW = 1;
        private ArrayList<String> data; // Take any list that matches your requirement.
        private Context context;
    
        // Define a constructor
        public RecyclerViewWithFooterAdapter(Context context, ArrayList<String> data) {
            this.context = context;
            this.data = data;
        }
    
        // Define a ViewHolder for Footer view
        public class FooterViewHolder extends ViewHolder {
            public FooterViewHolder(View itemView) {
                super(itemView);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Do whatever you want on clicking the item
                    }
                });
            }
        }
    
        // Now define the ViewHolder for Normal list item
        public class NormalViewHolder extends ViewHolder {
            public NormalViewHolder(View itemView) {
                super(itemView);
    
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Do whatever you want on clicking the normal items
                    }
                });
            }
        }
    
        // And now in onCreateViewHolder you have to pass the correct view
        // while populating the list item.
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View v;
    
            if (viewType == FOOTER_VIEW) {
                v = LayoutInflater.from(context).inflate(R.layout.list_item_footer, parent, false);
                FooterViewHolder vh = new FooterViewHolder(v);
                return vh;
            }
    
            v = LayoutInflater.from(context).inflate(R.layout.list_item_normal, parent, false);
    
            NormalViewHolder vh = new NormalViewHolder(v);
    
            return vh;
        }
    
        // Now bind the ViewHolder in onBindViewHolder
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    
            try {
                if (holder instanceof NormalViewHolder) {
                    NormalViewHolder vh = (NormalViewHolder) holder;
    
                    vh.bindView(position);
                } else if (holder instanceof FooterViewHolder) {
                    FooterViewHolder vh = (FooterViewHolder) holder;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        // Now the critical part. You have return the exact item count of your list
        // I've only one footer. So I returned data.size() + 1
        // If you've multiple headers and footers, you've to return total count
        // like, headers.size() + data.size() + footers.size()
    
        @Override
        public int getItemCount() {
            if (data == null) {
                return 0;
            }
    
            if (data.size() == 0) {
                //Return 1 here to show nothing
                return 1;
            }
    
            // Add extra view to show the footer view
            return data.size() + 1;
        }
    
        // Now define getItemViewType of your own.
    
        @Override
        public int getItemViewType(int position) {
            if (position == data.size()) {
                // This is where we'll add footer.
                return FOOTER_VIEW;
            }
    
            return super.getItemViewType(position);
        }
    
        // So you're done with adding a footer and its action on onClick.
        // Now set the default ViewHolder for NormalViewHolder
    
        public class ViewHolder extends RecyclerView.ViewHolder {
            // Define elements of a row here
            public ViewHolder(View itemView) {
                super(itemView);
                // Find view by ID and initialize here
            }
    
            public void bindView(int position) {
                // bindView() method to implement actions
            }
        }
    }
    

    The above code snippet adds a footer to the RecyclerView. You can check this GitHub repository for checking the implementation of adding both header and a footer.

    Android Transparent TextView?

    Although this answer is very late but might help other developer so I'm posting it here.

    Answers above showing only how to set transparent background of TextView. We can achieve transparent Textview backcgorund in two way:

    1. By setting opacity code such as #88000000 in android:background attribute
    2. By setting android:alpha="0.5" attribute to TextView

    Second approach is better because it gives flexibility to set background with different color and then setting setting opacity to widget using android:alpha="0.2"

    Example

    <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/black"
            android:alpha="0.3"
            android:textColor="@color/white"
            android:textStyle="bold"/>
    

    What's the main difference between int.Parse() and Convert.ToInt32

    Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, it throws an ArgumentNullException error.

    VBA procedure to import csv file into access

    Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

    Sub StripHeaderAndFooter()
    Dim fs As Object ''FileSystemObject
    Dim tsIn As Object, tsOut As Object ''TextStream
    Dim sFileIn As String, sFileOut As String
    Dim aryFile As Variant
    
        sFileIn = "z:\docs\FileName.csv"
        sFileOut = "z:\docs\FileOut.csv"
    
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
    
        sTmp = tsIn.ReadAll
    
        Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
        aryFile = Split(sTmp, vbCrLf)
    
        ''Start at line 3 and end at last line -1
        For i = 3 To UBound(aryFile) - 1
            tsOut.WriteLine aryFile(i)
        Next
    
        tsOut.Close
    
        DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
    End Sub
    

    Edit re various comments

    It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

    About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

    Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

    Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

    Error: Cannot match any routes. URL Segment: - Angular 2

    please modify your router.module.ts as:

    const routes: Routes = [
    {
        path: '',
        redirectTo: 'one',
        pathMatch: 'full'
    },
    {
        path: 'two',
        component: ClassTwo, children: [
            {
                path: 'three',
                component: ClassThree,
                outlet: 'nameThree',
            },
            {
                path: 'four',
                component: ClassFour,
                outlet: 'nameFour'
            },
            {
               path: '',
               redirectTo: 'two',
               pathMatch: 'full'
            }
        ]
    },];
    

    and in your component1.html

    <h3>In One</h3>
    
    <nav>
        <a routerLink="/two" class="dash-item">...Go to Two...</a>
        <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
        <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
    </nav>
    
    <router-outlet></router-outlet>                   // Successfully loaded component2.html
    <router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
    <router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'
    

    Python not working in command prompt?

    I wanted to add a common problem that happens on installation. It is possible that the path installation length is too long. To avoid this change the standard path so that it is shorter than 250 characters.

    I realized this when I installed the software and did a custom installation, on a WIN10 operation system. In the custom install, it should be possible to have Python added as PATH variable by the software

    How can I add some small utility functions to my AngularJS application?

    You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.

    function doSomething( a, b ) {
        return a + b;
    };
    
    angular.module('moduleName',[])
        // Define
        .constant('$doSomething', doSomething)
        // Usage
        .controller( 'SomeController', function( $doSomething ) {
            $scope.added = $doSomething( 100, 200 );
        })
    ;
    

    How to fix a Div to top of page with CSS only

    You can do something like this:

    <html>
    <head><title>My Glossary</title></head>
    <body style="margin:0px;">
            <div id="top" style="position:fixed;background:white;width:100%;">
                <a href="#A">A</a> |
                 <a href="#B">B</a> |
                <a href="#Z">Z</a>
            </div>
    
            <div id="term-defs" style="padding-top:1em;">
               <dl>
                   <span id="A"></span>
                   <dt>foo</dt>
                   <dd>This is the sound made by a fool</dd>
                   <!-- and so on ... ->
               </dl>
            </div>
    </body>
    </html>
    

    It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.

    Hope this helps.

    Reading a date using DataReader

     (DateTime)MyReader["ColumnName"];
    

    OR

    Convert.ToDateTime(MyReader["ColumnName"]);
    

    UICollectionView Self Sizing Cells with Auto Layout

    The solution comprises 3 simple steps:

    1. Enabling dynamic cell sizing

    flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

    1. Set the containerView.widthAnchor.constraint from collectionView(:cellForItemAt:)to limit the width of contentView to width of collectionView.
    class ViewController: UIViewController, UICollectionViewDataSource {
        ...
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! MultiLineCell
            cell.textView.text = dummyTextMessages[indexPath.row]
            cell.maxWidth = collectionView.frame.width
            return cell
        }
    
        ...
    }
    
    
    class MultiLineCell: UICollectionViewCell{
        ....
    
        var maxWidth: CGFloat? {
            didSet {
                guard let maxWidth = maxWidth else {
                    return
                }
                containerViewWidthAnchor.constant = maxWidth
                containerViewWidthAnchor.isActive = true
            }
        }
    
        ....
    }
    

    Since you want to enable self-sizing of UITextView, it has an additional step to;

    3. Calculate and set the heightAnchor.constant of UITextView.

    So, whenever the width of contentView is set we'll adjust height of UITextView along in didSet of maxWidth.

    Inside UICollectionViewCell:

    var maxWidth: CGFloat? {
        didSet {
            guard let maxWidth = maxWidth else {
                return
            }
            containerViewWidthAnchor.constant = maxWidth
            containerViewWidthAnchor.isActive = true
            
            let sizeToFitIn = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
            let newSize = self.textView.sizeThatFits(sizeToFitIn)
            self.textViewHeightContraint.constant = newSize.height
        }
    }
    

    These steps will get you the desired result.

    Complete runnable gist

    Reference: Vadim Bulavin blog post - Collection View Cells Self-Sizing: Step by Step Tutorial

    Screenshot:

    enter image description here

    getaddrinfo: nodename nor servname provided, or not known

    The error occurs when the DNS resolution fails. Check if you can wget (or curl) the api url from the command line. Changing the DNS server and testing it might help.

    Replace and overwrite instead of appending

    Using truncate(), the solution could be

    import re
    #open the xml file for reading:
    with open('path/test.xml','r+') as f:
        #convert to string:
        data = f.read()
        f.seek(0)
        f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
        f.truncate()
    

    Getting a union of two arrays in JavaScript

    _x000D_
    _x000D_
    function unique(arrayName)_x000D_
    {_x000D_
      var newArray=new Array();_x000D_
      label: for(var i=0; i<arrayName.length;i++ )_x000D_
      {  _x000D_
        for(var j=0; j<newArray.length;j++ )_x000D_
        {_x000D_
          if(newArray[j]==arrayName[i]) _x000D_
            continue label;_x000D_
        }_x000D_
        newArray[newArray.length] = arrayName[i];_x000D_
      }_x000D_
      return newArray;_x000D_
    }_x000D_
    _x000D_
    var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
    var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
    var union = unique(arr1.concat(arr2));_x000D_
    console.log(union);
    _x000D_
    _x000D_
    _x000D_

    HttpClient.GetAsync(...) never returns when using await/async

    I'm going to put this in here more for completeness than direct relevance to the OP. I spent nearly a day debugging an HttpClient request, wondering why I was never getting back a response.

    Finally found that I had forgotten to await the async call further down the call stack.

    Feels about as good as missing a semicolon.

    How to delete large data of table in SQL without log?

    Shorter syntax

    select 1
    WHILE (@@ROWCOUNT > 0)
    BEGIN
      DELETE TOP (10000) LargeTable 
      WHERE readTime < dateadd(MONTH,-7,GETDATE())
    END
    

    Yes or No confirm box using jQuery

    All the example I've seen aren't reusable for different "yes/no" type questions. I was looking for something that would allow me to specify a callback so I could call for any situation.

    The following is working well for me:

    $.extend({ confirm: function (title, message, yesText, yesCallback) {
        $("<div></div>").dialog( {
            buttons: [{
                text: yesText,
                click: function() {
                    yesCallback();
                    $( this ).remove();
                }
            },
            {
                text: "Cancel",
                click: function() {
                    $( this ).remove();
                }
            }
            ],
            close: function (event, ui) { $(this).remove(); },
            resizable: false,
            title: title,
            modal: true
        }).text(message).parent().addClass("alert");
    }
    });
    

    I then call it like this:

    var deleteOk = function() {
        uploadFile.del(fileid, function() {alert("Deleted")})
    };
    
    $.confirm(
        "CONFIRM", //title
        "Delete " + filename + "?", //message
        "Delete", //button text
        deleteOk //"yes" callback
    );
    

    Select rows with same id but different value in another column

    This ought to do it:

    SELECT *
    FROM YourTable
    WHERE ARIDNR IN (
        SELECT ARIDNR
        FROM YourTable
        GROUP BY ARIDNR
        HAVING COUNT(*) > 1
    )
    

    The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

    Input type=password, don't let browser remember the password

    I tried the following and it seems that works to any browser:

    <input id="passfld" type="text" autocomplete="off" />
    
    <script type="text/javascript">
        $(function(){  
            var passElem = $("input#passfld");
            passElem.focus(function() { 
                passElem.prop("type", "password");                                             
            });
        });
    </script>
    

    This way is much more safer than using timeout techniques, because it guaranties that the input field will yield to password when the user focuses it.

    error: Your local changes to the following files would be overwritten by checkout

    You can force checkout your branch, if you do not want to commit your local changes.

    git checkout -f branch_name
    

    Query based on multiple where clauses in Firebase

    ref.orderByChild("lead").startAt("Jack Nicholson").endAt("Jack Nicholson").listner....
    

    This will work.

    Plot multiple boxplot in one graph

    Using base graphics, we can use at = to control box position , combined with boxwex = for the width of the boxes. The 1st boxplot statement creates a blank plot. Then add the 2 traces in the following two statements.

    Note that in the following, we use df[,-1] to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.

    boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
    boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red", 
      boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
    boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue", 
      boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15
    

    enter image description here

    Some dummy data:

    df <- data.frame(
      id = c(rep("Good",200), rep("Bad", 200)),
      F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
      F2 = c(rnorm(200,7,1),  rnorm(200,6,1)),
      F3 = c(rnorm(200,6,2),  rnorm(200,9,3)),
      F4 = c(rnorm(200,12,3), rnorm(200,8,2)))
    

    C# Break out of foreach loop after X number of items

    Why not just use a regular for loop?

    for(int i = 0; i < 50 && i < listView.Items.Count; i++)
    {
        ListViewItem lvi = listView.Items[i];
    }
    

    Updated to resolve bug pointed out by Ruben and Pragmatrix.

    Spring jUnit Testing properties file

    I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

    Properties configProps = new Properties();
    InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
    InputStream iStream = getConfigFile();
    configProps.load(iStream);
    

    Splitting applicationContext to multiple files

    I'm the author of modular-spring-contexts.

    This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.

    The key points then are

    • control over dependencies between modules
    • control over which beans are exported and where they are used
    • reduced possibility of naming collisions of beans

    A simple example would look like this:

    File moduleDefinitions.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config />
    
        <module:module id="serverModule">
            <module:config location="/serverModule.xml" />
        </module:module>
    
        <module:module id="clientModule">
            <module:config location="/clientModule.xml" />
            <module:requires module="serverModule" />
        </module:module>
    
    </beans>
    

    File serverModule.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config />
    
        <bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
            <constructor-arg index="0" value="123.45" />
            <meta key="exported" value="true"/>
        </bean>
    
    </beans>
    

    File clientModule.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config />
    
        <module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />
    
    </beans>
    

    Focus Next Element In Tab Index

    Here's something I build for this purpose:

    focusNextElement: function () {
        //add all elements we want to include in our selection
        var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
        if (document.activeElement && document.activeElement.form) {
            var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
            function (element) {
                //check for visibility while always include the current activeElement 
                return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
            });
            var index = focussable.indexOf(document.activeElement);
            if(index > -1) {
               var nextElement = focussable[index + 1] || focussable[0];
               nextElement.focus();
            }                    
        }
    }
    

    Features:

    • configurable set of focusable elements
    • no jQuery needed
    • works in all modern browsers
    • fast & lightweight

    Ignore .pyc files in git repository

    Thanks @Enrico for the answer.

    Note if you're using virtualenv you will have several more .pyc files within the directory you're currently in, which will be captured by his find command.

    For example:

    ./app.pyc
    ./lib/python2.7/_weakrefset.pyc
    ./lib/python2.7/abc.pyc
    ./lib/python2.7/codecs.pyc
    ./lib/python2.7/copy_reg.pyc
    ./lib/python2.7/site-packages/alembic/__init__.pyc
    ./lib/python2.7/site-packages/alembic/autogenerate/__init__.pyc
    ./lib/python2.7/site-packages/alembic/autogenerate/api.pyc
    

    I suppose it's harmless to remove all the files, but if you only want to remove the .pyc files in your main directory, then just do

    find "*.pyc" -exec git rm -f "{}" \;

    This will remove just the app.pyc file from the git repository.

    How to create full compressed tar file using Python?

    Previous answers advise using the tarfile Python module for creating a .tar.gz file in Python. That's obviously a good and Python-style solution, but it has serious drawback in speed of the archiving. This question mentions that tarfile is approximately two times slower than the tar utility in Linux. According to my experience this estimation is pretty correct.

    So for faster archiving you can use the tar command using subprocess module:

    subprocess.call(['tar', '-czf', output_filename, file_to_archive])
    

    How do I get Flask to run on port 80?

    So it's throwing up that error message because you have apache2 running on port 80.

    If this is for development, I would just leave it as it is on port 5000.

    If it's for production either:

    Not Recommended

    • Stop apache2 first;

    Not recommended as it states in the documentation:

    You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)

    Recommended

    • Proxy HTTP traffic through apache2 to Flask.

    This way, apache2 can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.

    Here's a link to the official documentation about setting up Flask with Apache + mod_wsgi.

    Edit 1 - Clarification for @Djack

    Proxy HTTP traffic to Flask through apache2

    When a request comes to the server on port 80 (HTTP) or port 443 (HTTPS) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.

    reverse proxy for dynamic content

    There are a few advantages to configuring your web server like the above;

    • SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
    • Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
    • Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
    • +more. This is bordering on scope for this question. If you want more info do some research into this area.

    TypeError: 'str' does not support the buffer interface

    If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it).

    plaintext = input("Please enter the text you want to compress")
    filename = input("Please enter the desired filename")
    with gzip.open(filename + ".gz", "wb") as outfile:
        outfile.write(bytes(plaintext, 'UTF-8'))
    

    Also do not use variable names like string or file while those are names of module or function.

    EDIT @Tom

    Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:

    plaintext = 'Polish text: acelnószzACELNÓSZZ'
    filename = 'foo.gz'
    with gzip.open(filename, 'wb') as outfile:
        outfile.write(bytes(plaintext, 'UTF-8'))
    with gzip.open(filename, 'r') as infile:
        outfile_content = infile.read().decode('UTF-8')
    print(outfile_content)
    

    How to check if a Ruby object is a Boolean

    There is no Boolean class in Ruby, the only way to check is to do what you're doing (comparing the object against true and false or the class of the object against TrueClass and FalseClass). Can't think of why you would need this functionality though, can you explain? :)

    If you really need this functionality however, you can hack it in:

    module Boolean; end
    class TrueClass; include Boolean; end
    class FalseClass; include Boolean; end
    
    true.is_a?(Boolean) #=> true
    false.is_a?(Boolean) #=> true
    

    how do I make a single legend for many subplots with matplotlib?

    While rather late to the game, I'll give another solution here as this is still one of the first links to show up on google. Using matplotlib 2.2.2, this can be achieved using the gridspec feature. In the example below the aim is to have four subplots arranged in a 2x2 fashion with the legend shown at the bottom. A 'faux' axis is created at the bottom to place the legend in a fixed spot. The 'faux' axis is then turned off so only the legend shows. Result: https://i.stack.imgur.com/5LUWM.png.

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    #Gridspec demo
    fig = plt.figure()
    fig.set_size_inches(8,9)
    fig.set_dpi(100)
    
    rows   = 17 #the larger the number here, the smaller the spacing around the legend
    start1 = 0
    end1   = int((rows-1)/2)
    start2 = end1
    end2   = int(rows-1)
    
    gspec = gridspec.GridSpec(ncols=4, nrows=rows)
    
    axes = []
    axes.append(fig.add_subplot(gspec[start1:end1,0:2]))
    axes.append(fig.add_subplot(gspec[start2:end2,0:2]))
    axes.append(fig.add_subplot(gspec[start1:end1,2:4]))
    axes.append(fig.add_subplot(gspec[start2:end2,2:4]))
    axes.append(fig.add_subplot(gspec[end2,0:4]))
    
    line, = axes[0].plot([0,1],[0,1],'b')           #add some data
    axes[-1].legend((line,),('Test',),loc='center') #create legend on bottommost axis
    axes[-1].set_axis_off()                         #don't show bottommost axis
    
    fig.tight_layout()
    plt.show()
    

    Printing variables in Python 3.4

    The syntax has changed in that print is now a function. This means that the % formatting needs to be done inside the parenthesis:1

    print("%d. %s appears %d times." % (i, key, wordBank[key]))
    

    However, since you are using Python 3.x., you should actually be using the newer str.format method:

    print("{}. {} appears {} times.".format(i, key, wordBank[key]))
    

    Though % formatting is not officially deprecated (yet), it is discouraged in favor of str.format and will most likely be removed from the language in a coming version (Python 4 maybe?).


    1Just a minor note: %d is the format specifier for integers, not %s.

    Dynamically add data to a javascript map

    Javascript now has a specific built in object called Map, you can call as follows :

       var myMap = new Map()
    

    You can update it with .set :

       myMap.set("key0","value")
    

    This has the advantage of methods you can use to handle look ups, like the boolean .has

      myMap.has("key1"); // evaluates to false 
    

    You can use this before calling .get on your Map object to handle looking up non-existent keys

    While variable is not defined - wait

    I have upvoted @dnuttle's answer, but ended up using the following strategy:

    // On doc ready for modern browsers
    document.addEventListener('DOMContentLoaded', (e) => {
      // Scope all logic related to what you want to achieve by using a function
      const waitForMyFunction = () => {
        // Use a timeout id to identify your process and purge it when it's no longer needed
        let timeoutID;
        // Check if your function is defined, in this case by checking its type
        if (typeof myFunction === 'function') {
          // We no longer need to wait, purge the timeout id
          window.clearTimeout(timeoutID);
          // 'myFunction' is defined, invoke it with parameters, if any
          myFunction('param1', 'param2');
        } else {
          // 'myFunction' is undefined, try again in 0.25 secs
          timeoutID = window.setTimeout(waitForMyFunction, 250);
        }
      };
      // Initialize
      waitForMyFunction();
    });
    

    It is tested and working! ;)

    Gist: https://gist.github.com/dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c

    SQL Query to search schema of all tables

    For me I only have read access to run querys so I need to use this function often here is what I use:

    SELECT  *
    FROM    INFORMATION_SCHEMA.TABLES
    where   TABLES.TABLE_NAME like '%your table name here%'
    

    You can replace .TABLES with .COLUMNS then it would look like this:

     SELECT *
     FROM   INFORMATION_SCHEMA.COLUMNS
     WHERE  columns.COLUMN_NAME like '%your column name here%'
    

    Oracle: How to filter by date and time in a where clause

    Put it this way

    where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
       AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS')) 
    

    Where R is table name.
    TIME_STAMP is FieldName in Table R.

    How can I make a div not larger than its contents?

    We can use any of the two ways on the div element:

    display: table;
    

    or,

    display: inline-block; 
    

    I prefer to use display: table;, because it handles, all extra spaces on its own. While display: inline-block needs some extra space fixing.

    Importing packages in Java

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

    To import class use

    import full.package.name.of.SomeClass;
    

    to import static methods/fields use

    import static full.package.name.of.SomeClass.staticMethod;
    import static full.package.name.of.SomeClass.staticField;
    

    Python: Maximum recursion depth exceeded

    You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

    import sys
    sys.setrecursionlimit(10000) # 10000 is an example, try with different values
    

    ... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

    How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

    There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

    PDO

    PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

    <?php
    
    // Connection code. 
    $options = [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
    
    // Prepared statement
    $stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
    $stmt->execute([$_POST['email']]);
    $exists = $stmt->fetchColumn(); // either 1 or null
    
    if ($exists) {
        echo 'Email exists in the database.';
    } else {
        // email doesn't exist yet
    }
    

    For more examples see: How to check if email exists in the database?

    MySQLi

    As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

    <?php
    
    // Connection code
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
    $mysqli->set_charset('utf8mb4');
    
    // Prepared statement
    $stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
    $stmt->bind_param('s', $_POST['email']);
    $stmt->execute();
    $exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
    
    if ($exists) {
        echo 'Email exists in the database.';
    } else {
        // email doesn't exist yet
    }
    

    Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

    For more examples see: How to check whether a value exists in a database using mysqli prepared statements

    Minor remarks

    • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
    • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
    • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

    The Import android.support.v7 cannot be resolved

    Recent sdk-manager's download does not contain android-support-v7-appcompat.jar But the following dir contains aar file C:\Users\madan\android-sdks\extras\android\m2repository\com\ android\support\appcompat-v7\24.2.1\appcompat-v7-24.2.1.aar This file can be imported by right-click project, import, select general, select archieve and finally select aar file. Even this does not solve the problem. Later remove 'import android.R' and add 'import android.support.v7.appcompat.*;' Follow this tutorial for other details: http://www.srccodes.com/p/article/22/android-hello-world-example-using-eclipse-ide-and-android-development-tools-adt-plugin

    Postgresql: Scripting psql execution with password

    If you're having problems on windows like me (I'm using Windows 7 64-bit) and set PGPASSWORD=[Password] did not work.

    Then, as Kavaklioglu said in one of the comments,

    export PGPASSWORD=[password]
    

    You will need to save this at the top of the file, or before any usage so its set before being called.

    Certainly does work on windows :)

    How to convert/parse from String to char in java?

    If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt method:

    char c = s.charAt(0);
    

    Unfortunately Launcher3 has stopped working error in android studio?

    I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.

    I guess there mmust be some kind of dependency with this app.

    javascript regex for special characters

    // Regex for special symbols
    
    var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.@#]/;
    

    Trying to use fetch and pass in mode: no-cors

    Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

    The usage is straight pretty forward:
    1. Install the package: npm install -g local-ssl-proxy
    2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

    P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

    JVM heap parameters

    To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

    You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

    So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

    How do I pass JavaScript variables to PHP?

    Your code has a few things wrong with it.

    • You define a JavaScript function, func_load3(), but do not call it.
    • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
    • Your form has no means to submit it. It needs a submit button.
    • You do not check whether your form has been submitted.

    It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

    <?php
    if (isset($_POST['hidden1'])) {
       echo "You submitted {$_POST['hidden1']}";
       die;
    }
    
    echo <<<HTML
       <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
          <input type="submit" name="submit" value="Test this mess!" />
          <input type="hidden" name="hidden1" id="hidden1" />
       </form>
    
       <script type="text/javascript">
          document.getElementById("hidden1").value = "This is an example";
       </script>
    HTML;
    ?>
    

    Use CSS to remove the space between images

    Make them display: block in your CSS.

    Swift days between two NSDates

    Swift 3.2

    extension DateComponentsFormatter {
        func difference(from fromDate: Date, to toDate: Date) -> String? {
            self.allowedUnits = [.year,.month,.weekOfMonth,.day]
            self.maximumUnitCount = 1
            self.unitsStyle = .full
            return self.string(from: fromDate, to: toDate)
        }
    }
    

    How do you merge two Git repositories?

    I had to solve it as follows today: Project A was in bitbucket and Project B was in code commit .. both are the same projects but had to merge changes from A to B. (The trick is to create the same name branch in Project A, same as in Project B)

    • git checkout Project A
    • git remote remove origin
    • git remote add origin Project B
    • git checkout branch
    • git add *
    • git commit -m "we have moved the code"
    • git push

    Is it possible to get the index you're sorting over in Underscore.js?

    You can get the index of the current iteration by adding another parameter to your iterator function, e.g.

    _.each(['foo', 'bar', 'baz'], function (val, i) {
        console.log(i + ": " + val); // 0: foo, 1: bar, 2: baz
    });
    

    How does "cat << EOF" work in bash?

    Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

    $ cat >> temp.txt
    line 1
    line 2
    

    While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
    Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

    it is a section of a source code file that is treated as if it were a separate file.

    Convert HashBytes to VarChar

    I have found the solution else where:

    SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
    

    How do I pipe a subprocess call to a text file?

    The options for popen can be used in call

    args, 
    bufsize=0, 
    executable=None, 
    stdin=None, 
    stdout=None, 
    stderr=None, 
    preexec_fn=None, 
    close_fds=False, 
    shell=False, 
    cwd=None, 
    env=None, 
    universal_newlines=False, 
    startupinfo=None, 
    creationflags=0
    

    So...

    subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)
    

    Then you can do what you want with myoutput (which would need to be a file btw).

    Also, you can do something closer to a piped output like this.

    dmesg | grep hda
    

    would be:

    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    output = p2.communicate()[0]
    

    There's plenty of lovely, useful info on the python manual page.

    Exit a Script On Error

    Are you looking for exit?

    This is the best bash guide around. http://tldp.org/LDP/abs/html/

    In context:

    if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
    then
        echo $jar_file signed sucessfully
    else
        echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
        exit 1 # terminate and indicate error
    fi
    
    ...
    

    collapse cell in jupyter notebook

    There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

    %%html
    <style id=hide>div.input{display:none;}</style>
    <button type="button" 
    onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
    Show inputs</button>
    

    Or python:

    # Run me to hide code cells
    
    from IPython.core.display import display, HTML
    display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))
    

    Finding duplicate values in MySQL

    SELECT t.*,(select count(*) from city as tt
      where tt.name=t.name) as count
      FROM `city` as t
      where (
         select count(*) from city as tt
         where tt.name=t.name
      ) > 1 order by count desc
    

    Replace city with your Table. Replace name with your field name

    How to redirect the output of a PowerShell to a file during its execution

    If you want to do it from the command line and not built into the script itself, use:

    .\myscript.ps1 | Out-File c:\output.csv
    

    How to convert numbers to alphabet?

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

    >>> chr(65)
    'A'
    

    similarly if you have 97,

    >>> chr(97)
    'a'
    

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

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

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

    Android Studio Emulator and "Process finished with exit code 0"

    I restarted Android Studio and create a new device in AVD MANAGER then I have increased the RAM size of emulator and it works nicely.

    UPDATED Sometimes it happens when you close emulator during building the App in to emulator.

    SyntaxError: cannot assign to operator

    In case it helps someone, if your variables have hyphens in them, you may see this error since hyphens are not allowed in variable names in Python and are used as subtraction operators.

    Example:

    my-variable = 5   # would result in 'SyntaxError: can't assign to operator'
    

    The entity type <type> is not part of the model for the current context

    One other thing to check with your connection string - the model name. I was using two entity models, DB first. In the config I copied the entity connection for one, renamed it, and changed the connection string part. What I didn't change was the model name, so while the entity model generated correctly, when the context was initiated EF was looking in the wrong model for the entities.

    Looks obvious written down, but there are four hours I won't get back.

    Javascript checkbox onChange

    Pure javascript:

    _x000D_
    _x000D_
    const checkbox = document.getElementById('myCheckbox')
    
    checkbox.addEventListener('change', (event) => {
      if (event.currentTarget.checked) {
        alert('checked');
      } else {
        alert('not checked');
      }
    })
    _x000D_
    My Checkbox: <input id="myCheckbox" type="checkbox" />
    _x000D_
    _x000D_
    _x000D_

    How to Truncate a string in PHP to the word closest to a certain number of characters?

    Here you go:

    function neat_trim($str, $n, $delim='…') {
       $len = strlen($str);
       if ($len > $n) {
           preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
           return rtrim($matches[1]) . $delim;
       }
       else {
           return $str;
       }
    }
    

    What is the difference between require() and library()?

    You can use require() if you want to install packages if and only if necessary, such as:

    if (!require(package, character.only=T, quietly=T)) {
        install.packages(package)
        library(package, character.only=T)
    }
    

    For multiple packages you can use

    for (package in c('<package1>', '<package2>')) {
        if (!require(package, character.only=T, quietly=T)) {
            install.packages(package)
            library(package, character.only=T)
        }
    }
    

    Pro tips:

    • When used inside the script, you can avoid a dialog screen by specifying the repos parameter of install.packages(), such as

      install.packages(package, repos="http://cran.us.r-project.org")
      
    • You can wrap require() and library() in suppressPackageStartupMessages() to, well, suppress package startup messages, and also use the parameters require(..., quietly=T, warn.conflicts=F) if needed to keep the installs quiet.

    Finding an element in an array in Java

    Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

    Deleting queues in RabbitMQ

    I did it different way, because I only had access to management webpage. I created simple "snippet" which delete queues in Javascript. Here it is:

    function zeroPad(num, places) {
      var zero = places - num.toString().length + 1;
      return Array(+(zero > 0 && zero)).join("0") + num;
    }
    var queuePrefix = "PREFIX"
    for(var i=0; i<255; i++){ 
       var queueid = zeroPad(i, 4);
       $.ajax({url: '/api/queues/vhost/'+queuePrefix+queueid, type: 'DELETE', success: function(result) {console.log('deleted '+queuePrefix+queueid)}});
    }
    

    All my queues was in format: PREFIX_0001 to PREFIX_0XXX

    What is Type-safe?

    Type safety is not just a compile time constraint, but a run time constraint. I feel even after all this time, we can add further clarity to this.

    There are 2 main issues related to type safety. Memory** and data type (with its corresponding operations).

    Memory**

    A char typically requires 1 byte per character, or 8 bits (depends on language, Java and C# store unicode chars which require 16 bits). An int requires 4 bytes, or 32 bits (usually).

    Visually:

    char: |-|-|-|-|-|-|-|-|

    int : |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

    A type safe language does not allow an int to be inserted into a char at run-time (this should throw some kind of class cast or out of memory exception). However, in a type unsafe language, you would overwrite existing data in 3 more adjacent bytes of memory.

    int >> char:

    |-|-|-|-|-|-|-|-| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?|

    In the above case, the 3 bytes to the right are overwritten, so any pointers to that memory (say 3 consecutive chars) which expect to get a predictable char value will now have garbage. This causes undefined behavior in your program (or worse, possibly in other programs depending on how the OS allocates memory - very unlikely these days).

    ** While this first issue is not technically about data type, type safe languages address it inherently and it visually describes the issue to those unaware of how memory allocation "looks".

    Data Type

    The more subtle and direct type issue is where two data types use the same memory allocation. Take a int vs an unsigned int. Both are 32 bits. (Just as easily could be a char[4] and an int, but the more common issue is uint vs. int).

    |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

    |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

    A type unsafe language allows the programmer to reference a properly allocated span of 32 bits, but when the value of a unsigned int is read into the space of an int (or vice versa), we again have undefined behavior. Imagine the problems this could cause in a banking program:

    "Dude! I overdrafted $30 and now I have $65,506 left!!"

    ...'course, banking programs use much larger data types. ;) LOL!

    As others have already pointed out, the next issue is computational operations on types. That has already been sufficiently covered.

    Speed vs Safety

    Most programmers today never need to worry about such things unless they are using something like C or C++. Both of these languages allow programmers to easily violate type safety at run time (direct memory referencing) despite the compilers' best efforts to minimize the risk. HOWEVER, this is not all bad.

    One reason these languages are so computationally fast is they are not burdened by verifying type compatibility during run time operations like, for example, Java. They assume the developer is a good rational being who won't add a string and an int together and for that, the developer is rewarded with speed/efficiency.

    What is the basic difference between the Factory and Abstract Factory Design Patterns?

    By Definition we can drag out the differences of two:

    Factory: An interface is used for creating an object, but subclass decides which class to instantiate. The creation of object is done when it is required.

    Abstract Factory: Abstract Factory pattern acts as a super-factory which creates other factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

    So, in the definitions above we can emphasize on a particular difference. that is, Factory pattern is responsible for creating objects and Abstract Factory is responsible for creating a set of related objects; obviously both through an interface.

    Factory pattern:

    public interface IFactory{
      void VehicleType(string n);
     }
    
     public class Scooter : IFactory{
      public void VehicleType(string n){
       Console.WriteLine("Vehicle type: " + n);
      }
     }
    
     public class Bike : IFactory{
      public void VehicleType(string n) {
      Console.WriteLine("Vehicle type: " + n);
      }
     }
    
     public interface IVehicleFactory{
      IFactory GetVehicleType(string Vehicle);
     }
    
     public class ConcreteVehicleFactory : IVehicleFactory{
     public IFactory GetVehicleType(string Vehicle){
       switch (Vehicle){
        case "Scooter":
         return new Scooter();
        case "Bike":
         return new Bike();
        default:
        return new Scooter();
      }
     }
    
     class Program{
      static void Main(string[] args){
       IVehicleFactory factory = new ConcreteVehicleFactory();
       IFactory scooter = factory.GetVehicleType("Scooter");
       scooter.VehicleType("Scooter");
    
       IFactory bike = factory.GetVehicleType("Bike");
       bike.VehicleType("Bike");
    
       Console.ReadKey();
     }
    }
    

    Abstract Factory Pattern:

    interface IVehicleFactory{
     IBike GetBike();
     IScooter GetScooter();
    }
    
    class HondaFactory : IVehicleFactory{
         public IBike GetBike(){
                return new FZS();
         }
         public IScooter GetScooter(){
                return new FZscooter();
         }
     }
    class HeroFactory: IVehicleFactory{
          public IBike GetBike(){
                return new Pulsur();
         }
          public IScooter GetScooter(){
                return new PulsurScooter();
         }
    }
    
    interface IBike
        {
            string Name();
        }
    interface IScooter
        {
            string Name();
        }
    
    class FZS:IBike{
       public string Name(){
         return "FZS";
       }
    }
    class Pulsur:IBike{
       public string Name(){
         return "Pulsur";
       }
    }
    
    class FZscooter:IScooter {
      public string Name(){
         return "FZscooter";
       }
    }
    
    class PulsurScooter:IScooter{
      public string Name(){
         return "PulsurScooter";
       }
    }
    
    enum MANUFACTURERS
    {
        HONDA,
        HERO
    }
    
    class VehicleTypeCheck{
            IBike bike;
            IScooter scooter;
            IVehicleFactory factory;
            MANUFACTURERS manu;
    
            public VehicleTypeCheck(MANUFACTURERS m){
                manu = m;
            }
    
            public void CheckProducts()
            {
                switch (manu){
                    case MANUFACTURERS.HONDA:
                        factory = new HondaFactory();
                        break;
                    case MANUFACTURERS.HERO:
                        factory = new HeroFactory();
                        break;
                }
    
          Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " +      factory.GetScooter().Name());
            }
      }
    
    class Program
        {
            static void Main(string[] args)
            {
                VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
                chk.CheckProducts();
    
                chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
                chk.CheckProducts();
    
                Console.Read();
            }
        }
    

    HTML select dropdown list

        <select>
             <option value="" disabled="disabled" selected="selected">Please select a 
                  developer position</option>
              <option value="1">Beginner</option>
              <option value="2">Expert</option>
         </select>
    

    How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

    Do you have access to the command prompt ?

    Method 1 : Command Prompt

    The specifics of the Java installed on the system can be determined by executing the following command java -version

    Method 2 : Folder Structure

    In case you do not have access to command prompt then determining the folder where Java.

    32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

    64 Bit : C:\Program Files\Java\jdk1.6.0_25

    However during the installation it is possible that the user might change the installation folder.

    Method 3 : Registry

    You can also see the version installed in registry editor.

    1. Go to registry editor

    2. Edit -> Find

    3. Search for Java. You will get the registry entries for Java.

    4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

    How to test if a double is zero?

    In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

    How can a file be copied?

    from subprocess import call
    call("cp -p <file> <file>", shell=True)
    

    How to change a string into uppercase

    >>> s = 'sdsd'
    >>> s.upper()
    'SDSD'
    

    See String Methods.

    SQL Query for Selecting Multiple Records

    You're looking for the IN() clause:

    SELECT * FROM `Buses` WHERE `BusID` IN (1,2,3,5,7,9,11,44,88,etc...);
    

    The maximum recursion 100 has been exhausted before statement completion

    Specify the maxrecursion option at the end of the query:

    ...
    from EmployeeTree
    option (maxrecursion 0)
    

    That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

    How to get the list of all installed color schemes in Vim?

    If you have your vim compiled with +menu, you can follow menus with the :help of console-menu. From there, you can navigate to Edit.Color\ Scheme to get the same list as with in gvim.

    Other method is to use a cool script ScrollColors that previews the colorschemes while you scroll the schemes with j/k.

    Remove leading or trailing spaces in an entire column of data

    If you would like to use a formula, the TRIM function will do exactly what you're looking for:

    +----+------------+---------------------+
    |    |     A      |           B         |
    +----+------------+---------------------+
    | 1  | =TRIM(B1)  |  value to trim here |
    +----+------------+---------------------+
    

    So to do the whole column...
    1) Insert a column
    2) Insert TRIM function pointed at cell you are trying to correct.
    3) Copy formula down the page
    4) Copy inserted column
    5) Paste as "Values"

    Should be good to go from there...

    Using PHP with Socket.io

    UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

    C#: New line and tab characters in strings

    Use:

    sb.AppendLine();
    sb.Append("\t");
    

    for better portability. Environment.NewLine may not necessarily be \n; Windows uses \r\n, for example.

    How do I generate a random number between two variables that I have stored?

    If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

    //make sure to include the random number generators and such
    #include <random>
    //the random device that will seed the generator
    std::random_device seeder;
    //then make a mersenne twister engine
    std::mt19937 engine(seeder());
    //then the easy part... the distribution
    std::uniform_int_distribution<int> dist(min, max);
    //then just generate the integer like this:
    int compGuess = dist(engine);
    

    That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

    Hope this helps - Luke

    How to change font size in Eclipse for Java text editors?

    The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl + mousewheel zoom.

    Under menu Help ? Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

    Eclipse extension installation screen capture

    Complete the installation and restart Eclipse. Then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl + - and Ctrl + = to zoom (although you may have to unbind those keys from Eclipse first).

    Eclipse screen capture with the font size toolbar buttons circled

    To get Ctrl + mouse wheel zooming, you can use AutoHotkey with the following script:

    ; Ctrl + mouse wheel zooming in Eclipse.
    ; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
    ; Thank you for the unique window class, SWT/Eclipse.
    ;
    #IfWinActive ahk_class SWT_Window0
        ^WheelUp:: Send ^{=}
        ^WheelDown:: Send ^-
    #IfWinActive
    

    I need to learn Web Services in Java. What are the different types in it?

    Q1) Here are couple things to read or google more :

    Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

    It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

    Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

    http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

    http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

    http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

    Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

    SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

    Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

    Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

    If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

    Is there a difference between "throw" and "throw ex"?

    To give you a different perspective on this, using throw is particularly useful if you're providing an API to a client and you want to provide verbose stack trace information for your internal library. By using throw here, I'd get the stack trace in this case of the System.IO.File library for File.Delete. If I use throw ex, then that information will not be passed to my handler.

    static void Main(string[] args) {            
       Method1();            
    }
    
    static void Method1() {
        try {
            Method2();
        } catch (Exception ex) {
            Console.WriteLine("Exception in Method1");             
        }
    }
    
    static void Method2() {
        try {
            Method3();
        } catch (Exception ex) {
            Console.WriteLine("Exception in Method2");
            Console.WriteLine(ex.TargetSite);
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine(ex.GetType().ToString());
        }
    }
    
    static void Method3() {
        Method4();
    }
    
    static void Method4() {
        try {
            System.IO.File.Delete("");
        } catch (Exception ex) {
            // Displays entire stack trace into the .NET 
            // or custom library to Method2() where exception handled
            // If you want to be able to get the most verbose stack trace
            // into the internals of the library you're calling
            throw;                
            // throw ex;
            // Display the stack trace from Method4() to Method2() where exception handled
        }
    }
    

    Is there a way to specify which pytest tests to run from a file?

    If you have the same method name in two different classes and you just want to run one of them, this works:

    pytest tests.py -k 'TestClassName and test_method_name'
    

    How to add row of data to Jtable from values received from jtextfield and comboboxes

    String[] tblHead={"Item Name","Price","Qty","Discount"};
    DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
    JTable tbl=new JTable(dtm);
    String[] item={"A","B","C","D"};
    dtm.addRow(item);
    

    Here;this is the solution.

    How to add/subtract dates with JavaScript?

    All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9

    How to use the PRINT statement to track execution as stored procedure is running?

    I'm sure you can use RAISERROR ... WITH NOWAIT

    If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

    C programming: Dereferencing pointer to incomplete type error

    the case above is for a new project. I hit upon this error while editing a fork of a well established library.

    the typedef was included in the file I was editing but the struct wasn't.

    The end result being that I was attempting to edit the struct in the wrong place.

    If you run into this in a similar way look for other places where the struct is edited and try it there.

    /bin/sh: pushd: not found

    This is because pushd is a builtin function in bash. So it is not related to the PATH variable and also it is not supported by /bin/sh (which is used by default by make. You can change that by setting SHELL (although it will not work directly (test1)).

    You can instead run all the commands through bash -c "...". That will make the commands, including pushd/popd, run in a bash environment (test2).

    SHELL = /bin/bash
    
    test1:
            @echo before
            @pwd
            @pushd /tmp
            @echo in /tmp
            @pwd
            @popd
            @echo after
            @pwd
    
    test2:
            @/bin/bash -c "echo before;\
            pwd; \
            pushd /tmp; \
            echo in /tmp; \
            pwd; \
            popd; \
            echo after; \
            pwd;"
    

    When running make test1 and make test2 it gives the following:

    prompt>make test1
    before
    /download/2011/03_mar
    make: pushd: Command not found
    make: *** [test1] Error 127
    prompt>make test2
    before
    /download/2011/03_mar
    /tmp /download/2011/03_mar
    in /tmp
    /tmp
    /download/2011/03_mar
    after
    /download/2011/03_mar
    prompt>
    

    For test1, even though bash is used as a shell, each command/line in the rule is run by itself, so the pushd command is run in a different shell than the popd.

    Group By Eloquent ORM

    Laravel 5

    This is working for me (i use laravel 5.6).

    $collection = MyModel::all()->groupBy('column');
    

    If you want to convert the collection to plain php array, you can use toArray()

    $array = MyModel::all()->groupBy('column')->toArray();
    

    django templates: include and extends

    This should do the trick for you: put include tag inside of a block section.

    page1.html:

    {% extends "base1.html" %}
    
    {% block foo %}
       {% include "commondata.html" %}
    {% endblock %}
    

    page2.html:

    {% extends "base2.html" %}
    
    {% block bar %}
       {% include "commondata.html" %}
    {% endblock %}
    

    How do I revert an SVN commit?

    I tried the above, (svn merge) and you're right, it does jack. However

    svn update -r <revision> <target> [-R]
    

    seems to work, but isn't permanent (my svn is simply showing an old revision). So I had to

    mv <target> <target backup>
    svn update <target>
    mv <target backup> <target>
    svn commit -m "Reverted commit on <target>" <target>
    

    In my particular case my target is interfaces/AngelInterface.php. I made changes to the file, committed them, updated the build computer ran the phpdoc compiler and found my changes were a waste of time. svn log interfaces/AngelInterface.php shows my change as r22060 and the previous commit on that file was r22059. So I can svn update -r 22059 interfaces/AngelInterface.php and I end up with code as it was in -r22059 again. Then :-

    mv interfaces/AngelInterface.php interfaces/AngelInterface.php~
    svn update interfaces/AngelInterface.php
    mv interfaces/AngelInterface.php~ interfaces/AngelInterface.php
    svn commit -m "reverted -r22060" interfaces/AngelInterface.php
    

    Alternatively I could do the same thing on a directory, by specifying . -R in place of interfaces/AngelInterface.php in all the above.

    Find everything between two XML tags with RegEx

    You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/

    The content between the tags will be in the matched group.

    ASP.NET MVC - passing parameters to the controller

    The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:

    routes.MapRoute ("Default", "{controller}/{action}/{id}", 
                     new { controller = "Home", action = "Index", id = "" });
    

    Change it to:

    routes.MapRoute ("Default", "{controller}/{action}", 
                     new { controller = "Home", action = "Index" });
    

    What are invalid characters in XML

    In the Woodstox XML processor, invalid characters are classified by this code:

    if (c == 0) {
        throw new IOException("Invalid null character in text to output");
    }
    if (c < ' ' || (c >= 0x7F && c <= 0x9F)) {
        String msg = "Invalid white space character (0x" + Integer.toHexString(c) + ") in text to output";
        if (mXml11) {
            msg += " (can only be output using character entity)";
        }
        throw new IOException(msg);
    }
    if (c > 0x10FFFF) {
        throw new IOException("Illegal unicode character point (0x" + Integer.toHexString(c) + ") to output; max is 0x10FFFF as per RFC");
    }
    /*
     * Surrogate pair in non-quotable (not text or attribute value) content, and non-unicode encoding (ISO-8859-x,
     * Ascii)?
     */
    if (c >= SURR1_FIRST && c <= SURR2_LAST) {
        throw new IOException("Illegal surrogate pair -- can only be output via character entities, which are not allowed in this content");
    }
    throw new IOException("Invalid XML character (0x"+Integer.toHexString(c)+") in text to output");
    

    Source from here

    How to concatenate multiple column values into a single column in Panda dataframe

    If you have a list of columns you want to concatenate and maybe you'd like to use some separator, here's what you can do

    def concat_columns(df, cols_to_concat, new_col_name, sep=" "):
        df[new_col_name] = df[cols_to_concat[0]]
        for col in cols_to_concat[1:]:
            df[new_col_name] = df[new_col_name].astype(str) + sep + df[col].astype(str)
    
    

    This should be faster than apply and takes an arbitrary number of columns to concatenate.

    What are ODEX files in Android?

    The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.

    Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.

    An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.

    If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.

    To actually deodex, use small and baksmali:

    https://github.com/JesusFreke/smali/wiki/DeodexInstructions

    What jar should I include to use javax.persistence package in a hibernate based application?

    If you are developing an OSGi system I would recommend you to download the "bundlefied" version from Springsource Enterprise Bundle Repository.

    Otherwise its ok to use a regular jar-file containing the javax.persistence package

    Authenticating in PHP using LDAP through Active Directory

    PHP has libraries: http://ca.php.net/ldap

    PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

    I haven't used either, but I was going to at one point and they seemed like they should work.

    "Cannot start compilation: the output path is not specified for module..."

    While configuring idea plugin in gradle, you should define output directories as follows.

    idea{
        module{
            inheritOutputDirs = false
            outputDir = compileJava.destinationDir
            testOutputDir = compileTestJava.destinationDir
        }
    }
    

    What is a stack pointer used for in microprocessors?

    You got more preparing [for the exam] to do ;-)

    The Stack Pointer is a register which holds the address of the next available spot on the stack.

    The stack is a area in memory which is reserved to store a stack, that is a LIFO (Last In First Out) type of container, where we store the local variables and return address, allowing a simple management of the nesting of function calls in a typical program.

    See this Wikipedia article for a basic explanation of the stack management.

    What happens to a declared, uninitialized variable in C? Does it have a value?

    It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.

    As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code

    int num;
    int a = num;
    int b = num;
    

    does not guarantee that variables a and b will receive identical values. Interestingly, this is not some pedantic theoretical concept, this readily happens in practice as consequence of optimization.

    So in general, the popular answer that "it is initialized with whatever garbage was in memory" is not even remotely correct. Uninitialized variable's behavior is different from that of a variable initialized with garbage.

    Javascript close alert box

    You can use label and set its fade in and out time for e.g Hide it initially and show on click. $('#div_Message').fadeIn(500).delay(1000).fadeOut(1500);

    In C, how should I read a text file and print all strings

    The simplest way is to read a character, and print it right after reading:

    int c;
    FILE *file;
    file = fopen("test.txt", "r");
    if (file) {
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
    }
    

    c is int above, since EOF is a negative number, and a plain char may be unsigned.

    If you want to read the file in chunks, but without dynamic memory allocation, you can do:

    #define CHUNK 1024 /* read 1024 bytes at a time */
    char buf[CHUNK];
    FILE *file;
    size_t nread;
    
    file = fopen("test.txt", "r");
    if (file) {
        while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
            fwrite(buf, 1, nread, stdout);
        if (ferror(file)) {
            /* deal with error */
        }
        fclose(file);
    }
    

    The second method above is essentially how you will read a file with a dynamically allocated array:

    char *buf = malloc(chunk);
    
    if (buf == NULL) {
        /* deal with malloc() failure */
    }
    
    /* otherwise do this.  Note 'chunk' instead of 'sizeof buf' */
    while ((nread = fread(buf, 1, chunk, file)) > 0) {
        /* as above */
    }
    

    Your method of fscanf() with %s as format loses information about whitespace in the file, so it is not exactly copying a file to stdout.

    Best way to store chat messages in a database?

    There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

    Actually you can find here in Stack Overflow a link to an example schema for a chat: example

    If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

    Reading binary file and looping over each byte

    if you are looking for something speedy, here's a method I've been using that's worked for years:

    from array import array
    
    with open( path, 'rb' ) as file:
        data = array( 'B', file.read() ) # buffer the file
    
    # evaluate it's data
    for byte in data:
        v = byte # int value
        c = chr(byte)
    

    if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

    Function of Project > Clean in Eclipse

    There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.

    How to run a bash script from C++ program

    Since this is a pretty old question, and this method hasn't been added (aside from the system() call function) I guess it would be useful to include creating the shell script with the C binary itself. The shell code will be housed inside the file.c source file. Here is an example of code:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define SHELLSCRIPT "\
    #/bin/bash \n\
    echo -e \"\" \n\
    echo -e \"This is a test shell script inside C code!!\" \n\
    read -p \"press <enter> to continue\" \n\
    clear\
    "
    
    int main() {
    
    system(SHELLSCRIPT);
    return 0;
    }
    

    Basically, in a nutshell (pun intended), we are defining the script name, fleshing out the script, enclosing them in double quotes (while inserting proper escapes to ignore double quotes in the shell code), and then calling that script's name, which in this example is SHELLSCRIPT using the system() function in main().

    How do I compare two hashes?

    ... and now in module form to be applied to a variety of collection classes (Hash among them). It's not a deep inspection, but it's simple.

    # Enable "diffing" and two-way transformations between collection objects
    module Diffable
      # Calculates the changes required to transform self to the given collection.
      # @param b [Enumerable] The other collection object
      # @return [Array] The Diff: A two-element change set representing items to exclude and items to include
      def diff( b )
        a, b = to_a, b.to_a
        [a - b, b - a]
      end
    
      # Consume return value of Diffable#diff to produce a collection equal to the one used to produce the given diff.
      # @param to_drop [Enumerable] items to exclude from the target collection
      # @param to_add  [Enumerable] items to include in the target collection
      # @return [Array] New transformed collection equal to the one used to create the given change set
      def apply_diff( to_drop, to_add )
        to_a - to_drop + to_add
      end
    end
    
    if __FILE__ == $0
      # Demo: Hashes with overlapping keys and somewhat random values.
      Hash.send :include, Diffable
      rng = Random.new
      a = (:a..:q).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
      b = (:i..:z).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
      raise unless a == Hash[ b.apply_diff(*b.diff(a)) ] # change b to a
      raise unless b == Hash[ a.apply_diff(*a.diff(b)) ] # change a to b
      raise unless a == Hash[ a.apply_diff(*a.diff(a)) ] # change a to a
      raise unless b == Hash[ b.apply_diff(*b.diff(b)) ] # change b to b
    end
    

    ASP.NET Web API session or something?

    in Global.asax add

    public override void Init()
    {
        this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
        base.Init();
    }
    
    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
        System.Web.HttpContext.Current.SetSessionStateBehavior(
            SessionStateBehavior.Required);
    }
    

    give it a shot ;)

    Get the number of rows in a HTML table

    var x = document.getElementById("myTable").rows.length;
    

    Python dictionary : TypeError: unhashable type: 'list'

    This is indeed rather odd.

    If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

    This leads to two hypotheses:

    1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

    2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

    Android Studio: Drawable Folder: How to put Images for Multiple dpi?

    The standard procedures are:

    1. Choose Project > app > scr > main
    2. Right click "res", choose "New" and choose "Android resource directory" Step 2
    3. In the opened dialog, at Resource Type choose "drawable" Step 3
    4. In the list Available qualifier choose Density, then click the right arrow at the middle. Step 4
    5. Choose the Density that you like then press OK Step 5

    Conditional Formatting (IF not empty)

    This method works for Excel 2016, and calculates on cell value, so can be used on formula arrays (i.e. it will ignore blank cells that contain a formula).

    • Highlight the range.
    • Home > Conditional Formatting > New Rule > Use a Formula.
    • Enter "=LEN(#)>0" (where '#' is the upper-left-most cell in your range).
    • Alter the formatting to suit your preference.

    Note: Len(#)>0 be altered to only select cell values above a certain length.

    Note 2: '#' must not be an absolute reference (i.e. shouldn't contain '$').

    Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

    If you don't want to use

    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>(...)</version>
    </parent>
    

    as a parent POM, you may use the

    mvn org.springframework.boot:spring-boot-maven-plugin:run
    

    command instead.

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

    Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.

    For RESTeasy, you should use CorsFilter. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.

    See Also:

    How to group time by hour or by 10 minutes

    I know I am late to the show with this one, but I used this - pretty simple approach. This allows you to get the 60 minute slices without any rounding issues.

    Select 
       CONCAT( 
                Format(endtime,'yyyy-MM-dd_HH:'),  
                LEFT(Format(endtime,'mm'),1),
                '0' 
              ) as [Time-Slice]
    

    Calculate date from week number

    I like the solution provided by Henk Holterman. But to be a little more culture independent, you have to get the first day of the week for the current culture ( it's not always monday ):

    using System.Globalization;
    
    static DateTime FirstDateOfWeek(int year, int weekOfYear)
    {
      DateTime jan1 = new DateTime(year, 1, 1);
    
      int daysOffset = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;
    
      DateTime firstMonday = jan1.AddDays(daysOffset);
    
      int firstWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(jan1, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
    
      if (firstWeek <= 1)
      {
        weekOfYear -= 1;
      }
    
      return firstMonday.AddDays(weekOfYear * 7);
    }
    

    What's the difference between @Component, @Repository & @Service annotations in Spring?

    There is no difference between @Component, @Service, @Controller, @Repository. @Component is the Generic annotation to represent the component of our MVC. But there will be several components as part of our MVC application like service layer components, persistence layer components and presentation layer components. So to differentiate them Spring people have given the other three annotations also.

    • To represent persistence layer components: @Repository
    • To represent service layer components: @Service
    • To represent presentation layer components: @Controller
    • or else you can use @Component for all of them.

    What's the quickest way to multiply multiple cells by another number?

    Select Product from formula bar in your answer cell.

    Select cells you want to multiply.

    Pass array to MySQL stored routine

    I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar:

      declare pos int;           -- Keeping track of the next item's position
      declare item varchar(100); -- A single item of the input
      declare breaker int;       -- Safeguard for while loop 
    
      -- The string must end with the delimiter
      if right(inputString, 1) <> '|' then
         set inputString = concat(inputString, '|');
      end if;
    
      DROP TABLE IF EXISTS MyTemporaryTable;
      CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
      set breaker = 0;
    
      while (breaker < 2000) && (length(inputString) > 1) do
         -- Iterate looking for the delimiter, add rows to temporary table.
         set breaker = breaker + 1;
         set pos = INSTR(inputString, '|');
         set item = LEFT(inputString, pos - 1);
         set inputString = substring(inputString, pos + 1);
         insert into MyTemporaryTable values(item);
      end while;
    

    For example, input for this code could be the string Apple|Banana|Orange. MyTemporaryTable will be populated with three rows containing the strings Apple, Banana, and Orange respectively.

    I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).

    Hope this helps somebody.

    Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

    If your problem is like the following while using Google Chrome:

    [XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

    Then create a batch file by following these steps:

    Open notepad in Desktop.

    1. Just copy and paste the followings in your currently opened notepad file:

    start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

    1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
    2. Save the file as fileName.bat [Very important: .bat]
    3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

    This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

    Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

    How do I get the HTTP status code with jQuery?

    I think you should also implement the error function of the $.ajax method.

    error(XMLHttpRequest, textStatus, errorThrown)Function

    A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

    $.ajax({
        url: "http://my-ip/test/test.php",
        data: {},
        complete: function(xhr, statusText){
            alert(xhr.status); 
        },
        error: function(xhr, statusText, err){
            alert("Error:" + xhr.status); 
        }
    });
    

    Generate a random number in a certain range in MATLAB

    You can also use:

    round(mod(rand.*max,max-1))+min
    

    Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

    You can use following formulas.

    For Excel 2007 or later:

    =IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
    

    For Excel 2003:

    =IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
    

    Note, that

    • I'm using List!A:C in VLOOKUP and returns value from column ? 3
    • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

    fastest way to export blobs from table into individual files

    I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

    Original Method:

    SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
    EXEC master..xp_cmdshell @bcpCommand
    

    CLR Method:

    declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
    declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
    SELECT Master.dbo.WriteToFile(@file, @filepath, 0)
    

    C# Code for the CLR function

    using System;
    using System.Data;
    using System.Data.SqlTypes;
    using System.IO;
    using Microsoft.SqlServer.Server;
    
    namespace BlobExport
    {
        public class Functions
        {
          [SqlFunction]
          public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
          {        
            try
            {
              if (!binary.IsNull && !path.IsNull && !append.IsNull)
              {         
                var dir = Path.GetDirectoryName(path.Value);           
                if (!Directory.Exists(dir))              
                  Directory.CreateDirectory(dir);            
                  using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
                {
                    byte[] byteArr = binary.Value;
                    for (int i = 0; i < byteArr.Length; i++)
                    {
                        fs.WriteByte(byteArr[i]);
                    };
                }
                return "SUCCESS";
              }
              else
                 "NULL INPUT";
            }
            catch (Exception ex)
            {          
              return ex.Message;
            }
          }
        }
    }
    

    How to parse an RSS feed using JavaScript?

    If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/

    The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/

    It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:

    fetch(websiteUrl).then((res) => {
      res.text().then((htmlTxt) => {
        var domParser = new DOMParser()
        let doc = domParser.parseFromString(htmlTxt, 'text/html')
        var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
      })
    }).catch(() => console.error('Error in fetching the website'))
    

    How many characters can you store with 1 byte?

    2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).

       |----------------------------------------------------------|
       |                                                          |
       | Type    | Storage |  Minimum Value    | Maximum Value    |
       |         | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
       |         |         |                   |                  |
       |---------|---------|-------------------|------------------|
       |         |         |                   |                  |
       |         |         |                   |                  |
       | TINYINT |  1      |      -128 - 0     |  127 - 255       |
       |         |         |                   |                  |
       |----------------------------------------------------------|
    

    How many times a substring occurs

    Depending what you really mean, I propose the following solutions:

    1. You mean a list of space separated sub-strings and want to know what is the sub-string position number among all sub-strings:

      s = 'sub1 sub2 sub3'
      s.split().index('sub2')
      >>> 1
      
    2. You mean the char-position of the sub-string in the string:

      s.find('sub2')
      >>> 5
      
    3. You mean the (non-overlapping) counts of appearance of a su-bstring:

      s.count('sub2')
      >>> 1
      s.count('sub')
      >>> 3
      

    How to send HTML-formatted email?

    Best way to send html formatted Email

    This code will be in "Customer.htm"

        <table>
        <tr>
            <td>
                Dealer's Company Name
            </td>
            <td>
                :
            </td>
            <td>
                #DealerCompanyName#
            </td>
        </tr>
    </table>
    

    Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.

    string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
    

    Replace Particular string to your custom value.

    Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
    

    call SendEmail(string Body) Function and do procedure to send email.

     public static void SendEmail(string Body)
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(Session["Email"].Tostring());
                message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
                message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
                message.IsBodyHtml = true;
                message.Body = Body;
    
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.UseDefaultCredentials = true;
    
                smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
                smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
                smtpClient.EnableSsl = true;
                smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
                smtpClient.Send(message);
            }
    

    Dump a NumPy array into a csv file

    tofile is a convenient function to do this:

    import numpy as np
    a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
    a.tofile('foo.csv',sep=',',format='%10.5f')
    

    The man page has some useful notes:

    This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.

    Note. This function does not produce multi-line csv files, it saves everything to one line.

    How to generate XML file dynamically using PHP?

    Hope this code may help you out. Easy and simple solution

    $dom = new DOMDocument();
    $dom->encoding = 'utf-8';
    $dom->xmlVersion = '1.0';
    $dom->formatOutput = true;
    $xml_file_name = './movies_list.xml'; //You can give your path to save file.
    $root = $dom->createElement('Movies');
        $movie_node = $dom->createElement('movie');
        $attr_movie_id = new DOMAttr('movie_id', '5467');
        $movie_node->setAttributeNode($attr_movie_id);
            
            $child_node_title = $dom->createElement('Title', 'The Campaign');
            $movie_node->appendChild($child_node_title);
            
            $child_node_year = $dom->createElement('Year', 2012);
            $movie_node->appendChild($child_node_year);
            
            $child_node_genre = $dom->createElement('Genre', 'The Campaign');
            $movie_node->appendChild($child_node_genre);
            
            $child_node_ratings = $dom->createElement('Ratings', 6.2);
            $movie_node->appendChild($child_node_ratings);
        $root->appendChild($movie_node);
    $dom->appendChild($root);
    $dom->save($xml_file_name);
    

    For more information visit this to get information in details: https://www.guru99.com/php-and-xml.html

    Convert list of ASCII codes to string (byte array) in Python

    This is reviving an old question, but in Python 3, you can just use bytes directly:

    >>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
    b'\x11\x18y\x01\x0c\xde"L'
    

    How to use Servlets and Ajax?

    Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

    Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

    Kickoff example returning String as plain text

    Create a /some.jsp like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet" to "${pageContext.request.contextPath}/someservlet"; it's merely omitted from the code snippets for brevity):

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>SO question 4112686</title>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
                $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                    $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                        $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                    });
                });
            </script>
        </head>
        <body>
            <button id="somebutton">press here</button>
            <div id="somediv"></div>
        </body>
    </html>
    

    Create a servlet with a doGet() method which look like this:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = "some text";
    
        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
        response.getWriter().write(text);       // Write response body.
    }
    

    Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

    package com.example;
    
    @WebServlet("/someservlet/*")
    public class SomeServlet extends HttpServlet {
        // ...
    }
    

    Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

    <servlet>
        <servlet-name>someservlet</servlet-name>
        <servlet-class>com.example.SomeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>someservlet</servlet-name>
        <url-pattern>/someservlet/*</url-pattern>
    </servlet-mapping>
    

    Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

    Returning List<String> as JSON

    With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

    Here's an example which displays List<String> as <ul><li>. The servlet:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<String> list = new ArrayList<>();
        list.add("item1");
        list.add("item2");
        list.add("item3");
        String json = new Gson().toJson(list);
    
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    The JS code:

    $(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
        $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
            var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
            $.each(responseJson, function(index, item) { // Iterate over the JSON array.
                $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
            });
        });
    });
    

    Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse() afterwards, which is thus totally unnecessary if you set the content type right in first place.

    Returning Map<String, String> as JSON

    Here's another example which displays Map<String, String> as <option>:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> options = new LinkedHashMap<>();
        options.put("value1", "label1");
        options.put("value2", "label2");
        options.put("value3", "label3");
        String json = new Gson().toJson(options);
    
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    And the JSP:

    $(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
        $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
            var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
            $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
            $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
                $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
            });
        });
    });
    

    with

    <select id="someselect"></select>
    

    Returning List<Entity> as JSON

    Here's an example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = someProductService.list();
        String json = new Gson().toJson(products);
    
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    The JS code:

    $(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
        $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
            var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
            $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
                $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                    .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                    .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                    .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
            });
        });
    });
    

    Returning List<Entity> as XML

    Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = someProductService.list();
    
        request.setAttribute("products", products);
        request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
    }
    

    The JSP code (note: if you put the <table> in a <jsp:include>, it may be reusable elsewhere in a non-ajax response):

    <?xml version="1.0" encoding="UTF-8"?>
    <%@page contentType="application/xml" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <data>
        <table>
            <c:forEach items="${products}" var="product">
                <tr>
                    <td>${product.id}</td>
                    <td><c:out value="${product.name}" /></td>
                    <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
                </tr>
            </c:forEach>
        </table>
    </data>
    

    The JS code:

    $(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
        $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
            $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
        });
    });
    

    You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

    Ajaxifying an existing form

    You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

    <form id="someform" action="someservlet" method="post">
        <input type="text" name="foo" />
        <input type="text" name="bar" />
        <input type="text" name="baz" />
        <input type="submit" name="submit" value="Submit" />
    </form>
    

    You can progressively enhance it with ajax as below:

    $(document).on("submit", "#someform", function(event) {
        var $form = $(this);
    
        $.post($form.attr("action"), $form.serialize(), function(response) {
            // ...
        });
    
        event.preventDefault(); // Important! Prevents submitting the form.
    });
    

    You can in the servlet distinguish between normal requests and ajax requests as below:

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String foo = request.getParameter("foo");
        String bar = request.getParameter("bar");
        String baz = request.getParameter("baz");
    
        boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    
        // ...
    
        if (ajax) {
            // Handle ajax (JSON or XML) response.
        } else {
            // Handle regular (JSP) response.
        }
    }
    

    The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

    Manually sending request parameters to servlet

    If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param() to easily convert a JSON object to an URL-encoded query string.

    var params = {
        foo: "fooValue",
        bar: "barValue",
        baz: "bazValue"
    };
    
    $.post("someservlet", $.param(params), function(response) {
        // ...
    });
    

    The same doPost() method as shown here above can be reused. Do note that above syntax also works with $.get() in jQuery and doGet() in servlet.

    Manually sending JSON object to servlet

    If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify() (not part of jQuery) and instruct jQuery to set request content type to application/json instead of (default) application/x-www-form-urlencoded. This can't be done via $.post() convenience function, but needs to be done via $.ajax() as below.

    var data = {
        foo: "fooValue",
        bar: "barValue",
        baz: "bazValue"
    };
    
    $.ajax({
        type: "POST",
        url: "someservlet",
        contentType: "application/json", // NOT dataType!
        data: JSON.stringify(data),
        success: function(response) {
            // ...
        }
    });
    

    Do note that a lot of starters mix contentType with dataType. The contentType represents the type of the request body. The dataType represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type header.

    Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter() the usual way. Namely, servlets don't support application/json formatted requests, but only application/x-www-form-urlencoded or multipart/form-data formatted requests. Gson also supports parsing a JSON string into a JSON object.

    JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
    String foo = data.get("foo").getAsString();
    String bar = data.get("bar").getAsString();
    String baz = data.get("baz").getAsString();
    // ...
    

    Do note that this all is more clumsy than just using $.param(). Normally, you want to use JSON.stringify() only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

    Sending a redirect from servlet

    Important to realize and understand is that any sendRedirect() and forward() call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

    document.open();
    document.write(responseText);
    document.close();
    

    Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

    String redirectURL = "http://example.com";
    
    Map<String, String> data = new HashMap<>();
    data.put("redirect", redirectURL);
    String json = new Gson().toJson(data);
    
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
    
    function(responseJson) {
        if (responseJson.redirect) {
            window.location = responseJson.redirect;
            return;
        }
    
        // ...
    }
    

    See also:

    Jenkins / Hudson environment variables

    On my newer EC2 instance, simply adding the new value to the Jenkins user's .profile's PATH and then restarting tomcat worked for me.

    On an older instance where the config is different, using #2 from Sagar's answer was the only thing that worked (i.e. .profile, .bash* didn't work).

    How to create multidimensional array

    Create uninitialized multidimensional array:

    function MultiArray(a) {
      if (a.length < 1) throw "Invalid array dimension";
      if (a.length == 1) return Array(a[0]);
      return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
    }
    

    Create initialized multidimensional array:

    function MultiArrayInit(a, init) {
      if (a.length < 1) throw "Invalid array dimension";
      if (a.length == 1) return Array(a[0]).fill(init);
      return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
    }
    

    Usage:

    MultiArray([3,4,5]);  // -> Creates an array of [3][4][5] of empty cells
    
    MultiArrayInit([3,4,5], 1);  // -> Creates an array of [3][4][5] of 1s
    

    convert base64 to image in javascript/jquery

    var src = "data:image/jpeg;base64,";
    src += item_image;
    var newImage = document.createElement('img');
    newImage.src = src;
    newImage.width = newImage.height = "80";
    document.querySelector('#imageContainer').innerHTML = newImage.outerHTML;//where to insert your image
    

    MySql Query Replace NULL with Empty String in Select

    Try this, this should also get rid of those empty lines also:

    SELECT prereq FROM test WHERE prereq IS NOT NULL;