Programs & Examples On #Partialfunction

On localhost, how do I pick a free port number?

Do not bind to a specific port. Instead, bind to port 0:

sock.bind(('', 0))

The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.

How to get the Mongo database specified in connection string in C#

In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:

var connectionString = @"mongodb://usr:[email protected],srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");

Trying to detect browser close event

Following script will give message on Chrome and IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome
enter image description here

IE
enter image description here

on Firefox you will get generic message

enter image description here

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

What is git tag, How to create tags & How to checkout git remote tag(s)

This is bit out of context but in case you are here because you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

echo key and value of an array without and with loop

How to echo key and value of an array without and with loop

$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];

Timing Delays in VBA

I used the answer of Steve Mallory, but I am affraid the timer never or at least sometimes does not go to 86400 nor 0 (zero) sharp (MS Access 2013). So I modified the code. I changed the midnight condition to "If Timer >= 86399 Then" and added the break of the loop "Exit Do" as follows:

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer >= 86399
            ' Crossing midnight
            ' PauseTime = PauseTime - Elapsed
            ' Start = 0
            ' Elapsed = 0
            Exit Do
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

z-index not working with position absolute

The second div is position: static (the default) so the z-index does not apply to it.

You need to position (set the position property to anything other than static, you probably want relative in this case) anything you want to give a z-index to.

Get all Attributes from a HTML element with Javascript/jQuery

This approach works well if you need to get all the attributes with name and value in objects returned in an array.

Example output:

[
    {
        name: 'message',
        value: 'test2'
    }
    ...
]

_x000D_
_x000D_
function getElementAttrs(el) {_x000D_
  return [].slice.call(el.attributes).map((attr) => {_x000D_
    return {_x000D_
      name: attr.name,_x000D_
      value: attr.value_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
var allAttrs = getElementAttrs(document.querySelector('span'));_x000D_
console.log(allAttrs);
_x000D_
<span name="test" message="test2"></span>
_x000D_
_x000D_
_x000D_

If you want only an array of attribute names for that element, you can just map the results:

var onlyAttrNames = allAttrs.map(attr => attr.name);
console.log(onlyAttrNames); // ["name", "message"]

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

-XX:MaxPermSize=size

Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

-XX:PermSize=size

Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize option.

How to test an Internet connection with bash?

This bash script continuously check for Internet and make a beep sound when the Internet is available.

#!/bin/bash
play -n synth 0.3 sine 800 vol 0.75
while :
do
pingtime=$(ping -w 1 8.8.8.8 | grep ttl)
if [ "$pingtime" = "" ] 
then 
   pingtimetwo=$(ping -w 1 www.google.com | grep ttl) 
   if [ "$pingtimetwo" = "" ] 
   then 
       clear ; echo 'Offline'
   else
       clear ; echo 'Online' ; play -n synth 0.3 sine 800 vol 0.75
   fi 
else
    clear ; echo 'Online' ; play -n synth 0.3 sine 800 vol 0.75
fi
sleep 1
done

Javascript change Div style

Better change the class of the element (.regular is black, .alert is red):

function abc(){
  var myDiv = document.getElementById("test");
  if (myDiv.className == 'alert') {
    myDiv.className = 'regular';
  } else {
    myDiv.className = 'alert';
  }
}

add item to dropdown list in html using javascript

For higher performance, I recommend this:

var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');

//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
    //var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
    option.text = option.value = i;
    options.push(option.outerHTML);
}

select.insertAdjacentHTML('beforeEnd', options.join('\n'));

This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.

Optional for generating the string by hand:

function escapeHTML(str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:

var docfrag = document.createDocumentFragment();

for (var i = 1900; i < 2012; ++i)
{
     docfrag.appendChild(new Option(i, i));
}

var select = document.getElementById("year");
select.appendChild(docfrag);

How to randomize (shuffle) a JavaScript array?

Ronald Fisher and Frank Yates shuffle

ES2015 (ES6) release

Array.prototype.shuffle2 = function () {
    this.forEach(
        function (v, i, a) {
            let j = Math.floor(Math.random() * (i + 1));
            [a[i], a[j]] = [a[j], a[i]];
        }
    );
    return this;
}

Jet optimized ES2015 (ES6) release

Array.prototype.shuffle3 = function () {
    var m = this.length;
    while (m) {
        let i = Math.floor(Math.random() * m--);
        [this[m], this[i]] = [this[i], this[m]];
    }
    return this;
}

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

How to check if a key exists in Json Object and get its value

Use:

if (containerObject.has("video")) {
    //get value of video
}

Export and Import all MySQL databases at one time

I wrote this comment already more than 4 years ago and decided now to make it to an answer.

The script from jruzafa can be a bit simplified:

#!/bin/bash

USER="zend"
PASSWORD=""
ExcludeDatabases="Database|information_schema|performance_schema|mysql"
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | egrep -v $ExcludeDatabases`

for db in $databases; do
    echo "Dumping database: $db"
    mysqldump -u $USER -p$PASSWORD --databases $db > `date +%Y%m%d`.$db.sql
    # gzip $OUTPUT`date +%Y%m%d`.$db.sql
done

Note:

  1. The excluded databases - prevalently the system tables - are provided in the variable ExcludeDatabases
  2. Please be aware that the password is provided in the command line. This is considered as insecure. Study this question.

How to extract string following a pattern with grep, regex or perl

Oops, the sed command has to precede the tidy command of course:

echo "$htmlstr" | 
sed '/type="global"/d' |
tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
xmlstarlet sel -N x="http://www.w3.org/1999/xhtml" -T -t -m "//x:table" -v '@name' -n

How to position text over an image in css

as Harry Joy points out, set the image as the div's background and then, if you only have one line of text you can set the line-height of the text to be the same as the div height and this will place your text in the center of the div.

If you have more than one line you'll want to set the display to be table-cell and vertical-alignment to middle.

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

Python Selenium Chrome Webdriver

Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.

Step by step:
1. pip install chromedriver-binary
2. import the package

from selenium import webdriver
import chromedriver_binary  # Adds chromedriver binary to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")

Reference: https://pypi.org/project/chromedriver-binary/

Beautiful way to remove GET-variables with PHP?

In my opinion, the best way would be this:

<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>

It checks if there is an 'i' GET parameter, and removes it if there is.

Platform.runLater and Task in JavaFX

  • Platform.runLater: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handled by the GUI thread as soon as possible.
  • Task implements the Worker interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.

If you are familiar with Swing, the former is equivalent to SwingUtilities.invokeLater and the latter to the concept of SwingWorker.

The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.

"int cannot be dereferenced" in Java

Change

id.equals(list[pos].getItemNumber())

to

id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

Radio/checkbox alignment in HTML/CSS

This is a bit of a hack but this CSS seems to get it working very nicely in all browsers the same as using tables (apart from chrome)

input[type=radio] { vertical-align: middle; margin: 0; *margin-top: -2px; }
label { vertical-align: middle; }
@media screen and (-webkit-min-device-pixel-ratio:0) {
 input[type=radio] { margin-top: -2px; }
}

Make sure you use labels with your radios for it to work. i.e.

<option> <label>My Radio</label>

.NET console application as Windows service

I hear your point at wanting one assembly to stop repeated code but, It would be simplest and reduce code repetition and make it easier to reuse your code in other ways in future if...... you to break it into 3 assemblies.

  1. One library assembly that does all the work. Then have two very very slim/simple projects:
  2. one which is the commandline
  3. one which is the windows service.

AttributeError: Module Pip has no attribute 'main'

If python -m pip install --upgrade pip==9.0.3 doesn't work, and you're using Windows,

  1. Navigate to this directory and move the pip folders elsewhere.

enter image description here

  1. Close your IDE if you have it open.

  2. Press 'Repair' on Python 3.

enter image description here

  1. Your IDE should cease to detect pip packages and prompt you to install them. Install and keep the last stable pip version by blocking automatic updates. enter image description here

How to Detect Browser Window /Tab Close Event?

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

_x000D_
_x000D_
<script>_x000D_
    function endSession() {_x000D_
         // Browser or Broswer tab is closed_x000D_
         // Write code here_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

System.Runtime.InteropServices.COMException (0x800A03EC)

Try this as it worked for me...

  1. Go to "Start" -> "Run" and enter "dcomcnfg"
  2. This will bring up the component services window, expand out "Console Root" -> "Computers" -> "DCOM Config"
  3. Find "Microsoft Excel Application" in the list of components.
  4. Right click on the entry and select "Properties"
  5. Go to the "Identity" tab on the properties dialog.
  6. Select "The interactive user."

courtesy of Last paragraph mentioned in here

How can I properly use a PDO object for a parameterized SELECT query

You can use the bindParam or bindValue methods to help prepare your statement. It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.

Check the clear, easy to read example below:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetchAll(PDO::FETCH_ASSOC);
    //$check will now hold an array of returned rows. 
    //let's say we need the second result, i.e. index of 1
    $row_id = $check[1]['id']; 
    // do something
}

Tomcat: LifecycleException when deploying

For me the problem was caused by checking the project into an other directory from Git. Choosing the same name as the war file solved the problem.

Microsoft Web API: How do you do a Server.MapPath?

You can try like:

var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)

Recursively list all files in a directory including files in symlink directories

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

ls -LR

You can also accomplish this with

find -follow

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

find -L

as -follow has been deprecated.

Git credential helper - update password

On my first attempt to Git fetch after my password change, I was told that my username/password combination was invalid. This was correct as git-credential helper had cached my old values.

However, I attempted another git fetch after restarting my terminal/command-prompt and this time the credential helper prompted me to enter in my GitHub username and password.

I suspect the initial failed Git fetch request in combination with restarting my terminal/command-prompt resolved this for me.

I hope this answer helps anybody else in a similar position in the future!

How to list all users in a Linux group?

Zed's implementation should probably be expanded to work on some of the other major UNIX.

Someone have access to Solaris or HP-UX hardware?; did not test those cases.

#!/usr/bin/perl
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Date:         12/30/2013
# Author:       William H. McCloskey, Jr.
# Changes:      Added logic to detect host type & tailor subset of getent (OSX)
# Attribution:
#   The logic for this script was directly lifted from Zed Pobre's work.
#     See below for Copyright notice.
#   The idea to use dscl to emulate a subset of the now defunct getent on OSX
#     came from
#       http://zzamboni.org/\
#         brt/2008/01/21/how-to-emulate-unix-getent-with-macosxs-dscl/
#     with an example implementation lifted from
#       https://github.com/petere/getent-osx/blob/master/getent
#
# Copyright © 2010-2013 by Zed Pobre ([email protected] or [email protected])
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#

use strict; use warnings;

$ENV{"PATH"} = "/usr/bin:/bin";

# Only run on supported $os:
my $os;
($os)=(`uname -a` =~ /^([\w-]+)/);
unless ($os =~ /(HU-UX|SunOS|Linux|Darwin)/)
    {die "\$getent or equiv. does not exist:  Cannot run on $os\n";}

my $wantedgroup = shift;

my %groupmembers;

my @users;

# Acquire the list of @users based on what is available on this OS:
if ($os =~ /(SunOS|Linux|HP-UX)/) {
    #HP-UX & Solaris assumed to be like Linux; they have not been tested.
    my $usertext = `getent passwd`;
    @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
};
if ($os =~ /Darwin/) {
    @users = `dscl . -ls /Users`;
    chop @users;
}

# Now just do what Zed did - thanks Zed.
foreach my $userid (@users)
{
    my $usergrouptext = `id -Gn $userid`;
    my @grouplist = split(' ',$usergrouptext);

    foreach my $group (@grouplist)
    {
        $groupmembers{$group}->{$userid} = 1;
    }
}

if($wantedgroup)
{
    print_group_members($wantedgroup);
}
else
{
    foreach my $group (sort keys %groupmembers)
    {
        print "Group ",$group," has the following members:\n";
        print_group_members($group);
        print "\n";
    }
}

sub print_group_members
{
    my ($group) = @_;
    return unless $group;

    foreach my $member (sort keys %{$groupmembers{$group}})
    {
        print $member,"\n";
    }
}

If there is a better way to share this suggestion, please let me know; I considered many ways, and this is what I came up with.

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

What does "atomic" mean in programming?

Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.

"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.

When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.

When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."

Read/Write String from/to a File in Android

public static void writeStringAsFile(final String fileContents, String fileName) {
    Context context = App.instance.getApplicationContext();
    try {
        FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
        out.write(fileContents);
        out.close();
    } catch (IOException e) {
        Logger.logError(TAG, e);
    }
}

public static String readFileAsString(String fileName) {
    Context context = App.instance.getApplicationContext();
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    BufferedReader in = null;

    try {
        in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
        while ((line = in.readLine()) != null) stringBuilder.append(line);

    } catch (FileNotFoundException e) {
        Logger.logError(TAG, e);
    } catch (IOException e) {
        Logger.logError(TAG, e);
    } 

    return stringBuilder.toString();
}

Visual Studio 2017: Display method references

For anyone who is looking to enable this on the Mac version, it is not available. Developers of Visual Studio stated they will include in their roadmap.

Gradle failed to resolve library in Android Studio

Some time you may just need to add maven { url "https://jitpack.io" } in your allprojects block in project level build.gradle file.

Example:

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

Spring JPA and persistence.xml

I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.

I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.

I don't get the magic in your save() method either. How is the data saved?

In production I configure spring like this:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />

along with the reference in web.xml

For unit testing I do this:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
    p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
    p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

.tr-hover
{  
  background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
    $(this).addClass('tr-hover');
},function()
{
    $(this).removeClass('tr-hover');
});

Catching access violation exceptions?

A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

Build query string for System.Net.HttpClient get

Since I have to reuse this few time, I came up with this class that simply help to abstract how the query string is composed.

public class UriBuilderExt
{
    private NameValueCollection collection;
    private UriBuilder builder;

    public UriBuilderExt(string uri)
    {
        builder = new UriBuilder(uri);
        collection = System.Web.HttpUtility.ParseQueryString(string.Empty);
    }

    public void AddParameter(string key, string value) {
        collection.Add(key, value);
    }

    public Uri Uri{
        get
        {
            builder.Query = collection.ToString();
            return builder.Uri;
        }
    }

}

The use will be simplify to something like this:

var builder = new UriBuilderExt("http://example.com/");
builder.AddParameter("foo", "bar<>&-baz");
builder.AddParameter("bar", "second");
var uri = builder.Uri;

that will return the uri: http://example.com/?foo=bar%3c%3e%26-baz&bar=second

Apache - MySQL Service detected with wrong path. / Ports already in use

Ok so i found out the problem :)

ctrl+alt+delete to start task manager, once you get to task manager go to services. find MySQL and right click on it. Then click stop process. That worked for me and i hope it works for you :D

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

std::string formatting like sprintf

One solution I've favoured is to do this with sprintf directly into the std::string buffer, after making said buffer big enough:

#include <string>
#include <iostream>

using namespace std;

string l_output;
l_output.resize(100);

for (int i = 0; i < 1000; ++i)
{       
    memset (&l_output[0], 0, 100);
    sprintf (&l_output[0], "\r%i\0", i);

    cout << l_output;
    cout.flush();
}

So, create the std::string, resize it, access its buffer directly...

Remove Trailing Spaces and Update in Columns in SQL Server

Try SELECT LTRIM(RTRIM('Amit Tech Corp '))

LTRIM - removes any leading spaces from left side of string

RTRIM - removes any spaces from right

Ex:

update table set CompanyName = LTRIM(RTRIM(CompanyName))

How to replace substrings in windows batch file

If you have Ruby for Windows,

C:\>more file
bath Abath Bbath XYZbathABC

C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC

php & mysql query not echoing in html with tags?

You need to append your variables to the echoed string. For example:

echo 'This is a string '.$PHPvariable.' and this is more string'; 

Android Paint: .measureText() vs .getTextBounds()

You can do what I did to inspect such problem:

Study Android source code, Paint.java source, see both measureText and getTextBounds methods. You'd learn that measureText calls native_measureText, and getTextBounds calls nativeGetStringBounds, which are native methods implemented in C++.

So you'd continue to study Paint.cpp, which implements both.

native_measureText -> SkPaintGlue::measureText_CII

nativeGetStringBounds -> SkPaintGlue::getStringBounds

Now your study checks where these methods differ. After some param checks, both call function SkPaint::measureText in Skia Lib (part of Android), but they both call different overloaded form.

Digging further into Skia, I see that both calls result into same computation in same function, only return result differently.

To answer your question: Both your calls do same computation. Possible difference of result lies in fact that getTextBounds returns bounds as integer, while measureText returns float value.

So what you get is rounding error during conversion of float to int, and this happens in Paint.cpp in SkPaintGlue::doTextBounds in call to function SkRect::roundOut.

The difference between computed width of those two calls may be maximally 1.

EDIT 4 Oct 2011

What may be better than visualization. I took the effort, for own exploring, and for deserving bounty :)

enter image description here

This is font size 60, in red is bounds rectangle, in purple is result of measureText.

It's seen that bounds left part starts some pixels from left, and value of measureText is incremented by this value on both left and right. This is something called Glyph's AdvanceX value. (I've discovered this in Skia sources in SkPaint.cpp)

So the outcome of the test is that measureText adds some advance value to the text on both sides, while getTextBounds computes minimal bounds where given text will fit.

Hope this result is useful to you.

Testing code:

  protected void onDraw(Canvas canvas){
     final String s = "Hello. I'm some text!";

     Paint p = new Paint();
     Rect bounds = new Rect();
     p.setTextSize(60);

     p.getTextBounds(s, 0, s.length(), bounds);
     float mt = p.measureText(s);
     int bw = bounds.width();

     Log.i("LCG", String.format(
          "measureText %f, getTextBounds %d (%s)",
          mt,
          bw, bounds.toShortString())
      );
     bounds.offset(0, -bounds.top);
     p.setStyle(Style.STROKE);
     canvas.drawColor(0xff000080);
     p.setColor(0xffff0000);
     canvas.drawRect(bounds, p);
     p.setColor(0xff00ff00);
     canvas.drawText(s, 0, bounds.bottom, p);
  }

how to set background image in submit button?

Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.

A tutorial on the subject.

jQuery Combobox/select autocomplete?

This works great for me and I'm doing more, writing less with jQuery's example modified.

I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

$(function() {
   var mySource = [];
   $("#mySelect").children("option").map(function() {
      mySource.push($(this).text());
   });

   $("#myInput").autocomplete({
      source: mySource,
      minLength: 3
   });
}

There is already an object named in the database

Delete rows from dbo_MigrationHistory table or delete the table and run

update-database -verbose

It will run all the migrations in your project one by one

Codeigniter how to create PDF

TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.

Step 1

To Download TCPDF Click Here.

Step 2

Unzip the above download inside application/libraries/tcpdf.

Step 3

Create a new file inside application/libraries/Pdf.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */

Step 4

Create Controller file inside application/controllers/pdfexample.php.

 <?php
    class pdfexample extends CI_Controller{ 
    function __construct()
    { parent::__construct(); } function index() {
    $this->load->library('Pdf');
    $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetTitle('Pdf Example');
    $pdf->SetHeaderMargin(30);
    $pdf->SetTopMargin(20);
    $pdf->setFooterMargin(20);
    $pdf->SetAutoPageBreak(true);
    $pdf->SetAuthor('Author');
    $pdf->SetDisplayMode('real', 'default');
    $pdf->Write(5, 'CodeIgniter TCPDF Integration');
    $pdf->Output('pdfexample.pdf', 'I'); }
    }
    ?>

It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I changed the location of the app and copied it to a short path. You can do that by just copying your project and pasting it to a new Short Location. And, it worked for me.

For example,

Old_path: c/:user/android_studio_project/your_app
New_path: c/:your_app

How to unapply a migration in ASP.NET Core with EF Core

To unapply a specific migration(s):

dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName

To unapply all migrations:

dotnet ef database update 0
or
PM> Update-Database -Migration 0

To remove last migration:

dotnet ef migrations remove
or
PM> Remove-Migration

To remove all migrations:

just remove Migrations folder.

To remove last few migrations (not all):

There is no a command to remove a bunch of migrations and we can't just remove these few migrations and their *.designer.cs files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration above).

To unapply and remove last migration:

dotnet ef migrations remove --force
or
PM> Remove-Migration -Force

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

$hash = @{ a = 1; b = 2; c = 3}

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

$(document).ready shorthand

The correct shorthand is this:

$(function() {
    // this behaves as if within document.ready
});

The code you posted…

(function($){

//some code

})(jQuery);

…creates an anonymous function and executes it immediately with jQuery being passed in as the arg $. All it effectively does is take the code inside the function and execute it like normal, since $ is already an alias for jQuery. :D

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

AppFabric installation failed because installer MSI returned with error code : 1603

Looks like I got all the possible issues with that installation.

Troubleshooting: look at actual log file (in the log provided by the installer look for LOGFILE=...):

Process.Start: C:\Windows\system32\msiexec.exe /quiet /norestart /i "c:\2964b29c3cd7dcb37c9e\Packages\AppFabric-1.1-for-Windows-Server-64.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheService,CacheClient,CacheAdmin,Setup /l*vx "c:\Temp\AppServerSetup1_1(2014-07-09 11-58-09).log" LOGFILE="c:\Temp\AppServerSetup1_1_CustomActions(2014-07-09 11-58-09).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US

After you located the actual log file, check for errors. I had to:

  1. Fails to create AS_Observer:
    • Exec: c:\Windows\system32\net.exe localgroup AS_Observers /delete
  2. Fails to set ACLs on config folder:
    • Exec: md C:\Windows\SysWOW64\inetsrv\config
  3. COM not registered:
    • Install activation service feature for .NET 3.5 (both HTTP and non-HTTP) and enable HTTP activation for .NET 4.5

done. Hope that helps.

Make xargs handle filenames that contain spaces

On macOS 10.12.x (Sierra), if you have spaces in file names or subdirectories, you can use the following:

find . -name '*.swift' -exec echo '"{}"' \; |xargs wc -l

How does ApplicationContextAware work in Spring?

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.

So, it seemed to be invoked when Spring container has started, if you want to do something at that time.

It just has one method to set the context, so you will get the context and do something to sth now already in context I think.

How do I style a <select> dropdown with only CSS?

select  {
    outline: 0;
    overflow: hidden;
    height: 30px;
    background: #2c343c;
    color: #747a80;
    border: #2c343c;
    padding: 5px 3px 5px 10px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 10px;
}

select option {border: 1px solid #000; background: #010;}

Parsing command-line arguments in C

There are these tools in the GNU C Library, which includes GetOpt.

If you are using Qt and like the GetOpt interface, froglogic has published a nice interface here.

How to alter a column and change the default value?

In case the above does not work for you (i.e.: you are working with new SQL or Azure) try the following:

1) drop existing column constraint (if any):

ALTER TABLE [table_name] DROP CONSTRAINT DF_my_constraint

2) create a new one:

ALTER TABLE [table_name] ADD CONSTRAINT DF_my_constraint  DEFAULT getdate() FOR column_name;

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

Understanding typedefs for function pointers in C

int add(int a, int b)
{
  return (a+b);
}
int minus(int a, int b)
{
  return (a-b);
}

typedef int (*math_func)(int, int); //declaration of function pointer

int main()
{
  math_func addition = add;  //typedef assigns a new variable i.e. "addition" to original function "add"
  math_func substract = minus; //typedef assigns a new variable i.e. "substract" to original function "minus"

  int c = addition(11, 11);   //calling function via new variable
  printf("%d\n",c);
  c = substract(11, 5);   //calling function via new variable
  printf("%d",c);
  return 0;
}

Output of this is :

22

6

Note that, same math_func definer has been used for the declaring both the function.

Same approach of typedef may be used for extern struct.(using sturuct in other file.)

How can I get a collection of keys in a JavaScript dictionary?

One option is using Object.keys():

Object.keys(driversCounter)

It works fine for modern browsers (however, Internet Explorer supports it starting from version 9 only).

To add compatible support you can copy the code snippet provided in MDN.

SQL SERVER DATETIME FORMAT

The default date format depends on the language setting for the database server. You can also change it per session, like:

set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM

How to set the height and the width of a textfield in Java?

You should not play with the height. Let the text field determine the height based on the font used.

If you want to control the width of the text field then you can use

textField.setColumns(...);

to let the text field determine the preferred width.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

See the Swing tutorial on Layout Managers for more information.

Convert double/float to string

The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

How to add 'libs' folder in Android Studio?

You can create lib folder inside app you press right click and select directory you named as libs its will be worked

Fixing broken UTF-8 encoding

I found a solution after days of search. My comment is going to be buried but anyway...

  1. I get the corrupted data with php.

  2. I don't use set names UTF8

  3. I use utf8_decode() on my data

  4. I update my database with my new decoded data, still not using set names UTF8

and voilà :)

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

How to normalize a histogram in MATLAB?

For some Distributions, Cauchy I think, I have found that trapz will overestimate the area, and so the pdf will change depending on the number of bins you select. In which case I do

[N,h]=hist(q_f./theta,30000); % there Is a large range but most of the bins will be empty
plot(h,N/(sum(N)*mean(diff(h))),'+r')

Parsing JSON string in Java

Firstly there is an extra } after every array object.

Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");

Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).

I am using org.codehaus.jettison.json.

Best way to check if an PowerShell Object exist?

What all of these answers do not highlight is that when comparing a value to $null, you have to put $null on the left-hand side, otherwise you may get into trouble when comparing with a collection-type value. See: https://github.com/nightroman/PowerShellTraps/blob/master/Basic/Comparison-operators-with-collections/looks-like-object-is-null.ps1

$value = @(1, $null, 2, $null)
if ($value -eq $null) {
    Write-Host "$value is $null"
}

The above block is (unfortunately) executed. What's even more interesting is that in Powershell a $value can be both $null and not $null:

$value = @(1, $null, 2, $null)
if (($value -eq $null) -and ($value -ne $null)) {
    Write-Host "$value is both $null and not $null"
}

So it is important to put $null on the left-hand side to make these comparisons work with collections:

$value = @(1, $null, 2, $null)
if (($null -eq $value) -and ($null -ne $value)) {
    Write-Host "$value is both $null and not $null"
}

I guess this shows yet again the power of Powershell !

Can we make unsigned byte in Java

Yes and no. Ive been digging around with this problem. Like i understand this:

The fact is that java has signed interger -128 to 127.. It is possible to present a unsigned in java with:

public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

If you for example add -12 signed number to be unsigned you get 244. But you can use that number again in signed, it has to be shifted back to signed and it´ll be again -12.

If you try to add 244 to java byte you'll get outOfIndexException.

Cheers..

How do you install an APK file in the Android emulator?

Late, but to be completed with options here: A handy tool to install any apk via gui to a running emulator is: http://apkinstaller.com

This can directly connect to a running instance via adb and can successfully install any kind of apk packages.

Maybe this is also helpful for other people. ;)

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

This worked for me

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Update - as of version 1.3 (june 2016) it is possible to search and replace in Visual Studio Code. Using ctrl + shift + f , you can search and replace text in all files.


It seems this is not possible at the moment (Version 1.1.1 (April 2016))

"Q: Is it possible to globally search and replace?

A: This feature is not yet implemented, but you can expect it to come in the future!"

https://code.visualstudio.com/Docs/editor/codebasics

This seems also requested by community: https://github.com/Microsoft/vscode/issues/1690

SVN: Folder already under version control but not comitting?

A variation on @gauss256's answer, deleting .svn, worked for me:

rm -rf troublesome_folder/.svn
svn add troublesome_folder
svn commit

Before Gauss's solution I tried @jwir3's approach and got no joy:

svn cleanup
svn cleanup *
svn cleanup troublesome_folder
svn add --force troublesome_folder
svn commit

Removing address bar from browser (to view on Android)

Here's an example that makes sure that the body has minimum height of the device screen height and also hides the scroll bar. It uses DOMSubtreeModified event, but makes the check only every 400ms, to avoid performance loss.

var page_size_check = null, q_body;
(q_body = $('#body')).bind('DOMSubtreeModified', function() {
  if (page_size_check === null) {
    return;
  }
  page_size_check = setTimeout(function() {
    q_body.css('height', '');
    if (q_body.height() < window.innerHeight) {
      q_body.css('height', window.innerHeight + 'px');
    }
    if (!(window.pageYOffset > 1)) {
      window.scrollTo(0, 1);
    }
    page_size_check = null;
  }, 400);
});

Tested on Android and iPhone.

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

Change column type in pandas

How about creating two dataframes, each with different data types for their columns, and then appending them together?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))

Results

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object

After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.

C++ Singleton design pattern

In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...

struct Store{
   std::array<Something, 1024> data;
   size_t get(size_t idx){ /* ... */ }
   void incr_ref(size_t idx){ /* ... */}
   void decr_ref(size_t idx){ /* ... */}
};

template<Store* store_p>
struct ItemRef{
   size_t idx;
   auto get(){ return store_p->get(idx); };
   ItemRef() { store_p->incr_ref(idx); };
   ~ItemRef() { store_p->decr_ref(idx); };
};

Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances

Now somewhere inside a function (such as main) you can do:

auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201); 

The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).

If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:

template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning 
                       instances of ItemRef<Store_t, store_p>. */ };

The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).

What is the 'dynamic' type in C# 4.0 used for?

COM interop. Especially IUnknown. It was designed specially for it.

Reset select2 value and show placeholder

Following the recommended way of doing it. Found in the documentation https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder (this seems to be a fairly common issue):

When this happens it usually means that you do not have a blank <option></option> as the first option in your <select>.

as in:

<select>
   <option></option>
   <option value="foo">your option 1</option>
   <option value="bar">your option 2</option>
   <option value="etc">...</option>
</select>

Node.js Logging

Winston is strong choice for most of the developers. I have been using winston for long. Recently I used winston with with papertrail which takes the application logging to next level.

Here is a nice screenshot from their site.

enter image description here

How its useful

  • you can manage logs from different systems at one place. this can be very useful when you have two backend communicating and can see logs from both at on place.

  • Logs are live. you can see realtime logs of your production server.

  • Powerful search and filter

  • you can create alerts to send you email if it encounters specific text in log.

and you can find more http://help.papertrailapp.com/kb/how-it-works/event-viewer/

A simple configuration using winston,winston-express and winston-papertrail node modules.

import winston from 'winston';
import expressWinston from 'express-winston';
//
// Requiring `winston-papertrail` will expose
// `winston.transports.Papertrail`
//
require('winston-papertrail').Papertrail;
// create winston transport for Papertrail
var winstonPapertrail = new winston.transports.Papertrail({
  host: 'logsX.papertrailapp.com',
  port: XXXXX
});
app.use(expressWinston.logger({
  transports: [winstonPapertrail],
  meta: true, // optional: control whether you want to log the meta data about the request (default to true)
  msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
  expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
  colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
  ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
}));

How to cache data in a MVC application

Steve Smith did two great blog posts which demonstrate how to use his CachedRepository pattern in ASP.NET MVC. It uses the repository pattern effectively and allows you to get caching without having to change your existing code.

http://ardalis.com/Introducing-the-CachedRepository-Pattern

http://ardalis.com/building-a-cachedrepository-via-strategy-pattern

In these two posts he shows you how to set up this pattern and also explains why it is useful. By using this pattern you get caching without your existing code seeing any of the caching logic. Essentially you use the cached repository as if it were any other repository.

How to insert programmatically a new line in an Excel cell in C#?

E.Run runForBreak = new E.Run();

E.Text textForBreak = new E.Text() { Space = SpaceProcessingModeValues.Preserve };
textForBreak.Text = "\n";
runForBreak.Append(textForBreak);
sharedStringItem.Append(runForBreak);

Redirect from an HTML page

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Redirect to a page</title>
    </head>
    <body onload="window.location.assign('http://example.com')">

    </body>
</html>

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

How to set up Spark on Windows?

I found the easiest solution on Windows is to build from source.

You can pretty much follow this guide: http://spark.apache.org/docs/latest/building-spark.html

Download and install Maven, and set MAVEN_OPTS to the value specified in the guide.

But if you're just playing around with Spark, and don't actually need it to run on Windows for any other reason that your own machine is running Windows, I'd strongly suggest you install Spark on a linux virtual machine. The simplest way to get started probably is to download the ready-made images made by Cloudera or Hortonworks, and either use the bundled version of Spark, or install your own from source or the compiled binaries you can get from the spark website.

How do I make a transparent canvas in html5?

Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:

#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas

I'm not sure but it looks like that the background-color is inherited as transparent from the body.

Spring Test & Security: How to mock authentication?

Create a class TestUserDetailsImpl on your test package:

@Service
@Primary
@Profile("test")
public class TestUserDetailsImpl implements UserDetailsService {
    public static final String API_USER = "[email protected]";

    private User getAdminUser() {
        User user = new User();
        user.setUsername(API_USER);

        SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_API_USER");
        user.setAuthorities(Collections.singletonList(role));

        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) 
                                         throws UsernameNotFoundException {
        if (Objects.equals(username, ADMIN_USERNAME))
            return getAdminUser();
        throw new UsernameNotFoundException(username);
    }
}

Rest endpoint:

@GetMapping("/invoice")
@Secured("ROLE_API_USER")
public Page<InvoiceDTO> getInvoices(){
   ...
}

Test endpoint:

@Test
@WithUserDetails("[email protected]")
public void testApi() throws Exception {
     ...
}

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

Pseudo-terminal will not be allocated because stdin is not a terminal

Per zanco's answer, you're not providing a remote command to ssh, given how the shell parses the command line. To solve this problem, change the syntax of your ssh command invocation so that the remote command is comprised of a syntactically correct, multi-line string.

There are a variety of syntaxes that can be used. For example, since commands can be piped into bash and sh, and probably other shells too, the simplest solution is to just combine ssh shell invocation with heredocs:

ssh user@server /bin/bash <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT

Note that executing the above without /bin/bash will result in the warning Pseudo-terminal will not be allocated because stdin is not a terminal. Also note that EOT is surrounded by single-quotes, so that bash recognizes the heredoc as a nowdoc, turning off local variable interpolation so that the command text will be passed as-is to ssh.

If you are a fan of pipes, you can rewrite the above as follows:

cat <<'EOT' | ssh user@server /bin/bash
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT

The same caveat about /bin/bash applies to the above.

Another valid approach is to pass the multi-line remote command as a single string, using multiple layers of bash variable interpolation as follows:

ssh user@server "$( cat <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT
)"

The solution above fixes this problem in the following manner:

  1. ssh user@server is parsed by bash, and is interpreted to be the ssh command, followed by an argument user@server to be passed to the ssh command

  2. " begins an interpolated string, which when completed, will comprise an argument to be passed to the ssh command, which in this case will be interpreted by ssh to be the remote command to execute as user@server

  3. $( begins a command to be executed, with the output being captured by the surrounding interpolated string

  4. cat is a command to output the contents of whatever file follows. The output of cat will be passed back into the capturing interpolated string

  5. << begins a bash heredoc

  6. 'EOT' specifies that the name of the heredoc is EOT. The single quotes ' surrounding EOT specifies that the heredoc should be parsed as a nowdoc, which is a special form of heredoc in which the contents do not get interpolated by bash, but rather passed on in literal format

  7. Any content that is encountered between <<'EOT' and <newline>EOT<newline> will be appended to the nowdoc output

  8. EOT terminates the nowdoc, resulting in a nowdoc temporary file being created and passed back to the calling cat command. cat outputs the nowdoc and passes the output back to the capturing interpolated string

  9. ) concludes the command to be executed

  10. " concludes the capturing interpolated string. The contents of the interpolated string will be passed back to ssh as a single command line argument, which ssh will interpret as the remote command to execute as user@server

If you need to avoid using external tools like cat, and don't mind having two statements instead of one, use the read built-in with a heredoc to generate the SSH command:

IFS='' read -r -d '' SSH_COMMAND <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT

ssh user@server "${SSH_COMMAND}"

Checking version of angular-cli that's installed?

Simply run the following command :

ng v

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

How to prevent scanf causing a buffer overflow in C?

It's not that much work to make a function that's allocating the needed memory for your string. That's a little c-function i wrote some time ago, i always use it to read in strings.

It will return the read string or if a memory error occurs NULL. But be aware that you have to free() your string and always check for it's return value.

#define BUFFER 32

char *readString()
{
    char *str = malloc(sizeof(char) * BUFFER), *err;
    int pos;
    for(pos = 0; str != NULL && (str[pos] = getchar()) != '\n'; pos++)
    {
        if(pos % BUFFER == BUFFER - 1)
        {
            if((err = realloc(str, sizeof(char) * (BUFFER + pos + 1))) == NULL)
                free(str);
            str = err;
        }
    }
    if(str != NULL)
        str[pos] = '\0';
    return str;
}

SQL Error: ORA-00913: too many values

For me this works perfect

insert into oehr.employees select * from employees where employee_id=99

I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.

One good approach will be to use the answer @Parodo specified

How to implement a ConfigurationSection with a ConfigurationElementCollection

If you are looking for a custom configuration section like following

<CustomApplicationConfig>
        <Credentials Username="itsme" Password="mypassword"/>
        <PrimaryAgent Address="10.5.64.26" Port="3560"/>
        <SecondaryAgent Address="10.5.64.7" Port="3570"/>
        <Site Id="123" />
        <Lanes>
          <Lane Id="1" PointId="north" Direction="Entry"/>
          <Lane Id="2" PointId="south" Direction="Exit"/>
        </Lanes> 
</CustomApplicationConfig>

then you can use my implementation of configuration section so to get started add System.Configuration assembly reference to your project

Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first

Credentials Element

public class CredentialsConfigElement : System.Configuration.ConfigurationElement
    {
        [ConfigurationProperty("Username")]
        public string Username
        {
            get 
            {
                return base["Username"] as string;
            }
        }

        [ConfigurationProperty("Password")]
        public string Password
        {
            get
            {
                return base["Password"] as string;
            }
        }
    }

PrimaryAgent and SecondaryAgent

Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following

public class ServerInfoConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Address")]
        public string Address
        {
            get
            {
                return base["Address"] as string;
            }
        }

        [ConfigurationProperty("Port")]
        public int? Port
        {
            get
            {
                return base["Port"] as int?;
            }
        }
    }

I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection

it is splitted in two parts first you have to create an element implementation class then you have to create collection element class

LaneConfigElement

public class LaneConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Id")]
        public string Id
        {
            get
            {
                return base["Id"] as string;
            }
        }

        [ConfigurationProperty("PointId")]
        public string PointId
        {
            get
            {
                return base["PointId"] as string;
            }
        }

        [ConfigurationProperty("Direction")]
        public Direction? Direction
        {
            get
            {
                return base["Direction"] as Direction?;
            }
        }
    }

    public enum Direction
    { 
        Entry,
        Exit
    }

you can notice that one attribute of LanElement is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException on startup. Ok lets move on to Collection Definition

[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class LaneConfigCollection : ConfigurationElementCollection
    {
        public LaneConfigElement this[int index]
        {
            get { return (LaneConfigElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public void Add(LaneConfigElement serviceConfig)
        {
            BaseAdd(serviceConfig);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LaneConfigElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LaneConfigElement)element).Id;
        }

        public void Remove(LaneConfigElement serviceConfig)
        {
            BaseRemove(serviceConfig.Id);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(String name)
        {
            BaseRemove(name);
        }

    }

you can notice that I have set the AddItemName = "Lane" you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.

Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection

CustomApplicationConfigSection

public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
        public const string SECTION_NAME = "CustomApplicationConfig";

        [ConfigurationProperty("Credentials")]
        public CredentialsConfigElement Credentials
        {
            get
            {
                return base["Credentials"] as CredentialsConfigElement;
            }
        }

        [ConfigurationProperty("PrimaryAgent")]
        public ServerInfoConfigElement PrimaryAgent
        {
            get
            {
                return base["PrimaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("SecondaryAgent")]
        public ServerInfoConfigElement SecondaryAgent
        {
            get
            {
                return base["SecondaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("Site")]
        public SiteConfigElement Site
        {
            get
            {
                return base["Site"] as SiteConfigElement;
            }
        }

        [ConfigurationProperty("Lanes")]
        public LaneConfigCollection Lanes
        {
            get { return base["Lanes"] as LaneConfigCollection; }
        }
    }

Now you can see that we have two properties with name PrimaryAgent and SecondaryAgent both have the same type now you can easily understand why we had only one implementation class against these two element.

Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).

<configSections>
    <section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
  </configSections>

NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll

to retrieve this configuration use following line of code any where in your application

CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;

I hope above post would help you to get started with a bit complicated kind of custom config sections.

Happy Coding :)

****Edit**** To Enable LINQ on LaneConfigCollection you have to implement IEnumerable<LaneConfigElement>

And Add following implementation of GetEnumerator

public new IEnumerator<LaneConfigElement> GetEnumerator()
        {
            int count = base.Count;
            for (int i = 0; i < count; i++)
            {
                yield return base.BaseGet(i) as LaneConfigElement;
            }
        }

for the people who are still confused about how yield really works read this nice article

Two key points taken from above article are

it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)

Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)

What to do with branch after merge

If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.

RESTful Authentication

To be honest with you I've seen great answers here but something that bothers me a bit is when someone will take the whole Stateless concept to a extreme where it becomes dogmatic. It reminds me of those old Smalltalk fans that only wanted to embrace pure OO and if something is not an object, then you're doing it wrong. Give me a break.

The RESTful approach is supposed to make your life easier and reduce the overhead and cost of sessions, try to follow it as it is a wise thing to do, but the minute you follow a discipline (any discipline/guideline) to the extreme where it no longer provides the benefit it was intended for, then you're doing it wrong. Some of the best languages today have both, functional programming and object orientation.

If the easiest way for you to solve your problem is to store the authentication key in a cookie and send it on HTTP header, then do it, just don't abuse it. Remember that sessions are bad when they become heavy and big, if all your session consists of is a short string containing a key, then what's the big deal?

I am open to accept corrections in comments but I just don't see the point (so far) in making our lives miserable to simply avoid keeping a big dictionary of hashes in our server.

Declare variable in SQLite and use it

For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).

WITH const AS (SELECT 'name' AS name, 10 AS more)
SELECT table.cost, (table.cost + const.more) AS newCost
FROM table, const 
WHERE table.name = const.name

SQLite WITH clause

Recommended date format for REST GET API

Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.

Pros:

  • Epoch format does not have a timezone.
  • Epoch has a single format (Unix time is a single signed number).
  • Epoch time is not effected by daylight saving.
  • Most of the Backend frameworks and all native ios/android APIs support epoch conversion.
  • Local time conversion part can be done entirely in application side depends on the timezone setting of user's device/browser.

Cons:

  • Extra processing for converting to UTC for storing in UTC format in the database.
  • Readability of input/output.
  • Readability of GET URLs.

Notes:

  • Timezones are a presentation-layer problem! Most of your code shouldn't be dealing with timezones or local time, it should be passing Unix time around.
  • If you want to store a humanly-readable time (e.g. logs), consider storing it along with Unix time, not instead of Unix time.

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

SQL query return data from multiple tables

Part 1 - Joins and Unions

This answer covers:

  1. Part 1
    • Joining two or more tables using an inner join (See the wikipedia entry for additional info)
    • How to use a union query
    • Left and Right Outer Joins (this stackOverflow answer is excellent to describe types of joins)
    • Intersect queries (and how to reproduce them if your database doesn't support them) - this is a function of SQL-Server (see info) and part of the reason I wrote this whole thing in the first place.
  2. Part 2
    • Subqueries - what they are, where they can be used and what to watch out for
    • Cartesian joins AKA - Oh, the misery!

There are a number of ways to retrieve data from multiple tables in a database. In this answer, I will be using ANSI-92 join syntax. This may be different to a number of other tutorials out there which use the older ANSI-89 syntax (and if you are used to 89, may seem much less intuitive - but all I can say is to try it) as it is much easier to understand when the queries start getting more complex. Why use it? Is there a performance gain? The short answer is no, but it is easier to read once you get used to it. It is easier to read queries written by other folks using this syntax.

I am also going to use the concept of a small caryard which has a database to keep track of what cars it has available. The owner has hired you as his IT Computer guy and expects you to be able to drop him the data that he asks for at the drop of a hat.

I have made a number of lookup tables that will be used by the final table. This will give us a reasonable model to work from. To start off, I will be running my queries against an example database that has the following structure. I will try to think of common mistakes that are made when starting out and explain what goes wrong with them - as well as of course showing how to correct them.

The first table is simply a color listing so that we know what colors we have in the car yard.

mysql> create table colors(id int(3) not null auto_increment primary key, 
    -> color varchar(15), paint varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> insert into colors (color, paint) values ('Red', 'Metallic'), 
    -> ('Green', 'Gloss'), ('Blue', 'Metallic'), 
    -> ('White' 'Gloss'), ('Black' 'Gloss');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from colors;
+----+-------+----------+
| id | color | paint    |
+----+-------+----------+
|  1 | Red   | Metallic |
|  2 | Green | Gloss    |
|  3 | Blue  | Metallic |
|  4 | White | Gloss    |
|  5 | Black | Gloss    |
+----+-------+----------+
5 rows in set (0.00 sec)

The brands table identifies the different brands of the cars out caryard could possibly sell.

mysql> create table brands (id int(3) not null auto_increment primary key, 
    -> brand varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from brands;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| brand | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> insert into brands (brand) values ('Ford'), ('Toyota'), 
    -> ('Nissan'), ('Smart'), ('BMW');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from brands;
+----+--------+
| id | brand  |
+----+--------+
|  1 | Ford   |
|  2 | Toyota |
|  3 | Nissan |
|  4 | Smart  |
|  5 | BMW    |
+----+--------+
5 rows in set (0.00 sec)

The model table will cover off different types of cars, it is going to be simpler for this to use different car types rather than actual car models.

mysql> create table models (id int(3) not null auto_increment primary key, 
    -> model varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from models;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| model | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into models (model) values ('Sports'), ('Sedan'), ('4WD'), ('Luxury');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from models;
+----+--------+
| id | model  |
+----+--------+
|  1 | Sports |
|  2 | Sedan  |
|  3 | 4WD    |
|  4 | Luxury |
+----+--------+
4 rows in set (0.00 sec)

And finally, to tie up all these other tables, the table that ties everything together. The ID field is actually the unique lot number used to identify cars.

mysql> create table cars (id int(3) not null auto_increment primary key, 
    -> color int(3), brand int(3), model int(3));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from cars;
+-------+--------+------+-----+---------+----------------+
| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(3) | NO   | PRI | NULL    | auto_increment |
| color | int(3) | YES  |     | NULL    |                |
| brand | int(3) | YES  |     | NULL    |                |
| model | int(3) | YES  |     | NULL    |                |
+-------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> insert into cars (color, brand, model) values (1,2,1), (3,1,2), (5,3,1), 
    -> (4,4,2), (2,2,3), (3,5,4), (4,1,3), (2,2,1), (5,2,3), (4,5,1);
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> select * from cars;
+----+-------+-------+-------+
| id | color | brand | model |
+----+-------+-------+-------+
|  1 |     1 |     2 |     1 |
|  2 |     3 |     1 |     2 |
|  3 |     5 |     3 |     1 |
|  4 |     4 |     4 |     2 |
|  5 |     2 |     2 |     3 |
|  6 |     3 |     5 |     4 |
|  7 |     4 |     1 |     3 |
|  8 |     2 |     2 |     1 |
|  9 |     5 |     2 |     3 |
| 10 |     4 |     5 |     1 |
+----+-------+-------+-------+
10 rows in set (0.00 sec)

This will give us enough data (I hope) to cover off the examples below of different types of joins and also give enough data to make them worthwhile.

So getting into the grit of it, the boss wants to know The IDs of all the sports cars he has.

This is a simple two table join. We have a table that identifies the model and the table with the available stock in it. As you can see, the data in the model column of the cars table relates to the models column of the cars table we have. Now, we know that the models table has an ID of 1 for Sports so lets write the join.

select
    ID,
    model
from
    cars
        join models
            on model=ID

So this query looks good right? We have identified the two tables and contain the information we need and use a join that correctly identifies what columns to join on.

ERROR 1052 (23000): Column 'ID' in field list is ambiguous

Oh noes! An error in our first query! Yes, and it is a plum. You see, the query has indeed got the right columns, but some of them exist in both tables, so the database gets confused about what actual column we mean and where. There are two solutions to solve this. The first is nice and simple, we can use tableName.columnName to tell the database exactly what we mean, like this:

select
    cars.ID,
    models.model
from
    cars
        join models
            on cars.model=models.ID

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
|  2 | Sedan  |
|  4 | Sedan  |
|  5 | 4WD    |
|  7 | 4WD    |
|  9 | 4WD    |
|  6 | Luxury |
+----+--------+
10 rows in set (0.00 sec)

The other is probably more often used and is called table aliasing. The tables in this example have nice and short simple names, but typing out something like KPI_DAILY_SALES_BY_DEPARTMENT would probably get old quickly, so a simple way is to nickname the table like this:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID

Now, back to the request. As you can see we have the information we need, but we also have information that wasn't asked for, so we need to include a where clause in the statement to only get the Sports cars as was asked. As I prefer the table alias method rather than using the table names over and over, I will stick to it from this point onwards.

Clearly, we need to add a where clause to our query. We can identify Sports cars either by ID=1 or model='Sports'. As the ID is indexed and the primary key (and it happens to be less typing), lets use that in our query.

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Bingo! The boss is happy. Of course, being a boss and never being happy with what he asked for, he looks at the information, then says I want the colors as well.

Okay, so we have a good part of our query already written, but we need to use a third table which is colors. Now, our main information table cars stores the car color ID and this links back to the colors ID column. So, in a similar manner to the original, we can join a third table:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Damn, although the table was correctly joined and the related columns were linked, we forgot to pull in the actual information from the new table that we just linked.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
+----+--------+-------+
4 rows in set (0.00 sec)

Right, that's the boss off our back for a moment. Now, to explain some of this in a little more detail. As you can see, the from clause in our statement links our main table (I often use a table that contains information rather than a lookup or dimension table. The query would work just as well with the tables all switched around, but make less sense when we come back to this query to read it in a few months time, so it is often best to try to write a query that will be nice and easy to understand - lay it out intuitively, use nice indenting so that everything is as clear as it can be. If you go on to teach others, try to instill these characteristics in their queries - especially if you will be troubleshooting them.

It is entirely possible to keep linking more and more tables in this manner.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

While I forgot to include a table where we might want to join more than one column in the join statement, here is an example. If the models table had brand-specific models and therefore also had a column called brand which linked back to the brands table on the ID field, it could be done as this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
            and b.brand=d.ID
where
    b.ID=1

You can see, the query above not only links the joined tables to the main cars table, but also specifies joins between the already joined tables. If this wasn't done, the result is called a cartesian join - which is dba speak for bad. A cartesian join is one where rows are returned because the information doesn't tell the database how to limit the results, so the query returns all the rows that fit the criteria.

So, to give an example of a cartesian join, lets run the following query:

select
    a.ID,
    b.model
from
    cars a
        join models b

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  1 | Sedan  |
|  1 | 4WD    |
|  1 | Luxury |
|  2 | Sports |
|  2 | Sedan  |
|  2 | 4WD    |
|  2 | Luxury |
|  3 | Sports |
|  3 | Sedan  |
|  3 | 4WD    |
|  3 | Luxury |
|  4 | Sports |
|  4 | Sedan  |
|  4 | 4WD    |
|  4 | Luxury |
|  5 | Sports |
|  5 | Sedan  |
|  5 | 4WD    |
|  5 | Luxury |
|  6 | Sports |
|  6 | Sedan  |
|  6 | 4WD    |
|  6 | Luxury |
|  7 | Sports |
|  7 | Sedan  |
|  7 | 4WD    |
|  7 | Luxury |
|  8 | Sports |
|  8 | Sedan  |
|  8 | 4WD    |
|  8 | Luxury |
|  9 | Sports |
|  9 | Sedan  |
|  9 | 4WD    |
|  9 | Luxury |
| 10 | Sports |
| 10 | Sedan  |
| 10 | 4WD    |
| 10 | Luxury |
+----+--------+
40 rows in set (0.00 sec)

Good god, that's ugly. However, as far as the database is concerned, it is exactly what was asked for. In the query, we asked for for the ID from cars and the model from models. However, because we didn't specify how to join the tables, the database has matched every row from the first table with every row from the second table.

Okay, so the boss is back, and he wants more information again. I want the same list, but also include 4WDs in it.

This however, gives us a great excuse to look at two different ways to accomplish this. We could add another condition to the where clause like this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
    or b.ID=3

While the above will work perfectly well, lets look at it differently, this is a great excuse to show how a union query will work.

We know that the following will return all the Sports cars:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

And the following would return all the 4WDs:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

So by adding a union all clause between them, the results of the second query will be appended to the results of the first query.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
union all
select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
|  5 | 4WD    | Green |
|  7 | 4WD    | White |
|  9 | 4WD    | Black |
+----+--------+-------+
7 rows in set (0.00 sec)

As you can see, the results of the first query are returned first, followed by the results of the second query.

In this example, it would of course have been much easier to simply use the first query, but union queries can be great for specific cases. They are a great way to return specific results from tables from tables that aren't easily joined together - or for that matter completely unrelated tables. There are a few rules to follow however.

  • The column types from the first query must match the column types from every other query below.
  • The names of the columns from the first query will be used to identify the entire set of results.
  • The number of columns in each query must be the same.

Now, you might be wondering what the difference is between using union and union all. A union query will remove duplicates, while a union all will not. This does mean that there is a small performance hit when using union over union all but the results may be worth it - I won't speculate on that sort of thing in this though.

On this note, it might be worth noting some additional notes here.

  • If we wanted to order the results, we can use an order by but you can't use the alias anymore. In the query above, appending an order by a.ID would result in an error - as far as the results are concerned, the column is called ID rather than a.ID - even though the same alias has been used in both queries.
  • We can only have one order by statement, and it must be as the last statement.

For the next examples, I am adding a few extra rows to our tables.

I have added Holden to the brands table. I have also added a row into cars that has the color value of 12 - which has no reference in the colors table.

Okay, the boss is back again, barking requests out - *I want a count of each brand we carry and the number of cars in it!` - Typical, we just get to an interesting section of our discussion and the boss wants more work.

Rightyo, so the first thing we need to do is get a complete listing of possible brands.

select
    a.brand
from
    brands a

+--------+
| brand  |
+--------+
| Ford   |
| Toyota |
| Nissan |
| Smart  |
| BMW    |
| Holden |
+--------+
6 rows in set (0.00 sec)

Now, when we join this to our cars table we get the following result:

select
    a.brand
from
    brands a
        join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Nissan |
| Smart  |
| Toyota |
+--------+
5 rows in set (0.00 sec)

Which is of course a problem - we aren't seeing any mention of the lovely Holden brand I added.

This is because a join looks for matching rows in both tables. As there is no data in cars that is of type Holden it isn't returned. This is where we can use an outer join. This will return all the results from one table whether they are matched in the other table or not:

select
    a.brand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Holden |
| Nissan |
| Smart  |
| Toyota |
+--------+
6 rows in set (0.00 sec)

Now that we have that, we can add a lovely aggregate function to get a count and get the boss off our backs for a moment.

select
    a.brand,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+--------------+
| brand  | countOfBrand |
+--------+--------------+
| BMW    |            2 |
| Ford   |            2 |
| Holden |            0 |
| Nissan |            1 |
| Smart  |            1 |
| Toyota |            5 |
+--------+--------------+
6 rows in set (0.00 sec)

And with that, away the boss skulks.

Now, to explain this in some more detail, outer joins can be of the left or right type. The Left or Right defines which table is fully included. A left outer join will include all the rows from the table on the left, while (you guessed it) a right outer join brings all the results from the table on the right into the results.

Some databases will allow a full outer join which will bring back results (whether matched or not) from both tables, but this isn't supported in all databases.

Now, I probably figure at this point in time, you are wondering whether or not you can merge join types in a query - and the answer is yes, you absolutely can.

select
    b.brand,
    c.color,
    count(a.id) as countOfBrand
from
    cars a
        right outer join brands b
            on b.ID=a.brand
        join colors c
            on a.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
+--------+-------+--------------+
9 rows in set (0.00 sec)

So, why is that not the results that were expected? It is because although we have selected the outer join from cars to brands, it wasn't specified in the join to colors - so that particular join will only bring back results that match in both tables.

Here is the query that would work to get the results that we expected:

select
    a.brand,
    c.color,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
        left outer join colors c
            on b.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Holden | NULL  |            0 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| Toyota | NULL  |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
+--------+-------+--------------+
11 rows in set (0.00 sec)

As we can see, we have two outer joins in the query and the results are coming through as expected.

Now, how about those other types of joins you ask? What about Intersections?

Well, not all databases support the intersection but pretty much all databases will allow you to create an intersection through a join (or a well structured where statement at the least).

An Intersection is a type of join somewhat similar to a union as described above - but the difference is that it only returns rows of data that are identical (and I do mean identical) between the various individual queries joined by the union. Only rows that are identical in every regard will be returned.

A simple example would be as such:

select
    *
from
    colors
where
    ID>2
intersect
select
    *
from
    colors
where
    id<4

While a normal union query would return all the rows of the table (the first query returning anything over ID>2 and the second anything having ID<4) which would result in a full set, an intersect query would only return the row matching id=3 as it meets both criteria.

Now, if your database doesn't support an intersect query, the above can be easily accomlished with the following query:

select
    a.ID,
    a.color,
    a.paint
from
    colors a
        join colors b
            on a.ID=b.ID
where
    a.ID>2
    and b.ID<4

+----+-------+----------+
| ID | color | paint    |
+----+-------+----------+
|  3 | Blue  | Metallic |
+----+-------+----------+
1 row in set (0.00 sec)

If you wish to perform an intersection across two different tables using a database that doesn't inherently support an intersection query, you will need to create a join on every column of the tables.

SQL Query to concatenate column values from multiple rows in Oracle

For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT a.pid, seq, description
              FROM table_a a, table_b b
              WHERE a.pid = b.pid(+)
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT pid, seq, description
              FROM table_b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

The key idea here is using an artificial value for the group of descriptions to be concatenated.

In the following query, the constant string '1' is used, but any value will work:

SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
       FROM (
              SELECT '1' unique_id, b.pid, b.seq, b.description
              FROM table_b b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1;

Individual concatenated descriptions can be reordered in the PARTITION BY clause.

Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

Enter triggers button click

Using

<button type="button">Whatever</button>

should do the trick.

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

Excel: replace part of cell's string value

I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:

=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")

In my case, I am using excel to view a DBF file and however it was populated has times like this:

9:16a
2:22p

So I just made a new column and put that formula in it to convert it to the excel time format.

html5 input for money/currency

I stumbled across this article looking for a similar answer. I read @vsync example Using javascript's Number.prototype.toLocaleString: and it appeared to work well. The only complaint I had was that if you had more than a single input type="currency" within your page it would only modify the first instance of it.

As he mentions in his comments it was only designed as an example for stackoverflow.

However, the example worked well for me and although I have little experience with JS I figured out how to modify it so that it will work with multiple input type="currency" on the page using the document.querySelectorAll rather than document.querySelector and adding a for loop.

I hope this can be useful for someone else. ( Credit for the bulk of the code is @vsync )

var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

for ( var i = 0; i < currencyInput.length; i++ ) {

    var currency = 'GBP'
    onBlur( {
        target: currencyInput[ i ]
    } )

    currencyInput[ i ].addEventListener( 'focus', onFocus )
    currencyInput[ i ].addEventListener( 'blur', onBlur )

    function localStringToNumber( s ) {
        return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
    }

    function onFocus( e ) {
        var value = e.target.value;
        e.target.value = value ? localStringToNumber( value ) : ''
    }

    function onBlur( e ) {
        var value = e.target.value

        var options = {
            maximumFractionDigits: 2,
            currency: currency,
            style: "currency",
            currencyDisplay: "symbol"
        }

        e.target.value = ( value || value === 0 ) ?
            localStringToNumber( value ).toLocaleString( undefined, options ) :
            ''
    }
}

_x000D_
_x000D_
    var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

    for ( var i = 0; i < currencyInput.length; i++ ) {

        var currency = 'GBP'
        onBlur( {
            target: currencyInput[ i ]
        } )

        currencyInput[ i ].addEventListener( 'focus', onFocus )
        currencyInput[ i ].addEventListener( 'blur', onBlur )

        function localStringToNumber( s ) {
            return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
        }

        function onFocus( e ) {
            var value = e.target.value;
            e.target.value = value ? localStringToNumber( value ) : ''
        }

        function onBlur( e ) {
            var value = e.target.value

            var options = {
                maximumFractionDigits: 2,
                currency: currency,
                style: "currency",
                currencyDisplay: "symbol"
            }

            e.target.value = ( value || value === 0 ) ?
                localStringToNumber( value ).toLocaleString( undefined, options ) :
                ''
        }
    }
_x000D_
.input_date {
    margin:1px 0px 50px 0px;
    font-family: 'Roboto', sans-serif;
    font-size: 18px;
    line-height: 1.5;
    color: #111;
    display: block;
    background: #ddd;
    height: 50px;
    border-radius: 5px;
    border: 2px solid #111111;
    padding: 0 20px 0 20px;
    width: 100px;
}
_x000D_
    <label for="cost_of_sale">Cost of Sale</label>
    <input class="input_date" type="currency" name="cost_of_sale" id="cost_of_sale" value="0.00">

    <label for="sales">Sales</label>
    <input class="input_date" type="currency" name="sales" id="sales" value="0.00">

     <label for="gm_pounds">GM Pounds</label>
     <input class="input_date" type="currency" name="gm_pounds" id="gm_pounds" value="0.00">
_x000D_
_x000D_
_x000D_

How can I drop a table if there is a foreign key constraint in SQL Server?

You have to drop the constraint before drop your table.

You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.

Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'

-- Find FK in This table.
SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = 
OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName


-- Find the FKs in the tables in which this table is used
  SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =   
      OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
  + ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
 OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    ' ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName 

Input type number "only numeric value" validation

The easiest way would be to use a library like this one and specifically you want noStrings to be true

    export class CustomValidator{   // Number only validation   
      static numeric(control: AbstractControl) {
        let val = control.value;

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }

moment.js get current time in milliseconds?

You could subtract the current time stamp from 12 AM of the same day.

Using current timestamp:

moment().valueOf() - moment().startOf('day').valueOf()

Using arbitrary day:

moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

With Validation

In this example I used two controls,ddl and txtbox, have a happy coding

 asp:ScriptManager ID="script1" runat="server" /asp:ScriptManager

    asp:UpdatePanel ID="Panel1" runat="server"
       ContentTemplate

// ASP BUTTON
asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-success" OnClientClick="return Valid()" OnClick="btnSave_Click"


   /ContentTemplate    
    /asp:UpdatePanel    

  <script type="text/javascript">
        function Valid() {

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val() == 0) {
                alert("Please select YOUR TEXT");
                $("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val().length == 0) {
                alert("Please Type YOUR TEXT");
                $("ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }
            return true;
        }
</script>

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

UIView background color in Swift

You can use this extension as an alternative if you're dealing with RGB value.

extension UIColor {
    static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
        return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
      }
    }

Is there a way to know your current username in mysql?

Try the CURRENT_USER() function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges.

This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your client, even though you sent a username). If you want the username the client sent to MySQL when connecting use the USER() function instead.

The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user

What is the use of join() in Python threading?

In python 3.x join() is used to join a thread with the main thread i.e. when join() is used for a particular thread the main thread will stop executing until the execution of joined thread is complete.

#1 - Without Join():
import threading
import time
def loiter():
    print('You are loitering!')
    time.sleep(5)
    print('You are not loitering anymore!')

t1 = threading.Thread(target = loiter)
t1.start()
print('Hey, I do not want to loiter!')
'''
Output without join()--> 
You are loitering!
Hey, I do not want to loiter!
You are not loitering anymore! #After 5 seconds --> This statement will be printed

'''
#2 - With Join():
import threading
import time
def loiter():
    print('You are loitering!')
    time.sleep(5)
    print('You are not loitering anymore!')

t1 = threading.Thread(target = loiter)
t1.start()
t1.join()
print('Hey, I do not want to loiter!')

'''
Output with join() -->
You are loitering!
You are not loitering anymore! #After 5 seconds --> This statement will be printed
Hey, I do not want to loiter! 

'''

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Clear and refresh jQuery Chosen dropdown list

If in case trigger("chosen:updated"); doesn't works for you. You can try $('#ddl').trigger('change'); as in my case its work for me.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

SQL QUERY replace NULL value in a row with a value from the previous known value

First of all, do you really need to store the values? You may just use the view that does the job:

SELECT  t."date",
        x."number" AS "number"
FROM    @Table t
JOIN    @Table x
    ON  x."date" = (SELECT  TOP 1 z."date"
                    FROM    @Table z
                    WHERE   z."date" <= t."date"
                        AND z."number" IS NOT NULL
                    ORDER BY z."date" DESC)

If you really do have the ID ("date") column and it is a primary key (clustered), then this query should be pretty fast. But check the query plan: it might be better to have a cover index including the Val column as well.

Also if you do not like procedures when you can avoid them, you can also use similar query for UPDATE:

UPDATE  t
SET     t."number" = x."number"
FROM    @Table t
JOIN    @Table x
    ON  x."date" = (SELECT  TOP 1 z."date"
                    FROM    @Table z
                    WHERE   z."date" < t."date" --//@note: < and not <= here, as = not required
                        AND z."number" IS NOT NULL
                    ORDER BY z."date" DESC)
WHERE   t."number" IS NULL

NOTE: the code must works on "SQL Server".

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

One liner to check if element is in the list

If he really wants a one liner without any collections, OK, he can have one:

for(String s:new String[]{"a", "b", "c")) if (s.equals("a")) System.out.println("It's there");

*smile*

(Isn't it ugly? Please, don't use it in real code)

Git ignore local file changes

You probably need to do a git stash before you git pull, this is because it is reading your old config file. So do:

git stash
git pull
git commit -am <"say first commit">
git push

Also see git-stash(1) Manual Page.

Java NIO FileChannel versus FileOutputstream performance / usefulness

Answering the "usefulness" part of the question:

One rather subtle gotcha of using FileChannel over FileOutputStream is that performing any of its blocking operations (e.g. read() or write()) from a thread that's in interrupted state will cause the channel to close abruptly with java.nio.channels.ClosedByInterruptException.

Now, this could be a good thing if whatever the FileChannel was used for is part of the thread's main function, and design took this into account.

But it could also be pesky if used by some auxiliary feature such as a logging function. For example, you can find your logging output suddenly closed if the logging function happens to be called by a thread that's also interrupted.

It's unfortunate this is so subtle because not accounting for this can lead to bugs that affect write integrity.[1][2]

How to write loop in a Makefile?

This answer, just as that of @Vroomfondel aims to circumvent the loop problem in an elegant way.

My take is to let make generate the loop itself as an imported makefile like this:

include Loop.mk
Loop.mk:Loop.sh
     Loop.sh > $@

The shell script can the be as advanced as you like but a minimal working example could be

#!/bin/bash
LoopTargets=""
NoTargest=5
for Target in `seq $NoTargest` ; do
    File="target_${Target}.dat"
    echo $File:data_script.sh
    echo $'\t'./data_script.ss $Target
    LoopTargets="$LoopTargets $File"
done
echo;echo;echo LoopTargets:=$LoopTargets

which generates the file

target_1.dat:data_script.sh
    ./data_script.ss 1
target_2.dat:data_script.sh
    ./data_script.ss 2
target_3.dat:data_script.sh
    ./data_script.ss 3
target_4.dat:data_script.sh
    ./data_script.ss 4
target_5.dat:data_script.sh
    ./data_script.ss 5


LoopTargets:= target_1.dat target_2.dat target_3.dat target_4.dat target_5.dat

And advantage there is that make can itself keep track of which files have been generated and which ones need to be (re)generated. As such, this also enables make to use the -j flag for parallelization.

How to parse a JSON string into JsonNode in Jackson?

You need to use an ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);

Further documentation about creating parsers can be found here.

Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

https://developers.facebook.com/docs/facebook-login/for-devices

How can I set the color of a selected row in DataGrid

The default IsSelected trigger changes 3 properties, Background, Foreground & BorderBrush. If you want to change the border as well as the background, just include this in your style trigger.

<Style TargetType="{x:Type dg:DataGridCell}">
    <Style.Triggers>
        <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
            <Setter Property="Background" Value="#CCDAFF" />
            <Setter Property="BorderBrush" Value="Black" />
        </Trigger>
    </Style.Triggers>
</Style>

How do I Validate the File Type of a File Upload?

You could use a regular expression validator on the upload control:

  <asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Upload Excel files only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.xls|.XLS|.xlsx|.XLSX)$" ControlToValidate="fileUpload"> </asp:RegularExpressionValidator>

There is also the accept attribute of the input tag:

<input type="file" accept="application/msexcel" id="fileUpload" runat="server">

but I did not have much success when I tried this (with FF3 and IE7)

How to prevent default event handling in an onclick method?

Give a class or id to the element and use jquery function unbind();

$(".slide_prevent").click(function(){
                $(".slide_prevent").unbind();
              });

Get Application Directory

Based on @jared-burrows' solution. For any package, but passing Context as parameter...

public static String getDataDir(Context context) throws Exception {
    return context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0)
            .applicationInfo.dataDir;
}

Return a value if no rows are found in Microsoft tSQL

You can do something just like this.

IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
   select 
select name ,Id from TableName WHERE Column=colval
END
ELSE
  SELECT 'test' as name,0 as Id

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

Disabling SSL Certificate Validation in Spring RestTemplate

@Bean
public RestTemplate restTemplate() 
                throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
 }

How to compare two lists in python?

a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']

# if you care about order
a == b # True
a == c # False

# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True

By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.

Remove numbers from string sql server

One more approach using Recursive CTE..

declare @string varchar(100)
set @string ='te165st1230004616161616'

;With cte
as
(
select @string as string,0  as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc


**Output:**   
  test

Round a divided number in Bash

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

Example, rounding down:

N/2
M/5
K/16

Example, rounding up:

(N+1)/2
(M+4)/5
(K+15)/16

To do round-to-nearest, add (denom/2) to the numerator (halves will round up):

(N+1)/2
(M+2)/5
(K+8)/16

How to pretty-print a numpy.array without scientific notation and with given precision?

I use

def np_print(array,fmt="10.5f"):
    print (array.size*("{:"+fmt+"}")).format(*array)

It's not difficult to modify it for multi-dimensional arrays.

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

How to remove word wrap from textarea?

The following CSS based solution works for me:

<html>
 <head>
  <style type='text/css'>
   textarea {
    white-space: nowrap;
    overflow:    scroll;
    overflow-y:  hidden;
    overflow-x:  scroll;
    overflow:    -moz-scrollbars-horizontal;
   }
  </style>
 </head>
 <body>
  <form>
   <textarea>This is a long line of text for testing purposes...</textarea>
  </form>
 </body>
</html>

jQuery Toggle Text?

I've written my own little extension for toggleText. It may come in handy.

Fiddle: https://jsfiddle.net/b5u14L5o/

jQuery Extension:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
                                                    : $(this).text(stateOne);
        });  
    }
});

Usage:

...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------

//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------

//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------

//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------

How do I get today's date in C# in mm/dd/yyyy format?

Or without the year:

DateTime.Now.ToString("M/dd")

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

in this link i mentioned before on the comment, read this part :

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

this "JOIN FETCH" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).

And it is only effect the method of "when the query should happen". And you must also know this:

hibernate have two orthogonal notions : when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.

when is the association fetched --> your "FETCH" type

how is it fetched --> Join/select/Subselect/Batch

In your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:

@OneToMany(fetch = FetchType.LAZY)
private Set<Department> department;

when you use

FROM Employee emp
JOIN FETCH emp.department dep

you will get emp and emp.dep. when you didnt use fetch you can still get emp.dep but hibernate will processing another select to the database to get that set of department.

so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).

Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).

use fetch when :

  • no large unneeded collection/set inside that entity you about to get

  • communication from application server to database server too far and need long time

  • you may need that collection latter when you don't have the access to it(outside of the transactional method/class)

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Why is the use of alloca() not considered good practice?

As noted in this newsgroup posting, there are a few reasons why using alloca can be considered difficult and dangerous:

  • Not all compilers support alloca.
  • Some compilers interpret the intended behaviour of alloca differently, so portability is not guaranteed even between compilers that support it.
  • Some implementations are buggy.

Rails: Check output of path helper from console

you can also

include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:

url_for controller: :users, only_path: true
users_path
# => '/users'

or

Rails.application.routes.url_helpers.users_path

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   @JsonProperty("geonames")
   private List<Country> countries; 

   //getter - setter
}

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

How do you perform a left outer join using linq extension methods

Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.

The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.

static IQueryable<TResult> LeftOuterJoin<TSource,TInner, TKey, TResult>(
     this IQueryable<TSource> source, 
     IQueryable<TInner> inner, 
     Expression<Func<TSource,TKey>> sourceKey, 
     Expression<Func<TInner,TKey>> innerKey, 
     Expression<Func<TSource, TInner, TResult>> result
    ) {
    return from a in source.AsExpandable()
            join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
            from d in c.DefaultIfEmpty()
            select result.Invoke(a,d);
}

It can be used as follows

Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});

How do I verify that a string only contains letters, numbers, underscores and dashes?

use a regex and see if it matches!

([a-z][A-Z][0-9]\_\-)*

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

currently unable to handle this request HTTP ERROR 500

I found this was caused by adding a new scope variable to the login scope

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO is like the end of a script.

You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.


BEGIN and END are just like { and } in C/++/#, Java, etc.

They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...

IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
   INSERT INTO Log SELECT @id, 'deleted'
   DELETE my_table WHERE id = @id
END

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

Install a .NET windows service without InstallUtil.exe

Here is a class I use when writing services. I usually have an interactive screen that comes up when the service is not called. From there I use the class as needed. It allows for multiple named instances on the same machine -hence the InstanceID field

Sample Call

  IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
  Inst.Install("MySvc", "My Sample Service", "Service that executes something",
                    _InstanceID,
// System.ServiceProcess.ServiceAccount.LocalService,      // this is more secure, but only available in XP and above and WS-2003 and above
  System.ServiceProcess.ServiceAccount.LocalSystem,       // this is required for WS-2000
  System.ServiceProcess.ServiceStartMode.Automatic);
  if (controller == null)
  {
    controller = new System.ServiceProcess.ServiceController(String.Format("MySvc_{0}", _InstanceID), ".");
                }
                if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Start_Stop.Text = "Stop Service";
                    Start_Stop_Debugging.Enabled = false;
                }
                else
                {
                    Start_Stop.Text = "Start Service";
                    Start_Stop_Debugging.Enabled = true;
                }

The class itself

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;

namespace MySvc
{
    class IntegratedServiceInstaller
    {
        public void Install(String ServiceName, String DisplayName, String Description,
            String InstanceID,
            System.ServiceProcess.ServiceAccount Account, 
            System.ServiceProcess.ServiceStartMode StartMode)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            ProcessInstaller.Account = Account;

            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
            string processPath = Process.GetCurrentProcess().MainModule.FileName;
            if (processPath != null && processPath.Length > 0)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                String path = String.Format("/assemblypath={0}", fi.FullName);
                String[] cmdline = { path };
                Context = new System.Configuration.Install.InstallContext("", cmdline);
            }

            SINST.Context = Context;
            SINST.DisplayName = String.Format("{0} - {1}", DisplayName, InstanceID);
            SINST.Description = String.Format("{0} - {1}", Description, InstanceID);
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.StartType = StartMode;
            SINST.Parent = ProcessInstaller;

            // http://bytes.com/forum/thread527221.html
            SINST.ServicesDependedOn = new String[] { "Spooler", "Netlogon", "Netman" };

            System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
            SINST.Install(state);

            // http://www.dotnet247.com/247reference/msgs/43/219565.aspx
            using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", ServiceName, InstanceID), true))
            {
                try
                {
                    Object sValue = oKey.GetValue("ImagePath");
                    oKey.SetValue("ImagePath", sValue);
                }
                catch (Exception Ex)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message);
                }
            }

        }
        public void Uninstall(String ServiceName, String InstanceID)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
            SINST.Context = Context;
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.Uninstall(null);
        }
    }
}

File Explorer in Android Studio

Device Explorer path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/...

Logs File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/storage/emulated/0/Android/data/com.app.domain/files/LogFiles/

Shared Preferences File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

System.currentTimeMillis vs System.nanoTime

Yes, if such precision is required use System.nanoTime(), but be aware that you are then requiring a Java 5+ JVM.

On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:

private void test() {
    System.out.println("currentTimeMillis: "+System.currentTimeMillis());
    System.out.println("nanoTime         : "+System.nanoTime());
    System.out.println();

    testNano(false);                                                            // to sync with currentTimeMillis() timer tick
    for(int xa=0; xa<10; xa++) {
        testNano(true);
        }
    }

private void testNano(boolean shw) {
    long strMS=System.currentTimeMillis();
    long strNS=System.nanoTime();
    long curMS;
    while((curMS=System.currentTimeMillis()) == strMS) {
        if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
        }
    if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
    }

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Please see http://mvnrepository.com/artifact/javax.mail/mail/, you can download jar or use the maven dependency, depending on your project type. That should pretty much cover it and you won't get a NoClassDefFoundError exception.

Sending HTML email using Python

Here's a working example to send plain text and HTML emails from Python using smtplib along with the CC and BCC options.

https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail(params, type_):
      email_subject = params['email_subject']
      email_from = "[email protected]"
      email_to = params['email_to']
      email_cc = params.get('email_cc')
      email_bcc = params.get('email_bcc')
      email_body = params['email_body']

      msg = MIMEMultipart('alternative')
      msg['To'] = email_to
      msg['CC'] = email_cc
      msg['Subject'] = email_subject
      mt_html = MIMEText(email_body, type_)
      msg.attach(mt_html)

      server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
      server.set_debuglevel(1)
      toaddrs = [email_to] + [email_cc] + [email_bcc]
      server.sendmail(email_from, toaddrs, msg.as_string())
      server.quit()

# Calling the mailer functions
params = {
    'email_to': '[email protected]',
    'email_cc': '[email protected]',
    'email_bcc': '[email protected]',
    'email_subject': 'Test message from python library',
    'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
    send_mail(params, t)

Tesseract running error

I'm using Visual Studio 2017 Community Edition.
I solved this problem by making a directory called tessdata in the Debug directory of my project. Then I put the eng.traineddata file into said directory.

C# Telnet Library

I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.

** Unique in this instance can be validly interpreted as brain-dead.

Make Bootstrap 3 Tabs Responsive

The solution is just 3 lines:

@media only screen and (max-width: 479px) {
   .nav-tabs > li {
      width: 100%;
   }
}

..but you have to accept the idea of tabs that wrap to more lines in other dimensions.

Of course you can achieve a horizontal scrolling area with white-space: nowrap trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!

Return index of highest value in an array

My solution is:

$maxs = array_keys($array, max($array))

Note:
this way you can retrieve every key related to a given max value.

If you are interested only in one key among all simply use $maxs[0]

How to implement authenticated routes in React Router 4?

I implemented using-

<Route path='/dashboard' render={() => (
    this.state.user.isLoggedIn ? 
    (<Dashboard authenticate={this.authenticate} user={this.state.user} />) : 
    (<Redirect to="/login" />)
)} />

authenticate props will be passed to components e.g. signup using which user state can be changed. Complete AppRoutes-

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { Redirect } from 'react-router';

import Home from '../pages/home';
import Login from '../pages/login';
import Signup from '../pages/signup';
import Dashboard from '../pages/dashboard';

import { config } from '../utils/Config';

export default class AppRoutes extends React.Component {

    constructor(props) {
        super(props);

        // initially assuming that user is logged out
        let user = {
            isLoggedIn: false
        }

        // if user is logged in, his details can be found from local storage
        try {
            let userJsonString = localStorage.getItem(config.localStorageKey);
            if (userJsonString) {
                user = JSON.parse(userJsonString);
            }
        } catch (exception) {
        }

        // updating the state
        this.state = {
            user: user
        };

        this.authenticate = this.authenticate.bind(this);
    }

    // this function is called on login/logout
    authenticate(user) {
        this.setState({
            user: user
        });

        // updating user's details
        localStorage.setItem(config.localStorageKey, JSON.stringify(user));
    }

    render() {
        return (
            <Switch>
                <Route exact path='/' component={Home} />
                <Route exact path='/login' render={() => <Login authenticate={this.authenticate} />} />
                <Route exact path='/signup' render={() => <Signup authenticate={this.authenticate} />} />
                <Route path='/dashboard' render={() => (
                    this.state.user.isLoggedIn ? 
                            (<Dashboard authenticate={this.authenticate} user={this.state.user} />) : 
                            (<Redirect to="/login" />)
                )} />
            </Switch>
        );
    }
} 

Check the complete project here: https://github.com/varunon9/hello-react

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

Oldapps.com has old versions of Chrome available for download, and they’re the standalone versions, so combined with @SamMeiers’ answer, these work a treat.

The Google Chrome support forum has some good discussion of getting old versions of Chrome.

MongoDB: How to find the exact version of installed MongoDB

Option1:

Start the console and execute this:

db.version()

Option2:

Open a shell console and do:

$ mongod --version

It will show you something like

$ mongod --version
db version v3.0.2

Vim autocomplete for Python

This can be a good option if you want python completion as well as other languages. https://github.com/Valloric/YouCompleteMe

The python completion is jedi based same as jedi-vim.

Access: Move to next record until EOF

I have done this in the past, and have always used this:

  With Me.RecordsetClone
    .MoveFirst
    Do Until .EOF
      If Me.Dirty Then
         Me.Dirty = False
      End If
      .MoveNext
      Me.Bookmark = .Bookmark
    Loop
  End With

Some people would use the form's Recordset, which doesn't require setting the bookmark (i.e., navigating the form's Recordset navigates the form's edit buffer automatically, so the user sees the move immediately), but I prefer the indirection of the RecordsetClone.

Removing an activity from the history stack

I know I'm late on this (it's been two years since the question was asked) but I accomplished this by intercepting the back button press. Rather than checking for specific activities, I just look at the count and if it's less than 3 it simply sends the app to the back (pausing the app and returning the user to whatever was running before launch). I check for less than three because I only have one intro screen. Also, I check the count because my app allows the user to navigate back to the home screen through the menu, so this allows them to back up through other screens like normal if there are activities other than the intro screen on the stack.

//We want the home screen to behave like the bottom of the activity stack so we do not return to the initial screen
//unless the application has been killed. Users can toggle the session mode with a menu item at all other times.
@Override
public void onBackPressed() {
    //Check the activity stack and see if it's more than two deep (initial screen and home screen)
    //If it's more than two deep, then let the app proccess the press
    ActivityManager am = (ActivityManager)this.getSystemService(Activity.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(3); //3 because we have to give it something. This is an arbitrary number
    int activityCount = tasks.get(0).numActivities;

    if (activityCount < 3)
    {
        moveTaskToBack(true);
    }
    else
    {
        super.onBackPressed();
    }
}

How to set Status Bar Style in Swift 3

[UPDATED] For Xcode 10+ & Swift 4.2+

This is the preferred method for iOS 7 and higher

In your application's Info.plist, set View controller-based status bar appearance to YES.

Override preferredStatusBarStyle (Apple docs) in each of your view controllers. For example:

override var preferredStatusBarStyle: UIStatusBarStyle {     
      return .lightContent
}

If you have preferredStatusBarStyle returning a different preferred status bar style based on something that changes inside of your view controller (for example, whether the scroll position or whether a displayed image is dark), then you will want to call setNeedsStatusBarAppearanceUpdate() when that state changes.

iOS before version 7, deprecated method

Apple has deprecated this, so it will be removed in the future. Use the above method so that you don't have to rewrite it when the next iOS version is released.

If your application will support In your application's Info.plist, set View controller-based status bar appearance to NO.

In appDelegate.swift, the didFinishLaunchingWithOptions function, add:

UIApplication.shared.statusBarStyle = .lightContent

For Navigation Controller

If you use a navigation controller and you want the preferred status bar style of each view controller to be used and set View controller-based status bar appearance to YES in your application's info.plist

extension UINavigationController {
   open override var preferredStatusBarStyle: UIStatusBarStyle {
      return topViewController?.preferredStatusBarStyle ?? .default
   }
}

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Oracle PL/SQL - How to create a simple array variable?

Another solution is to use an Oracle Collection as a Hashmap:

declare 
-- create a type for your "Array" - it can be of any kind, record might be useful
  type hash_map is table of varchar2(1000) index by varchar2(30);
  my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
  i varchar2(30);
begin
  my_hmap('a') := 'apple';
  my_hmap('b') := 'box';
  my_hmap('c') := 'crow';
-- then how you use it:

  dbms_output.put_line (my_hmap('c')) ;

-- or to loop on every element - it's a "collection"
  i := my_hmap.FIRST;

  while (i is not null)  loop     
    dbms_output.put_line(my_hmap(i));      
    i := my_hmap.NEXT(i);
  end loop;

end;

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

Number of elements in a javascript object

Although JS implementations might keep track of such a value internally, there's no standard way to get it.

In the past, Mozilla's Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5.

For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():

function countProperties(obj) {
    var count = 0;

    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            ++count;
    }

    return count;
}

In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)

function countProperties(obj) {
    return Object.keys(obj).length;
}

Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length).

If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten

How to set default font family for entire Android app

I know this question is quite old, but I have found a nice solution. Basically, you pass a container layout to this function, and it will apply the font to all supported views, and recursively cicle in child layouts:

public static void setFont(ViewGroup layout)
{
    final int childcount = layout.getChildCount();
    for (int i = 0; i < childcount; i++)
    {
        // Get the view
        View v = layout.getChildAt(i);

        // Apply the font to a possible TextView
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Apply the font to a possible EditText
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Recursively cicle into a possible child layout
        try {
            ViewGroup vg = (ViewGroup) v;
            Utility.setFont(vg);
            continue;
        }
        catch (Exception e) { }
    }
}