Programs & Examples On #Buildpath

This tag refers to build path settings for a Java project in Eclipse IDE. You can reach this option through the project properties (Project > Properties > Java Build Path) from the context menu on a created project or the File menu of the workbench.

How to set the java.library.path from Eclipse

For a given application launch, you can do it as jim says.

If you want to set it for the entire workspace, you can also set it under

Window->
  Preferences->
    Java->
      Installed JREs

Each JRE has a "Default VM arguments" (which I believe are completely ignored if any VM args are set for a run configuration.)

You could even set up different JRE/JDKs with different parameters and have some projects use one, other projects use another.

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Go to Project > Properties > Java Compiler > Building
  2. Look under Build Path Problems
  3. Un-check "Abort build when build path error occurs"
    It won't solve all your errors but at least it will let you run your program :)

Android - R cannot be resolved to a variable

Fought the same problem for about an hour. I finally realized that I was referencing some image files in an xml file that I did not yet have in my R.drawable folder. As soon as I copied the files into the folder, the problem went away. You need to make sure you have all the necessary files present.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

If you are not using Maven, just drop the javax.servlet-api.jar in your project lib folder.

Setting the classpath in java using Eclipse IDE

You can create new User library,

On

"Configure Build Paths" page -> Add Library -> User Library (on list) -> User Libraries Button (rigth side of page)

and create your library and (add Jars buttons) include your specific Jars.

I hope this can help you.

getting JRE system library unbound error in build path

I too faced the same issue. I followed the following steps to resolve my issue -

  • Right click on your project -> Properties
  • Select Java Build Path in the left menu
  • Select Libraries tab
  • Under the module path, select the troublesome JRE entry
  • Click on Edit button
  • Select Workspace default JRE.
  • Click on Finish button

If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.

Eclipse error: "The import XXX cannot be resolved"

Add the jar files in class path instead of module path. Worked for me.

Attach the Source in Eclipse of a jar

I am using project is not Spring or spring boot based application. I have multiple subprojects and they are nested one within another. The answers shown here supports on first level of subproject. If I added another sub project for source code attachement, it is not allowing me saying folder already exists error.

Looks like eclipse is out dated IDE. I am using the latest version of Eclipse version 2015-2019. It is killing all my time.

My intension is run the application in debug mode navigate through the sub projects which are added as external dependencies (non modifiable).

How can I check if a var is a string in JavaScript?

The typeof operator isn't an infix (so the LHS of your example doesn't make sense).

You need to use it like so...

if (typeof a_string == 'string') {
    // This is a string.
}

Remember, typeof is an operator, not a function. Despite this, you will see typeof(var) being used a lot in the wild. This makes as much sense as var a = 4 + (1).

Also, you may as well use == (equality comparison operator) since both operands are Strings (typeof always returns a String), JavaScript is defined to perform the same steps had I used === (strict comparison operator).

As Box9 mentions, this won't detect a instantiated String object.

You can detect for that with....

var isString = str instanceof String;

jsFiddle.

...or...

var isString = str.constructor == String;

jsFiddle.

But this won't work in a multi window environment (think iframes).

You can get around this with...

var isString = Object.prototype.toString.call(str) == '[object String]';

jsFiddle.

But again, (as Box9 mentions), you are better off just using the literal String format, e.g. var str = 'I am a string';.

Further Reading.

MongoDB or CouchDB - fit for production?

Speaking production, seamless failover/recovery both require a baby sitter
1- Couchbase, there is no seamless failover/recovery, manual intervention is required.
rebalancing takes too much time, too much risk if more than one node get lost.

2- Mongo with shards, data recovery from loosing a config server, is not an easy task

C# "internal" access modifier when doing unit testing

If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

How to implement authenticated routes in React Router 4?

I know it's been a while but I've been working on an npm package for private and public routes.

Here's how to make a private route:

<PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>

And you can also make Public routes that only unauthed user can access

<PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

I hope it helps!

Stop Excel from automatically converting certain text values to dates

What I have done for this same problem was to add the following before each csv value: "=""" and one double quote after each CSV value, before opening the file in Excel. Take the following values for example:

012345,00198475

These should be altered before opening in Excel to:

"="""012345","="""00198475"

After you do this, every cell value appears as a formula in Excel and so won't be formatted as a number, date, etc. For example, a value of 012345 appears as:

="012345"

SQL: Two select statements in one query

The UNION statement is your friend:

SELECT   a.playername, a.games, a.goals
FROM     tblMadrid as a
WHERE    a.playername = "ronaldo"
UNION
SELECT   b.playername, b.games, b.goals
FROM     tblBarcelona as b
WHERE    b.playername = "messi"
ORDER BY goals;

Allow 2 decimal places in <input type="number">

On input:

step="any"
class="two-decimals"

On script:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

How do you get the width and height of a multi-dimensional array?

Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#

[Test]
public void ArraysAreRowMajor()
{
    var myArray = new int[2,3]
        {
            {1, 2, 3},
            {4, 5, 6}
        };

    int rows = myArray.GetLength(0);
    int columns = myArray.GetLength(1);
    Assert.AreEqual(2,rows);
    Assert.AreEqual(3,columns);
    Assert.AreEqual(1,myArray[0,0]);
    Assert.AreEqual(2,myArray[0,1]);
    Assert.AreEqual(3,myArray[0,2]);
    Assert.AreEqual(4,myArray[1,0]);
    Assert.AreEqual(5,myArray[1,1]);
    Assert.AreEqual(6,myArray[1,2]);
}

Can I draw rectangle in XML?

Quick and dirty way:

<View
    android:id="@+id/colored_bar"
    android:layout_width="48dp"
    android:layout_height="3dp"
    android:background="@color/bar_red" />

Laravel Blade html image

in my case this worked perfectly

<img  style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">

this code is used to display image from folder

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

  1. Due to optimization, it is very easy to compare given integers just with min and max range.
  2. The reason that range() function is so fast in Python3 is that here we use mathematical reasoning for the bounds, rather than a direct iteration of the range object.
  3. So for explaining the logic here:
    • Check whether the number is between the start and stop.
    • Check whether the step precision value doesn't go over our number.
  4. Take an example, 997 is in range(4, 1000, 3) because:

    4 <= 997 < 1000, and (997 - 4) % 3 == 0.

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

Forking / Multi-Threaded Processes | Bash

Let me try example

for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } &  done ; sleep 10

And use jobs to see what's running.

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

PHP Function with Optional Parameters

NOTE: This is an old answer, for PHP 5.5 and below. PHP 5.6+ supports default arguments

In PHP 5.5 and below, you can achieve this by using one of these 2 methods:

  • using the func_num_args() and func_get_arg() functions;
  • using NULL arguments;

How to use

function method_1()
{
  $arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
  $arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
}

function method_2($arg1 = null, $arg2 = null)
{
  $arg1 = $arg1? $arg1: "default_value_for_arg1";
  $arg2 = $arg2? $arg2: "default_value_for_arg2";
}

I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.

'^M' character at end of lines

Another vi command that'll do: :%s/.$// This removes the last character of each line in the file. The drawback to this search and replace command is that it doesn't care what the last character is, so be careful not to call it twice.

How to set the margin or padding as percentage of height of parent container?

This is a very interesting bug. (In my opinion, it is a bug anyway) Nice find!

Regarding how to set it, I would recommend Camilo Martin's answer. But as to why, I'd like to explain this a bit if you guys don't mind.


In the CSS specs I found:

'padding'
Percentages: refer to width of containing block

… which is weird, but okay.

So, with a parent width: 210px and a child padding-top: 50%, I get a calculated/computed value of padding-top: 96.5px – which is not the expected 105px.

That is because in Windows (I'm not sure about other OSs), the size of common scrollbars is per default 17px × 100% (or 100% × 17px for horizontal bars). Those 17px are substracted before calculating the 50%, hence 50% of 193px = 96.5px.

How to count items in JSON object using command line?

You can also use jq to track down the array within the returned json and then pipe that in to a second jq call to get its length. Suppose it was in a property called records, like {"records":[...]}.

$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$ 

How do I programmatically determine operating system in Java?

You can just use sun.awt.OSInfo#getOSType() method

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

Problem

I had a similar problem using axes. The class parameter is frameon but the kwarg is frame_on. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

Solution

frame_on

Example

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

Get Locale Short Date Format using javascript

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

The Intl.DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.

var date = new Date(2014, 11, 31, 12, 30, 0);

var formatter = new Intl.DateTimeFormat("ru");
console.log( formatter.format(date) ); // 31.12.2014

var formatter = new Intl.DateTimeFormat("en-US");

console.log(formatter.format(date)); // 12/31/2014

format of your current zone :

console.log(new Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale).
format(new Date()))

How can I upgrade NumPy?

FYI, when you using or importing TensorFlow, a similar error may occur, like (caused by NumPy):

RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 60, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: numpy.core.multiarray failed to import


Error importing tensorflow.  Unless you are using bazel,
you should not try to import tensorflow from its source directory;
please exit the tensorflow source tree, and relaunch your python interpreter
from there.

I followed Elmira's and Drew's solution, sudo easy_install numpy, and it worked!

sudo easy_install numpy
Searching for numpy
Best match: numpy 1.11.3
Removing numpy 1.8.2 from easy-install.pth file
Adding numpy 1.11.3 to easy-install.pth file

Using /usr/local/lib/python2.7/dist-packages
Processing dependencies for numpy
Finished processing dependencies for numpy

After that I could use TensorFlow without error.

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

input() error - NameError: name '...' is not defined

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

loading json data from local file into React JS

If you have couple of json files:

import data from 'sample.json';

If you were to dynamically load one of the many json file, you might have to use a fetch instead:

fetch(`${fileName}.json`)
  .then(response => response.json())
  .then(data => console.log(data))

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Only numbers. Input number in React

2019 Answer Late, but hope it helps somebody

This will make sure you won't get null on an empty textfield

  • Textfield value is always 0
  • When backspacing, you will end with 0
  • When value is 0 and you start typing, 0 will be replaced with the actual number
// This will make sure that value never is null when textfield is empty

const minimum = 0;   

export default (props) => {
    const [count, changeCount] = useState(minimum);

    function validate(count) {
        return parseInt(count) | minimum
    }

    function handleChangeCount(count) {
        changeCount(validate(count))
    }

    return (
        <Form>
            <FormGroup>
                <TextInput
                    type="text"
                    value={validate(count)}
                    onChange={handleChangeCount}
                />
            </FormGroup>
            <ActionGroup>
                <Button type="submit">submit form</Button>
            </ActionGroup>
        </Form>
    );
};

How to concatenate string variables in Bash

Despite of the special operator, +=, for concatenation, there is a simpler way to go:

foo='Hello'
foo=$foo' World'
echo $foo

Double quotes take an extra calculation time for interpretation of variables inside. Avoid it if possible.

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

How to find and replace string?

// replaced text will be in buffer.
void Replace(char* buffer, const char* source, const char* oldStr,  const char* newStr)
{
    if(buffer==NULL || source == NULL || oldStr == NULL || newStr == NULL) return; 

    int slen = strlen(source);
    int olen = strlen(oldStr);
    int nlen = strlen(newStr);

    if(olen>slen) return;
    int ix=0;

    for(int i=0;i<slen;i++)
    {
        if(oldStr[0] == source[i])
        {
            bool found = true;
            for(int j=1;j<olen;j++)
            {
                if(source[i+j]!=oldStr[j])
                {
                    found = false;
                    break;
                }
            }

            if(found)
            {
                for(int j=0;j<nlen;j++)
                    buffer[ix++] = newStr[j];

                i+=(olen-1);
            }
            else
            {
                buffer[ix++] = source[i];
            }
        }
        else
        {
            buffer[ix++] = source[i];
        }
    }
}

How to set space between listView Items in Android

Maybe you can try to add android:layout_marginTop = "15dp" and android:layout_marginBottom = "15dp" in the outermost Layout

Run MySQLDump without Locking Tables

    mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db |   mysql -u root --password=xxx -h localhost db

Jenkins fails when running "service start jenkins"

I had a similar issue on CentOS 7 while a correct version of Java was installed and java -version gave a nice result.

Collecting multiple answers from different SO threads I did the following:

Make sure Java is installed (and version is compatible with Jenkins) There're some tricks if saying about CentOS, this is mentioned in official Jenkins tutorial here

If Java is installed and available, when running java -v output should look like this:

    ~>$java -version
    openjdk version "1.8.0_161"
    OpenJDK Runtime Environment (build 1.8.0_161-b14)
    OpenJDK 64-Bit Server VM (build 25.161-b14, mixed mode)

Add a path to Java to your /etc/rc.d/init.d/jenkins

   ~>$ sudo vim /etc/rc.d/init.d/jenkins
    candidates="
    /etc/alternatives/java
    /usr/lib/jvm/java-1.8.0/bin/java
    /usr/lib/jvm/jre-1.8.0/bin/java
    /usr/lib/jvm/java-1.7.0/bin/java
    /usr/lib/jvm/jre-1.7.0/bin/java
    /usr/bin/java
    /usr/java/jdk1.8.0_162/bin/java ##add your java path here
    "

How to get your 'real' path to java distributive which is called when you type smth like java -v Follow this SO thread

If steps above didn't help, try to make sure all permission issues are resolved:

  1. If Jenkins fails to run Java, it could be jenkins user doesn't have permissions to run it, then change jenkins to root in config (described here)
  2. Try to play with chmod setting 755 permissions to java installation folder

And finally what helped me in result When I did run journalctl -xe as was suggested when I've tried to sudo service jenkins start, I got similar Java stacktrace:

Starting CloudBees Jenkins Enterprise Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Main._main(Main.java:140)
at Main.main(Main.java:98)
Caused by: java.lang.UnsatisfiedLinkError: /tmp/jna--1712433994/jna7387046629130767794.tmp: /tmp/jna--1712433994/jna7387046629130767794.tmp: failed to map segment from shared object: Operation not permitted
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1937)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1822)
at java.lang.Runtime.load0(Runtime.java:809)
at java.lang.System.load(System.java:1086)
at com.sun.jna.Native.loadNativeDispatchLibraryFromClasspath(Native.java:761)
at com.sun.jna.Native.loadNativeDispatchLibrary(Native.java:736)
at com.sun.jna.Native.<clinit>(Native.java:131)
at com.sun.akuma.CLibrary.<clinit>(CLibrary.java:89)
at com.sun.akuma.JavaVMArguments.resolvePID(JavaVMArguments.java:128)
at com.sun.akuma.JavaVMArguments.ofLinux(JavaVMArguments.java:116)
at com.sun.akuma.JavaVMArguments.of(JavaVMArguments.java:104)
at com.sun.akuma.JavaVMArguments.current(JavaVMArguments.java:92)
at com.sun.akuma.Daemon.daemonize(Daemon.java:106)
at com.sun.akuma.Daemon.all(Daemon.java:88)
... 6 more

The problem is that Jenkins tries to launch JNA library from /tmp dir which is marked as noexec by default, so we it could be fixed by creating a temporary directory in a /jenkins path so it could be executed. The full way to do this is described here by CloudBees support (thanks a lot for them)

I hope something from this list will help (as well I mostly leave it for me in the future when I'll have to install Jenkins for CentOs again :)

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Using Case/Switch and GetType to determine the object

Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.

Bootstrap date time picker

All scripts should be imported in order:

  1. jQuery and Moment.js
  2. Bootstrap js file
  3. Bootstrap datepicker js file

Bootstrap-datetimepicker requires moment.js to be loaded before datepicker.js.

Working snippet:

_x000D_
_x000D_
$(function() {_x000D_
  $('#datetimepicker1').datetimepicker();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class='col-sm-6'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker1'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit and replay XHR chrome/firefox etc?

Microsoft Chromium-based Edge supports "Edit and Replay" requests in the Network Tab as an experimental feature:

enter image description here

More details about the feature and how to enable it can be found here

Freemarker iterating over hashmap keys

You can use a single quote to access the key that you set in your Java program.

If you set a Map in Java like this

Map<String,Object> hash = new HashMap<String,Object>();
hash.put("firstname", "a");
hash.put("lastname", "b");

Map<String,Object> map = new HashMap<String,Object>();
map.put("hash", hash);

Then you can access the members of 'hash' in Freemarker like this -

${hash['firstname']}
${hash['lastname']}

Output :

a
b

GridLayout (not GridView) how to stretch all children evenly

Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.

The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.

Here is some code:

Main Activity:

public class GridHolderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_6);
    }
}

activity_main_6 XML (inflates 3 fragments)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/frag1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".Grid.TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />

Base fragment layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:layout_height="match_parent">

    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img1"
        android:layout_weight="1"/>


    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img2"
        android:layout_weight="1"/>
</LinearLayout>

Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment

public class TwoHorizontalGridFragment extends Fragment {
private View rootView;

private ImageQueue imageQueue1;
private ImageQueue imageQueue2;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    /**
     * Inflate the layout for this fragment
     */
    rootView = inflater.inflate(
            R.layout.two_horiz, container, false);
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
    imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
    imageQueue1.updateFiles();
    imageQueue2.updateFiles();
}

}

Thats it!

This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

How to make the division of 2 ints produce a float instead of another int?

You can cast the numerator or the denominator to float...

int operations usually return int, so you have to change one of the operanding numbers.

Git diff between current branch and master but not including unmerged master commits

git diff `git merge-base master branch`..branch

Merge base is the point where branch diverged from master.

Git diff supports a special syntax for this:

git diff master...branch

You must not swap the sides because then you would get the other branch. You want to know what changed in branch since it diverged from master, not the other way round.

Loosely related:


Note that .. and ... syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions.

Quoting man git-diff:

  • git diff [--options] <commit> <commit> [--] [<path>…]

    This is to view the changes between two arbitrary <commit>.

  • git diff [--options] <commit>..<commit> [--] [<path>…]

    This is synonymous to the previous form. If <commit> on one side is omitted, it will have the same effect as using HEAD instead.

  • git diff [--options] <commit>...<commit> [--] [<path>…]

    This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B". You can omit any one of <commit>, which has the same effect as using HEAD instead.

Just in case you are doing something exotic, it should be noted that all of the <commit> in the above description, except in the last two forms that use ".." notations, can be any <tree>.

For a more complete list of ways to spell <commit>, see "SPECIFYING REVISIONS" section in gitrevisions[7]. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>" and "<commit>...<commit>") do not mean a range as defined in the "SPECIFYING RANGES" section in gitrevisions[7].

Connection Java-MySql : Public Key Retrieval is not allowed

This solution worked for MacOS Sierra, and running MySQL version 8.0.11. Please make sure driver you have added in your build path - "add external jar" should match up with SQL version.

String url = "jdbc:mysql://localhost:3306/syscharacterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";

How to debug "ImagePullBackOff"?

Have you tried to edit to see what's wrong (I had the wrong image location)

kubectl edit pods arix-3-yjq9w

or even delete your pod?

kubectl delete arix-3-yjq9w

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com

How do I get the color from a hexadecimal color code using .NET?

If you don't want to use the ColorTranslator, you can do it in easily:

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

The colorcode is just the hexadecimal representation of the ARGB value.

EDIT

If you need to use 4 values instead of a single integer, you can use this (combining several comments):

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

Bootstrap navbar Active State not working

For bootstrap mobile menu un-collapse after clicking a item you can use this

$("ul.nav.navbar-nav li a").click(function() {    

    $(".navbar-collapse").removeClass("in");
});

How to create User/Database in script for Docker Postgres

By using docker-compose:

Assuming that you have following directory layout:

$MYAPP_ROOT/docker-compose.yml
           /Docker/init.sql
           /Docker/db.Dockerfile

File: docker-compose.yml

version: "3.3"
services:
  db:
    build:
      context: ./Docker
      dockerfile: db.Dockerfile
    volumes:
      - ./var/pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

File: Docker/init.sql

CREATE USER myUser;

CREATE DATABASE myApp_dev;
GRANT ALL PRIVILEGES ON DATABASE myApp_dev TO myUser;

CREATE DATABASE myApp_test;
GRANT ALL PRIVILEGES ON DATABASE myApp_test TO myUser;

File: Docker/db.Dockerfile

FROM postgres:11.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/

Composing and starting services:

docker-compose -f docker-compose.yml up --no-start
docker-compose -f docker-compose.yml start

Java Convert GMT/UTC to Local time doesn't work as expected

I am joining the choir recommending that you skip the now long outdated classes Date, Calendar, SimpleDateFormat and friends. In particular I would warn against using the deprecated methods and constructors of the Date class, like the Date(String) constructor you used. They were deprecated because they don’t work reliably across time zones, so don’t use them. And yes, most of the constructors and methods of that class are deprecated.

While at the time you asked the question, Joda-Time was (from all I know) a clearly better alternative, time has moved on again. Today Joda-Time is a largely finished project, and its developers recommend you use java.time, the modern Java date and time API, instead. I will show you how.

    ZonedDateTime localTime = ZonedDateTime.now(ZoneId.systemDefault());

    // Convert Local Time to UTC 
    OffsetDateTime gmtTime
            = localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println("Local:" + localTime.toString() 
            + " --> UTC time:" + gmtTime.toString());

    // Reverse Convert UTC Time to Local time
    localTime = gmtTime.atZoneSameInstant(ZoneId.systemDefault());
    System.out.println("Local Time " + localTime.toString());

For starters, note that not only is the code only half as long as yours, it is also clearer to read.

On my computer the code prints:

Local:2017-09-02T07:25:46.211+02:00[Europe/Berlin] --> UTC time:2017-09-02T05:25:46.211Z
Local Time 2017-09-02T07:25:46.211+02:00[Europe/Berlin]

I left out the milliseconds from the epoch. You can always get them from System.currentTimeMillis(); as in your question, and they are independent of time zone, so I didn’t find them intersting here.

I hesitatingly kept your variable name localTime. I think it’s a good name. The modern API has a class called LocalTime, so using that name, only not capitalized, for an object that hasn’t got type LocalTime might confuse some (a LocalTime doesn’t hold time zone information, which we need to keep here to be able to make the right conversion; it also only holds the time-of-day, not the date).

Your conversion from local time to UTC was incorrect and impossible

The outdated Date class doesn’t hold any time zone information (you may say that internally it always uses UTC), so there is no such thing as converting a Date from one time zone to another. When I just ran your code on my computer, the first line it printed, was:

Local:Sat Sep 02 07:25:45 CEST 2017,1504329945967 --> UTC time:Sat Sep 02 05:25:45 CEST 2017-1504322745000

07:25:45 CEST is correct, of course. The correct UTC time would have been 05:25:45 UTC, but it says CEST again, which is incorrect.

Now you will never need the Date class again, :-) but if you were ever going to, the must-read would be All about java.util.Date on Jon Skeet’s coding blog.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

  • In Java 8 and later the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (that’s ThreeTen for JSR-310, where the modern API was first defined).
  • On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and I think that there’s a wonderful explanation in this question: How to use ThreeTenABP in Android Project.

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

Failed binder transaction when putting an bitmap dynamically in a widget

You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.

Compress!!

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray(); 
        setresult.putExtra("BMP",bytes);

Uncompress!!

        byte[] bytes = data.getByteArrayExtra("BMP");
        Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

How to make join queries using Sequelize on Node.js

In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster

UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

The first problem is that your query string is wrong:

I think this: "INSERT INTO employee(hans,germany) values(?,?)" should be like this: "INSERT INTO employee(name,country) values(?,?)"

The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.

You should add these to your code:

String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

How to delete columns in pyspark dataframe

Adding to @Patrick's answer, you can use the following to drop multiple columns

columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)

How to get only numeric column values?

The other answers indicating using IsNumeric in the where clause are correct, as far as they go, but it's important to remember that it returns 1 if the value can be converted to any numeric type. As such, oddities such as "1d3" will make it through the filter.

If you need only values composed of digits, search for that explicitly:

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%'

The above is filtering to reject any column which contains a non-digit character

Note that in any case, you're going to incur a table scan, indexes are useless for this sort of query.

How to initialize all members of an array to the same value?

For delayed initialization (i.e. class member constructor initialization) consider:

int a[4];

unsigned int size = sizeof(a) / sizeof(a[0]);
for (unsigned int i = 0; i < size; i++)
  a[i] = 0;

CSS selector for first element with class

Try this solution:

_x000D_
_x000D_
 .home p:first-of-type {_x000D_
  border:5px solid red;_x000D_
  width:100%;_x000D_
  display:block;_x000D_
}
_x000D_
<div class="home">_x000D_
  <span>blah</span>_x000D_
  <p class="red">first</p>_x000D_
  <p class="red">second</p>_x000D_
  <p class="red">third</p>_x000D_
  <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CodePen link

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Rails: Using greater than/less than with a where statement

Arel is your friend:

User.where(User.arel_table[:id].gt(200))

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The advantages of EditorFor is that your code is not tied to an <input type="text". So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.

See: HttpURLConnection implementation

System.MissingMethodException: Method not found?

I got this exception while testing out some code a coworker had written. Here is a summary of the exception info.:

Method not found: "System.Threading.Tasks.Task1<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry1<System_Canon>> Microsoft.EntityFrameworkCore.DbSet`1.AddAsync...

This was in Visual Studio 2019 in a class library targeting .NET Core 3.1. The fix was to use the Add method instead of AddAsync on the DbSet.

Tree data structure in C#

Tree With Generic Data

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class Tree<T>
{
    public T Data { get; set; }
    public LinkedList<Tree<T>> Children { get; set; } = new LinkedList<Tree<T>>();
    public Task Traverse(Func<T, Task> actionOnNode, int maxDegreeOfParallelism = 1) => Traverse(actionOnNode, new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism));
    private async Task Traverse(Func<T, Task> actionOnNode, SemaphoreSlim semaphore)
    {
        await actionOnNode(Data);
        SafeRelease(semaphore);
        IEnumerable<Task> tasks = Children.Select(async input =>
        {
            await semaphore.WaitAsync().ConfigureAwait(false);
            try
            {
                await input.Traverse(actionOnNode, semaphore).ConfigureAwait(false);
            }
            finally
            {
                SafeRelease(semaphore);
            }
        });
        await Task.WhenAll(tasks);
    }
    private void SafeRelease(SemaphoreSlim semaphore)
    {
        try
        {
            semaphore.Release();
        }
        catch (Exception ex)
        {
            if (ex.Message.ToLower() != "Adding the specified count to the semaphore would cause it to exceed its maximum count.".ToLower())
            {
                throw;
            }
        }
    }

    public async Task<IEnumerable<T>> ToList()
    {
        ConcurrentBag<T> lst = new ConcurrentBag<T>();
        await Traverse(async (data) => lst.Add(data));
        return lst;
    }
    public async Task<int> Count() => (await ToList()).Count();
}



Unit Tests

using System.Threading.Tasks;
using Xunit;

public class Tree_Tests
{
    [Fact]
    public async Task Tree_ToList_Count()
    {
        Tree<int> head = new Tree<int>();

        Assert.NotEmpty(await head.ToList());
        Assert.True(await head.Count() == 1);

        // child
        var child = new Tree<int>();
        head.Children.AddFirst(child);
        Assert.True(await head.Count() == 2);
        Assert.NotEmpty(await head.ToList());

        // grandson
        child.Children.AddFirst(new Tree<int>());
        child.Children.AddFirst(new Tree<int>());
        Assert.True(await head.Count() == 4);
        Assert.NotEmpty(await head.ToList());
    }

    [Fact]
    public async Task Tree_Traverse()
    {
        Tree<int> head = new Tree<int>() { Data = 1 };

        // child
        var child = new Tree<int>() { Data = 2 };
        head.Children.AddFirst(child);

        // grandson
        child.Children.AddFirst(new Tree<int>() { Data = 3 });
        child.Children.AddLast(new Tree<int>() { Data = 4 });

        int counter = 0;
        await head.Traverse(async (data) => counter += data);
        Assert.True(counter == 10);

        counter = 0;
        await child.Traverse(async (data) => counter += data);
        Assert.True(counter == 9);

        counter = 0;
        await child.Children.First!.Value.Traverse(async (data) => counter += data);
        Assert.True(counter == 3);

        counter = 0;
        await child.Children.Last!.Value.Traverse(async (data) => counter += data);
        Assert.True(counter == 4);
    }
}

How do I test if a recordSet is empty? isNull?

RecordCount is what you want to use.

If Not temp_rst1.RecordCount > 0 ...

How can I push a specific commit to a remote, and not previous commits?

I did want to obmit a old big history and start from a fresh commit i choosed to:

rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo 
git push 

when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.

Word wrap for a label in Windows Forms

Not sure it will fit all use-cases but I often use a simple trick to get the wrapping behaviour: put your Label with AutoSize=false inside a 1x1 TableLayoutPanel which will take care of the Label's size.

Microsoft.ACE.OLEDB.12.0 provider is not registered

I thought I'd chime in because I found this question when facing a slightly different context of the problem and thought it might help other tormented souls in the future:

I had an ASP.NET app hosted on IIS 7.0 running on Windows Server 2008 64-bit.

Since IIS is in control of the process bitness, the solution in my case was to set the Enable32bitAppOnWin64 setting to true: http://blogs.msdn.com/vijaysk/archive/2009/03/06/iis-7-tip-2-you-can-now-run-32-bit-and-64-bit-applications-on-the-same-server.aspx

It works slightly differently in IIS 6.0 (You cannot set Enable32bitAppOnWin64 at application-pool level) http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0aafb9a0-1b1c-4a39-ac9a-994adc902485.mspx?mfr=true

How to get form values in Symfony2 controller

In Symfony >= 2.3, you can get the value of single fields with:

$var = $form->get('yourformfieldname')->getData();

On the other hand, you can use:

$data = $form->getData();

BUT this would get you two different things:

  • the entity with values populated by the form, if your form have the data-class option enabled (so it's binded to an entity); this will exclude any field with the 'mapping' => false option

  • otherwise, an array with all the form's fields

Java: How to convert List to Map

Apache Commons MapUtils.populateMap

If you don't use Java 8 and you don't want to use a explicit loop for some reason, try MapUtils.populateMap from Apache Commons.

MapUtils.populateMap

Say you have a list of Pairs.

List<ImmutablePair<String, String>> pairs = ImmutableList.of(
    new ImmutablePair<>("A", "aaa"),
    new ImmutablePair<>("B", "bbb")
);

And you now want a Map of the Pair's key to the Pair object.

Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {

  @Override
  public String transform(Pair<String, String> input) {
    return input.getKey();
  }
});

System.out.println(map);

gives output:

{A=(A,aaa), B=(B,bbb)}

That being said, a for loop is maybe easier to understand. (This below gives the same output):

Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
  map.put(pair.getKey(), pair);
}
System.out.println(map);

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

The Ruby-way (TM) since Ruby 2.3: Use the squiggly HEREDOC <<~ to define a multi-line string with newlines and proper indentation:

conn.exec <<~EOS
            select attr1, attr2, attr3, attr4, attr5, attr6, attr7
            from table1, table2, table3, etc, etc, etc, etc, etc
            where etc etc etc etc etc etc etc etc etc etc etc etc etc
          EOS

# -> "select...\nfrom...\nwhere..."

If proper indentation is not a concern, then single and double quotes can span multiple lines in Ruby:

conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7 
           from table1, table2, table3, etc, etc, etc, etc, etc, 
           where etc etc etc etc etc etc etc etc etc etc etc etc etc"    

# -> "select...\n           from...\n           where..."
      

If single or double quotes are cumbersome because that would need lots of escaping, then the percent string literal notation % is the most flexible solution:

conn.exec %(select attr1, attr2, attr3, attr4, attr5, attr6, attr7
            from table1, table2, table3, etc, etc, etc, etc, etc
            where (ProductLine = 'R' OR ProductLine = "S") AND Country = "...")
# -> "select...\n            from...\n            where..."

If the aim is to avoid the newlines (which both the squiggly HEREDOC, quotes and the percent string literal will cause), then a line continuation can be used by putting a backslash \ as the last non-whitespace character in a line. This will continue the line and will cause Ruby to concatenate the Strings back to back (watch out for those spaces inside the quoted string):

conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' \
          'from table1, table2, table3, etc, etc, etc, etc, etc, ' \
          'where etc etc etc etc etc etc etc etc etc etc etc etc etc'

# -> "select...from...where..."

If you use Rails, then String.squish will strip the string of leading and trailing space and collapse all consecutive whitespaces (newlines, tabs, and all) into a single space:

conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7 
           from table1, table2, table3, etc, etc, etc, etc, etc, 
           where etc etc etc etc etc etc etc etc etc etc etc etc etc".squish

# -> "select...attr7 from...etc, where..."

More details:

Ruby HEREDOC Syntax

The Here Document Notation for Strings is a way to designate long blocks of text inline in code. It is started by << followed by a user-defined String (the End of String terminator). All following lines are concatenated until the End of String terminator is found at the very beginning of a line:

puts <<HEREDOC 
Text Text Text Text
Bla Bla
HEREDOC
# -> "Text Text Text Text\nBlaBla"

The End of String terminator can be chosen freely, but it is common to use something like "EOS" (End of String) or something that matches the domain of the String such as "SQL".

HEREDOC supports interpolation by default or when the EOS terminator is double quoted:

price = 10
print <<"EOS"  # comments can be put here
1.) The price is #{price}.
EOS
# -> "1.) The price is 10."

Interpolation can be disabled if the EOS terminator is single quoted:

print <<'EOS' # Disabled interpolation
3.) The price is #{price}.
EOS
# -> "3.) The price is #{price}."

One important restriction of the <<HEREDOC is that the End of String terminator needs to be at the beginning of the line:

  puts <<EOS 
    def foo
      print "foo"
    end
  EOS
EOS
#-> "....def foo\n......print "foo"\n....end\n..EOS"

To get around this, the <<- syntax was created. It allows the EOS terminator to be indented to make the code look nicer. The lines between the <<- and EOS terminator are still used in their full extend including all indentation:

def printExample
  puts <<-EOS # Use <<- to indent End of String terminator
    def foo
      print "foo"
    end
  EOS
end
# -> "....def foo\n......print "foo"\n....end"

Since Ruby 2.3, we now have the squiggly HEREDOC <<~ removes leading whitespace:

puts <<~EOS # Use the squiggly HEREDOC <<~ to remove leading whitespace (since Ruby 2.3!)
  def foo
    print "foo"
  end
EOS
# -> "def foo\n..print "foo"\nend"

Empty lines and lines which only contains tabs and space are ignored by <<~

puts <<~EOS.inspect 
  Hello

    World!
EOS
#-> "Hello\n..World!"

If both tabs and spaces are used, tabs are considered as equal to 8 spaces. If the least-indented line is in the middle of a tab, this tab is not removed.

puts <<~EOS.inspect
<tab>One Tab
<space><space>Two Spaces
EOS
# -> "\tOne Tab\nTwoSpaces"

HEREDOC can do some crazy stuff such as executing commands using backticks:

puts <<`EOC`            
echo #{price}
echo #{price * 2}
EOC

HEREDOC String definitions can be "stacked", which means that the first EOS terminator (EOSFOO below) will end the first string and start the second (EOSBAR below):

print <<EOSFOO, <<EOSBAR    # you can stack them
I said foo.
EOSFOO
I said bar.
EOSBAR

I don't think anybody would ever use it as such, but the <<EOS is really just a string literal and can be put whereever a string can normally be put:

def func(a,b,c)
  puts a
  puts b
  puts c
end

func(<<THIS, 23, <<THAT) 
Here's a line
or two.
THIS
and here's another.
THAT

If you don't have Ruby 2.3, but Rails >= 3.0 then you can use String.strip_heredoc which does the same as <<~

# File activesupport/lib/active_support/core_ext/string/strip.rb, line 22
class String
  def strip_heredoc
    gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze)
  end
end

puts <<-USAGE.strip_heredoc # If no Ruby 2.3, but Rails >= 3.0
  This command does such and such.

  Supported options are:
    -h         This message
    ...
USAGE

Troubleshooting

If you see errors when Ruby parses your file, then it is most likely that you either have extra leading or trailing spaces with a HEREDOC or extra trailing spaces with a squiggly HEREDOC. For example:

What you see:

    database_yml = <<~EOS
      production:
        database: #{fetch(:user)}
        adapter: postgresql
        pool: 5
        timeout: 5000
    EOS  

What Ruby tells you:

SyntaxError: .../sample.rb:xx: can't find string "EOS" anywhere before EOF
...sample.rb:xx: syntax error, unexpected end-of-input, expecting `end'

What is at fault:

Spot the extra spaces after the terminating EOS

Spot the extra spaces after the terminating EOS.

Percent String Literals

See RubyDoc for how to use the percentage sign followed by a string in a parentheses pair such as a %(...), %[...], %{...}, etc. or a pair of any non-alphanumeric character such as %+...+

Last Words

Last, to get the answer to the original question "Is there a way to imply concatenation?" answered: Ruby always implies concatenation if two strings (single and double quoted) are found back to back:

puts "select..." 'from table...' "where..."
# -> "select...from table...where..."

The caveat is that this does not work across line-breaks, because Ruby is interpreting an end of statement and the consequitive line of just strings alone on a line doesn't do anything.

NodeJS: How to get the server's port?

Requiring the http module was never necessary.

An additional import of http is not necessary in Express 3 or 4. Assigning the result of listen() is enough.

var server = require('express')();

server.get('/', function(req, res) {
  res.send("Hello Foo!");
});

var listener = server.listen(3000);
console.log('Your friendly Express server, listening on port %s', listener.address().port);
// Your friendly Express server, listening on port 3000

Again, this is tested in Express 3.5.1 & 4.0.0. Importing http was never necessary. The listen method returns an http server object. https://github.com/visionmedia/express/blob/master/lib/application.js#L531

VBA equivalent to Excel's mod function

Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
    Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function

This function always works and is the exact copy of the Excel function.

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

Curl command line for consuming webServices?

Posting a string:

curl -d "String to post" "http://www.example.com/target"

Posting the contents of a file:

curl -d @soap.xml "http://www.example.com/target"

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

Java ArrayList - how can I tell if two lists are equal, order not mattering?

I'd say these answers miss a trick.

Bloch, in his essential, wonderful, concise Effective Java, says, in item 47, title "Know and use the libraries", "To summarize, don't reinvent the wheel". And he gives several very clear reasons why not.

There are a few answers here which suggest methods from CollectionUtils in the Apache Commons Collections library but none has spotted the most beautiful, elegant way of answering this question:

Collection<Object> culprits = CollectionUtils.disjunction( list1, list2 );
if( ! culprits.isEmpty() ){
  // ... do something with the culprits, i.e. elements which are not common

}

Culprits: i.e. the elements which are not common to both Lists. Determining which culprits belong to list1 and which to list2 is relatively straightforward using CollectionUtils.intersection( list1, culprits ) and CollectionUtils.intersection( list2, culprits ).
However it tends to fall apart in cases like { "a", "a", "b" } disjunction with { "a", "b", "b" } ... except this is not a failing of the software, but inherent to the nature of the subtleties/ambiguities of the desired task.

You can always examine the source code (l. 287) for a task like this, as produced by the Apache engineers. One benefit of using their code is that it will have been thoroughly tried and tested, with many edge cases and gotchas anticipated and dealt with. You can copy and tweak this code to your heart's content if need be.


NB I was at first disappointed that none of the CollectionUtils methods provides an overloaded version enabling you to impose your own Comparator (so you can redefine equals to suit your purposes).

But from collections4 4.0 there is a new class, Equator which "determines equality between objects of type T". On examination of the source code of collections4 CollectionUtils.java they seem to be using this with some methods, but as far as I can make out this is not applicable to the methods at the top of the file, using the CardinalityHelper class... which include disjunction and intersection.

I surmise that the Apache people haven't got around to this yet because it is non-trivial: you would have to create something like an "AbstractEquatingCollection" class, which instead of using its elements' inherent equals and hashCode methods would instead have to use those of Equator for all the basic methods, such as add, contains, etc. NB in fact when you look at the source code, AbstractCollection does not implement add, nor do its abstract subclasses such as AbstractSet... you have to wait till the concrete classes such as HashSet and ArrayList before add is implemented. Quite a headache.

In the mean time watch this space, I suppose. The obvious interim solution would be to wrap all your elements in a bespoke wrapper class which uses equals and hashCode to implement the kind of equality you want... then manipulate Collections of these wrapper objects.

How to uninstall Ruby from /usr/local?

Create a symlink at /usr/bin named 'ruby' and point it to the latest installed ruby.

You can use something like ln -s /usr/bin/ruby /to/the/installed/ruby/binary

Hope this helps.

ASP.Net MVC How to pass data from view to controller

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

controller:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

How to upgrade all Python packages with pip

When using a virtualenv and if you just want to upgrade packages added to your virtualenv, you may want to do:

pip install `pip freeze -l | cut --fields=1 -d = -` --upgrade

Need table of key codes for android and presenter

List Of Key codes:

a - z-> 29 - 54

"0" - "9"-> 7 - 16

BACK BUTTON - 4, MENU BUTTON - 82

UP-19, DOWN-20, LEFT-21, RIGHT-22

SELECT (MIDDLE) BUTTON - 23

SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67

How do you update a DateTime field in T-SQL?

When in doubt, be explicit about the data type conversion using CAST/CONVERT:

UPDATE TABLE
   SET EndDate = CAST('2009-05-25' AS DATETIME)
 WHERE Id = 1

How to get the selected radio button’s value?

In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:

var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);

or simpler:

alert(document.theForm.genderS.value);

refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

Finding repeated words on a string and counting the repetitions

as introduction of stream has changed the way we code; i would like to add some of the ways of doing this using it

    String[] strArray = str.split(" ");
    
    //1. All string value with their occurrences
    Map<String, Long> counterMap = 
            Arrays.stream(strArray).collect(Collectors.groupingBy(e->e, Collectors.counting()));

    //2. only duplicating Strings
    Map<String, Long> temp = counterMap.entrySet().stream().filter(map->map.getValue() > 1).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
    System.out.println("test : "+temp);
    
    //3. List of Duplicating Strings
    List<String> masterStrings = Arrays.asList(strArray);
    Set<String> duplicatingStrings = 
            masterStrings.stream().filter(i -> Collections.frequency(masterStrings, i) > 1).collect(Collectors.toSet());

How to pass table value parameters to stored procedure from .net code

Generic

   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
    {
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)
        {
            tbl.Rows.Add(selector.Invoke(item));

        }

        return tbl;

    }

how to set radio button checked in edit mode in MVC razor view

Add checked to both of your radio button. And then show/hide your desired one on document ready.

<div class="form-group">
    <div class="mt-radio-inline" style="padding-left:15px;">
        <label class="mt-radio mt-radio-outline">
            Full Edition
            <input type="radio" value="@((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
        <label class="mt-radio mt-radio-outline">
            Select Modules
            <input type="radio" value="@((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
    </div>
</div>

Convert a JSON String to a HashMap

The following parser reads a file, parses it into a generic JsonElement, using Google's JsonParser.parse method, and then converts all the items in the generated JSON into a native Java List<object> or Map<String, Object>.

Note: The code below is based off of Vikas Gupta's answer.

GsonParser.java

import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

public class GsonParser {
    public static void main(String[] args) {
        try {
            print(loadJsonArray("data_array.json", true));
            print(loadJsonObject("data_object.json", true));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void print(Object object) {
        System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString());
    }

    public static Map<String, Object> loadJsonObject(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToMap(loadJson(filename, isResource).getAsJsonObject());
    }

    public static List<Object> loadJsonArray(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToList(loadJson(filename, isResource).getAsJsonArray());
    }

    private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8"));
    }

    public static Object parse(JsonElement json) {
        if (json.isJsonObject()) {
            return jsonToMap((JsonObject) json);
        } else if (json.isJsonArray()) {
            return jsonToList((JsonArray) json);
        }

        return null;
    }

    public static Map<String, Object> jsonToMap(JsonObject jsonObject) {
        if (jsonObject.isJsonNull()) {
            return new HashMap<String, Object>();
        }

        return toMap(jsonObject);
    }

    public static List<Object> jsonToList(JsonArray jsonArray) {
        if (jsonArray.isJsonNull()) {
            return new ArrayList<Object>();
        }

        return toList(jsonArray);
    }

    private static final Map<String, Object> toMap(JsonObject object) {
        Map<String, Object> map = new HashMap<String, Object>();

        for (Entry<String, JsonElement> pair : object.entrySet()) {
            map.put(pair.getKey(), toValue(pair.getValue()));
        }

        return map;
    }

    private static final List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();

        for (JsonElement element : array) {
            list.add(toValue(element));
        }

        return list;
    }

    private static final Object toPrimitive(JsonPrimitive value) {
        if (value.isBoolean()) {
            return value.getAsBoolean();
        } else if (value.isString()) {
            return value.getAsString();
        } else if (value.isNumber()){
            return value.getAsNumber();
        }

        return null;
    }

    private static final Object toValue(JsonElement value) {
        if (value.isJsonNull()) {
            return null;
        } else if (value.isJsonArray()) {
            return toList((JsonArray) value);
        } else if (value.isJsonObject()) {
            return toMap((JsonObject) value);
        } else if (value.isJsonPrimitive()) {
            return toPrimitive((JsonPrimitive) value);
        }

        return null;
    }
}

FileLoader.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;

public class FileLoader {
    public static Reader openReader(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
        return openReader(filename, isResource, "UTF-8");
    }

    public static Reader openReader(String filename, boolean isResource, String charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
        return new InputStreamReader(openInputStream(filename, isResource), charset);
    }

    public static InputStream openInputStream(String filename, boolean isResource) throws FileNotFoundException, MalformedURLException {
        if (isResource) {
            return FileLoader.class.getClassLoader().getResourceAsStream(filename);
        }

        return new FileInputStream(load(filename, isResource));
    }

    public static String read(String path, boolean isResource) throws IOException {
        return read(path, isResource, "UTF-8");
    }

    public static String read(String path, boolean isResource, String charset) throws IOException {
        return read(pathToUrl(path, isResource), charset);
    }

    @SuppressWarnings("resource")
    protected static String read(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }

    protected static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    protected static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return FileLoader.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }
}

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

row-level trigger vs statement-level trigger

The main difference is not what can be modified by the trigger, that depends on the DBMS. A trigger (row or statement level) may modify one or many rows*, of the same or other tables as well and may have cascading effects (trigger other actions/triggers) but all these depend on the DBMS of course.

The main difference is how many times the trigger is activated. Imagine you have a 1M rows table and you run:

UPDATE t
SET columnX = columnX + 1

A statement-level trigger will be activated once (and even if no rows are updated). A row-level trigger will be activated a million times, once for every updated row.


Another difference is the order or activation. For example in Oracle the 4 different types of triggers will be activated in the following order:

Before the triggering statement executes
Before each row that the triggering statement affects
After each row that the triggering statement affects
After the triggering statement executes

In the previous example, we'd have something like:

Before statement-level trigger executes

  Before row-level trigger executes
  One row is updated
  After row-level trigger executes

  Before row-level trigger executes
  Second row is updated
  After row-level trigger executes

  ...

  Before row-level trigger executes
  Millionth row is updated
  After row-level trigger executes

After statement-level trigger executes

Addendum

* Regarding what rows can be modified by a trigger: Different DBMS have different limitations on this, depending on the specific implementation or triggers in the DBMS. For example, Oracle may show a "mutating table" errors for some cases, e.g. when a row-level trigger selects from the whole table (SELECT MAX(col) FROM tablename) or if it modifies other rows or the whole table and not only the row that is related to / triggered from.

It is perfectly valid of course for a row-level trigger (in Oracle or other) to modify the row that its change has triggered it and that is a very common use. Example in dbfiddle.uk.

Other DBMS may have different limitations on what any type of trigger can do and even what type of triggers are offered (some do not have BEFORE triggers for example, some do not have statement level triggers at all, etc).

SQL SELECT from multiple tables

select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid

How to set HTTP headers (for cache-control)?

For Apache server, you should check mod_expires for setting Expires and Cache-Control headers.

Alternatively, you can use Header directive to add Cache-Control on your own:

Header set Cache-Control "max-age=290304000, public"

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

Build an iOS app without owning a mac?

On Windows, you can use Mac on a virtual machine (this probably also works on Linux but I haven't tested). A virtual machine is basically a program that you run on your computer that allows you to run one OS in a window inside another one. Make sure you have at least 60GB free space on your hard drive. The virtual hard drive that you will download takes up 10GB initially but when you've installed all the necessary programs for developing iOS apps its size can easily increase to 50GB (I recommend leaving a few GBs margin just in case).

Here are some detailed steps for how install a Mac virtual machine on Windows:

  1. Install VirtualBox.

  2. You have to enable virtualization in the BIOS. To open the BIOS on Windows 10, you need to start by holding down the Shift key while pressing the Restart button in the start menu. Then you will get a blue screen with some options. Choose "Troubleshoot", then "Advanced options", then "UEFI Firmware Settings", then "Restart". Then your computer will restart and open the BIOS directly. On older versions of Windows, shut down the computer normally, hold the F2 key down, start your computer again and don't release F2 until you're in the BIOS. On some computers you may have to hold down another key than F2.

  3. Now that you're in the BIOS, you need to enable virtualization. Which setting you're supposed to change depends on which computer you're using. This may vary even between two computers with the same version of Windows. On my computer, you need to set Intel Virtual Technology in the Configuration tab to Enabled. On other computers it may be in for example Security -> Virtualization or in Advanced -> CPU Setup. If you can't find any of these options, search Google for enable virtualization (the kind of computer you have). Don't change anything in the BIOS just like that at random because otherwise it could cause problems on your computer. When you've enabled virtualization, save the changes and exit the BIOS. This is usually done in the Exit tab.

  4. Download this file (I have no association with the person who uploaded it, but I've used it myself so I'm sure there are no viruses). If the link gets broken, post a comment to let me know and I will try to upload the file somewhere else. The password to open the 7Z file is stackoverflow.com. This 7Z file contains a VMDK file which will act as the hard drive for the Mac virtual machine. Extract that VMDK file. If disk space is an issue for you, once you've extracted the VMDK file, you can delete the 7Z file and therefore save 7GB.

  5. Open VirtualBox that you installed in step 1. In the toolbar, press the New button. Then choose a name for your virtual machine (the name is unimportant, I called it "Mac"). In "Type", select "Mac OS X" and in "Version" select "macOS 10.13 High Sierra (64 bit)" (the Mac version you will install on the virtual machine is actually Catalina, but VirtualBox doesn't have that option yet and it works just fine if VirtualBox thinks it's High Sierra).

    It's also a good idea (though not required) to move the VMDK file you extracted in step 4 to the folder listed under "Machine Folder" (in the screenshot above that would be C:\Users\myname\VirtualBox VMs).

  6. Select the amount of memory that your virtual machine can use. Try to balance the amount because too little memory will result in the virtual machine having low performance and a too much memory will result making your host system (Windows) run out of memory which will cause the virtual machine and/or other programs that you're running on Windows to crash. On a computer with 4GB available memory, 2GB was a good amount. Don't worry if you select a bad amount, you will be able to change it whenever you want (except when the virtual machine is running).

  7. In the Hard disk step, choose "Use an existing virtual hard disk file" and click on the little folder icon to the right of the drop list. That will open a new window. In that new window, click on the "Add" button on the top left, which will open a browse window. Select the VMDK file that you downloaded and extracted in step 4, then click "Choose".

    When you're done with this, click "Create".

  8. Select the virtual machine in the list on the left of the window and click on the Settings button in the toolbar. In System -> Processor, select 2 CPUs; and in Network -> Attached to, select Bridged Adapter. If you realize later that you selected an amount of memory in step 6 that causes problems, you can change it in System -> Motherboard. When you're done changing the settings, click OK.

  9. Open the command prompt (C:\Windows\System32\cmd.exe). Run the following commands in there, replacing "Your VM Name" with whatever you called your virtual machine in step 5 (for example "Mac") (keep the quotation marks):

    cd "C:\Program Files\Oracle\VirtualBox\"
    VBoxManage.exe modifyvm "Your VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
    VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemSerial" C02L280HFMR7
    
  10. Now everything is ready for you to use the virtual machine. In VirtualBox, click on the Start button and follow the installation instructions for Mac. Once you've installed Mac on the virtual machine, you can develop your iOS app just like if you had a real Mac.

Remark: If you want to save space on your hard disk, you can compress the VMDK file that you extracted in step 4 and used in step 7. To do this, right click on it, select Properties, click on the Advanced... button on the bottom right, and check the checkbox "Compress contents to save disk space". This will make this very large file take less disk space without making anything work less well. I did it and it reduced the disk size of the VMDK file from 50GB to 40GB without losing any data.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Change the background color of a pop-up dialog

To change the background color of all dialogs and pop-ups in your app, use colorBackgroundFloating attribute.

<style name="MyApplicationTheme" parent="@style/Theme.AppCompat.NoActionBar">
...
<item name="colorBackgroundFloating">
    @color/background</item>
<item name="android:colorBackgroundFloating" tools:targetApi="23">
    @color/background</item>
...
</style>

Documentation:

colorBackgroundFloating

Convert Little Endian to Big Endian

You can use the lib functions. They boil down to assembly, but if you are open to alternate implementations in C, here they are (assuming int is 32-bits) :

void byte_swap16(unsigned short int *pVal16) {

//#define method_one 1
// #define method_two 1
#define method_three 1
#ifdef method_one
    unsigned char *pByte;

    pByte = (unsigned char *) pVal16;
    *pVal16 = (pByte[0] << 8) | pByte[1];
#endif

#ifdef method_two
    unsigned char *pByte0;
    unsigned char *pByte1;

    pByte0 = (unsigned char *) pVal16;
    pByte1 = pByte0 + 1;
    *pByte0 = *pByte0 ^ *pByte1;
    *pByte1 = *pByte0 ^ *pByte1;
    *pByte0 = *pByte0 ^ *pByte1;
#endif

#ifdef method_three
    unsigned char *pByte;

    pByte = (unsigned char *) pVal16;
    pByte[0] = pByte[0] ^ pByte[1];
    pByte[1] = pByte[0] ^ pByte[1];
    pByte[0] = pByte[0] ^ pByte[1];
#endif


}



void byte_swap32(unsigned int *pVal32) {

#ifdef method_one
    unsigned char *pByte;

    // 0x1234 5678 --> 0x7856 3412  
    pByte = (unsigned char *) pVal32;
    *pVal32 = ( pByte[0] << 24 ) | (pByte[1] << 16) | (pByte[2] << 8) | ( pByte[3] );
#endif

#if defined(method_two) || defined (method_three)
    unsigned char *pByte;

    pByte = (unsigned char *) pVal32;
    // move lsb to msb
    pByte[0] = pByte[0] ^ pByte[3];
    pByte[3] = pByte[0] ^ pByte[3];
    pByte[0] = pByte[0] ^ pByte[3];
    // move lsb to msb
    pByte[1] = pByte[1] ^ pByte[2];
    pByte[2] = pByte[1] ^ pByte[2];
    pByte[1] = pByte[1] ^ pByte[2];
#endif
}

And the usage is performed like so:

unsigned short int u16Val = 0x1234;
byte_swap16(&u16Val);
unsigned int u32Val = 0x12345678;
byte_swap32(&u32Val);

How do I decompile a .NET EXE into readable C# source code?

When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.

From the ILSpy website (https://github.com/icsharpcode/ILSpy/):

ILSpy is the open-source .NET assembly browser and decompiler.

ILSpy Features

  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
  • Supports lambdas and 'yield return'
  • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Update:

April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:

  • Assembly Lists
  • Support for decompiling Expression trees
  • Support for lifted operatores on nullables
  • Decompile to Visual Basic
  • Search for multiple strings separated by space (searching for "Assembly manager" in ILSpy.exe would find AssemblyListManager)
  • Clicking on a local variable will highlight all other occurrences of that variable
  • Ctrl+F can be used to search within the decompiled code view

Update:

  • ILSpy 2.1 supports async/await decompilation

JSON.NET Error Self referencing loop detected for type

You can apply an attribute to the property too. The [JsonProperty( ReferenceLoopHandling = ... )] attribute is well suited to this.

For example:

/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
    // ...code omitted for brevity...

    /// <summary>
    /// An inner (nested) error.
    /// </summary>
    [JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
    public ExceptionInfo Inner { get; set; }

    // ...code omitted for brevity...    
}

Hope that helps, Jaans

Show all current locks from get_lock

I found following way which can be used if you KNOW name of lock

select IS_USED_LOCK('lockname');

however i not found any info about how to list all names.

Declare and assign multiple string variables at the same time

You can to do it this way:

string Camnr = "", Klantnr = "", ... // or String.Empty

Or you could declare them all first and then in the next line use your way.

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

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

  • Step-1 Clean your
    .m2/repository

  • Step-2 execute the maven command(for example mvn clean verify) from the terminal at the current project location(where your project's pom.xml file exist) instead of running maven from eclipse.
  • How do files get into the External Dependencies in Visual Studio C++?

    The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

    You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

    Get div height with plain JavaScript

    var myDiv = document.getElementById('myDiv'); //get #myDiv
    alert(myDiv.clientHeight);
    

    clientHeight and clientWidth are what you are looking for.

    offsetHeight and offsetWidth also return the height and width but it includes the border and scrollbar. Depending on the situation, you can use one or the other.

    Hope this helps.

    How to load local html file into UIWebView

    Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.

    Java: Enum parameter in method

    I like this a lot better. reduces the if/switch, just do.

    private enum Alignment { LEFT, RIGHT;
    
    void process() {
    //Process it...
    } 
    };    
    String drawCellValue (int maxCellLength, String cellValue, Alignment align){
      align.process();
    }
    

    of course, it can be:

    String process(...) {
    //Process it...
    } 
    

    Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

    Horizontal centering is easy: text-align: center;. Vertical centering of text inside an element can be done by setting line-height equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.

    Better is to set line-height equal to font-size (or slightly smaller) and use padding. You'll have to adjust your height to accomodate.

    Here's a CSS-only, single <div> solution that looks pretty iPhone-like. They expand with content.

    Demo: http://jsfiddle.net/ThinkingStiff/mLW47/

    Output:

    enter image description here

    CSS:

    .badge {
        background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
        background-color: red;
        border: 2px solid white;
        border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
        box-shadow: 1px 1px 1px black;
        color: white;
        font: bold 15px/13px Helvetica, Verdana, Tahoma;
        height: 16px; 
        min-width: 14px;
        padding: 4px 3px 0 3px;
        text-align: center;
    }
    

    HTML:

    <div class="badge">1</div>
    <div class="badge">2</div>
    <div class="badge">3</div>
    <div class="badge">44</div>
    <div class="badge">55</div>
    <div class="badge">666</div>
    <div class="badge">777</div>
    <div class="badge">8888</div>
    <div class="badge">9999</div>
    

    Setting mime type for excel document

    For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

    I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

    Bubble Sort Homework

    def bubbleSort ( arr ):
        swapped = True 
        length = len ( arr )
        j = 0
    
        while swapped:
            swapped = False
            j += 1 
            for i in range ( length  - j ):
                if arr [ i ] > arr [ i + 1 ]:
                    # swap
                    tmp = arr [ i ]
                    arr [ i ] = arr [ i + 1]
                    arr [ i + 1 ] = tmp 
    
                    swapped = True
    
    if __name__ == '__main__':
        # test list
        a = [ 67, 45, 39, -1, -5, -44 ];
    
        print ( a )
        bubbleSort ( a )
        print ( a )
    

    Get file size before uploading

    For the HTML bellow

    <input type="file" id="myFile" />
    

    try the following:

    //binds to onchange event of your input field
    $('#myFile').bind('change', function() {
    
      //this.files[0].size gets the size of your file.
      alert(this.files[0].size);
    
    });
    

    See following thread:

    How to check file input size with jQuery?

    Random numbers with Math.random() in Java

    int i = (int) (10 +Math.random()*11);
    

    this will give you random number between 10 to 20.

    the key here is:

    a + Math.random()*b
    

    a starting num (10) and ending num is max number (20) - a (10) + 1 (11)

    Enjoy!

    Storing Python dictionaries

    For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

    Python 2.7.x example.

    import ConfigParser
    
    config = ConfigParser.ConfigParser()
    
    dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
    dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
    dict3 = {'x':1, 'y':2, 'z':3}
    
    # Make each dictionary a separate section in the configuration
    config.add_section('dict1')
    for key in dict1.keys():
        config.set('dict1', key, dict1[key])
       
    config.add_section('dict2')
    for key in dict2.keys():
        config.set('dict2', key, dict2[key])
    
    config.add_section('dict3')
    for key in dict3.keys():
        config.set('dict3', key, dict3[key])
    
    # Save the configuration to a file
    f = open('config.ini', 'w')
    config.write(f)
    f.close()
    
    # Read the configuration from a file
    config2 = ConfigParser.ConfigParser()
    config2.read('config.ini')
    
    dictA = {}
    for item in config2.items('dict1'):
        dictA[item[0]] = item[1]
    
    dictB = {}
    for item in config2.items('dict2'):
        dictB[item[0]] = item[1]
    
    dictC = {}
    for item in config2.items('dict3'):
        dictC[item[0]] = item[1]
    
    print(dictA)
    print(dictB)
    print(dictC)
    

    Python 3.X example.

    import configparser
    
    config = configparser.ConfigParser()
    
    dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
    dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
    dict3 = {'x':1, 'y':2, 'z':3}
    
    # Make each dictionary a separate section in the configuration
    config['dict1'] = dict1
    config['dict2'] = dict2
    config['dict3'] = dict3
    
    # Save the configuration to a file
    f = open('config.ini', 'w')
    config.write(f)
    f.close()
    
    # Read the configuration from a file
    config2 = configparser.ConfigParser()
    config2.read('config.ini')
    
    # ConfigParser objects are a lot like dictionaries, but if you really
    # want a dictionary you can ask it to convert a section to a dictionary
    dictA = dict(config2['dict1'] )
    dictB = dict(config2['dict2'] )
    dictC = dict(config2['dict3'])
    
    print(dictA)
    print(dictB)
    print(dictC)
    

    Console output

    {'key2': 'keyinfo2', 'key1': 'keyinfo'}
    {'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
    {'z': '3', 'y': '2', 'x': '1'}
    

    Contents of config.ini

    [dict1]
    key2 = keyinfo2
    key1 = keyinfo
    
    [dict2]
    k1 = hot
    k2 = cross
    k3 = buns
    
    [dict3]
    z = 3
    y = 2
    x = 1
    

    How to get the last day of the month?

    This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.

    # Some random date.
    some_date = datetime.date(2012, 5, 23)
    
    # Get last weekday
    last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()
    
    print last_weekday
    31
    

    The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.

    The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.

    Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

    It's also a good idea to make sure you're using the correct version of jQuery. I had recently acquired a project using jQuery 1.6.2 that wasn't working with the hoverIntent plugin. Upgrading it to the most recent version fixed that for me.

    When to use %r instead of %s in Python?

    The %s specifier converts the object using str(), and %r converts it using repr().

    For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

    Here's an example, using a date:

    >>> import datetime
    >>> d = datetime.date.today()
    >>> str(d)
    '2011-05-14'
    >>> repr(d)
    'datetime.date(2011, 5, 14)'
    

    Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

    Signed versus Unsigned Integers

    Signed integers in C represent numbers. If a and b are variables of signed integer types, the standard will never require that a compiler make the expression a+=b store into a anything other than the arithmetic sum of their respective values. To be sure, if the arithmetic sum would not fit into a, the processor might not be able to put it there, but the standard would not require the compiler to truncate or wrap the value, or do anything else for that matter if values that exceed the limits for their types. Note that while the standard does not require it, C implementations are allowed to trap arithmetic overflows with signed values.

    Unsigned integers in C behave as abstract algebraic rings of integers which are congruent modulo some power of two, except in scenarios involving conversions to, or operations with, larger types. Converting an integer of any size to a 32-bit unsigned type will yield the member corresponding to things which are congruent to that integer mod 4,294,967,296. The reason subtracting 3 from 2 yields 4,294,967,295 is that adding something congruent to 3 to something congruent to 4,294,967,295 will yield something congruent to 2.

    Abstract algebraic rings types are often handy things to have; unfortunately, C uses signedness as the deciding factor for whether a type should behave as a ring. Worse, unsigned values are treated as numbers rather than ring members when converted to larger types, and unsigned values smaller than int get converted to numbers when any arithmetic is performed upon them. If v is a uint32_t which equals 4,294,967,294, then v*=v; should make v=4. Unfortunately, if int is 64 bits, then there's no telling what v*=v; could do.

    Given the standard as it is, I would suggest using unsigned types in situations where one wants the behavior associated with algebraic rings, and signed types when one wants to represent numbers. It's unfortunate that C drew the distinctions the way it did, but they are what they are.

    Saving timestamp in mysql table using php

    pass like this

    date('Y-m-d H:i:s','1299762201428')
    

    How can I check if two segments intersect?

    Since you do not mention that you want to find the intersection point of the line, the problem becomes simpler to solve. If you need the intersection point, then the answer by OMG_peanuts is a faster approach. However, if you just want to find whether the lines intersect or not, you can do so by using the line equation (ax + by + c = 0). The approach is as follows:

    1. Let's start with two line segments: segment 1 and segment 2.

      segment1 = [[x1,y1], [x2,y2]]
      segment2 = [[x3,y3], [x4,y4]]
      
    2. Check if the two line segments are non zero length line and distinct segments.

    3. From hereon, I assume that the two segments are non-zero length and distinct. For each line segment, compute the slope of the line and then obtain the equation of a line in the form of ax + by + c = 0. Now, compute the value of f = ax + by + c for the two points of the other line segment (repeat this for the other line segment as well).

      a2 = (y3-y4)/(x3-x4);
      b1 = -1;
      b2 = -1;
      c1 = y1 - a1*x1;
      c2 = y3 - a2*x3;
      // using the sign function from numpy
      f1_1 = sign(a1*x3 + b1*y3 + c1);
      f1_2 = sign(a1*x4 + b1*y4 + c1);
      f2_1 = sign(a2*x1 + b2*y1 + c2);
      f2_2 = sign(a2*x2 + b2*y2 + c2);
      
    4. Now all that is left is the different cases. If f = 0 for any point, then the two lines touch at a point. If f1_1 and f1_2 are equal or f2_1 and f2_2 are equal, then the lines do not intersect. If f1_1 and f1_2 are unequal and f2_1 and f2_2 are unequal, then the line segments intersect. Depending on whether you want to consider the lines which touch as "intersecting" or not, you can adapt your conditions.

    Structs in Javascript

    The only difference between object literals and constructed objects are the properties inherited from the prototype.

    var o = {
      'a': 3, 'b': 4,
      'doStuff': function() {
        alert(this.a + this.b);
      }
    };
    o.doStuff(); // displays: 7
    

    You could make a struct factory.

    function makeStruct(names) {
      var names = names.split(' ');
      var count = names.length;
      function constructor() {
        for (var i = 0; i < count; i++) {
          this[names[i]] = arguments[i];
        }
      }
      return constructor;
    }
    
    var Item = makeStruct("id speaker country");
    var row = new Item(1, 'john', 'au');
    alert(row.speaker); // displays: john
    

    Is Unit Testing worth the effort?

    If you are using NUnit one simple but effective demo is to run NUnit's own test suite(s) in front of them. Seeing a real test suite giving a codebase a workout is worth a thousand words...

    Numpy: Divide each row by a vector element

    JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.

    data = np.array([[1,1,1],[2,2,2],[3,3,3]])
    vector = np.array([1,2,3])
    
    data
    # array([[1, 1, 1],
    #        [2, 2, 2],
    #        [3, 3, 3]])
    vector
    # array([1, 2, 3])
    
    data.shape
    # (3, 3)
    vector.shape
    # (3,)
    
    data / vector.reshape((3,1))
    # array([[1, 1, 1],
    #        [1, 1, 1],
    #        [1, 1, 1]])
    

    Performing the reshape() allows the dimensions to line up for broadcasting:

    data:            3 x 3
    vector:              3
    vector reshaped: 3 x 1
    

    Note that data/vector is ok, but it doesn't get you the answer that you want. It divides each column of array (instead of each row) by each corresponding element of vector. It's what you would get if you explicitly reshaped vector to be 1x3 instead of 3x1.

    data / vector
    # array([[1, 0, 0],
    #        [2, 1, 0],
    #        [3, 1, 1]])
    data / vector.reshape((1,3))
    # array([[1, 0, 0],
    #        [2, 1, 0],
    #        [3, 1, 1]])
    

    In Windows cmd, how do I prompt for user input and use the result in another command?

    @echo off
    :start
    set /p var1="Enter first number: "
    pause
    

    how to do bitwise exclusive or of two strings in python?

    Here is your string XOR'er, presumably for some mild form of encryption:

    >>> src = "Hello, World!"
    >>> code = "secret"
    >>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100))
    >>> encrypt = xorWord(src, code)
    >>> encrypt
    ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
    >>> decrypt = xorWord(encrypt,code)
    >>> print decrypt
    Hello, World!
    

    Note that this is an extremely weak form of encryption. Watch what happens when given a blank string to encode:

    >>> codebreak = xorWord("      ", code)
    >>> print codebreak
    SECRET
    

    How do I import CSV file into a MySQL table?

    The mysql command line is prone to too many problems on import. Here is how you do it:

    • use excel to edit the header names to have no spaces
    • save as .csv
    • use free Navicat Lite Sql Browser to import and auto create a new table (give it a name)
    • open the new table insert a primary auto number column for ID
    • change the type of the columns as desired.
    • done!

    OpenCV get pixel channel value from Mat image

    The below code works for me, for both accessing and changing a pixel value.

    For accessing pixel's channel value :

    for (int i = 0; i < image.cols; i++) {
        for (int j = 0; j < image.rows; j++) {
            Vec3b intensity = image.at<Vec3b>(j, i);
            for(int k = 0; k < image.channels(); k++) {
                uchar col = intensity.val[k]; 
            }   
        }
    }
    

    For changing a pixel value of a channel :

    uchar pixValue;
    for (int i = 0; i < image.cols; i++) {
        for (int j = 0; j < image.rows; j++) {
            Vec3b &intensity = image.at<Vec3b>(j, i);
            for(int k = 0; k < image.channels(); k++) {
                // calculate pixValue
                intensity.val[k] = pixValue;
            }
         }
    }
    

    `

    Source : Accessing pixel value

    Converting string to Date and DateTime

    To parse the date, you should use: DateTime::createFromFormat();

    Ex:

    $dateDE = "16/10/2013";
    $dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
    

    However, careful, because this will crash with:

    PHP Fatal error: Call to a member function format() on a non-object 
    

    You actually need to check that the formatting went fine, first:

    $dateDE = "16/10/2013";
    $dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
    if (!$dateObj)
    {
        throw new \UnexpectedValueException("Could not parse the date: $date");
    }
    $dateUS = $dateObj->format("m/d/Y");
    

    Now instead of crashing, you will get an exception, which you can catch, propagate, etc.

    $dateDE has the wrong format, it should be "16.10.2013";

    Embedding Base64 Images

    Update: 2017-01-10

    Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.

    http://caniuse.com/#feat=datauri


    Data URIs are now supported by the following web browsers:

    • Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
    • Konqueror, via KDE's KIO slaves input/output system
    • Opera (including devices such as the Nintendo DSi or Wii)
    • WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
    • Trident
      • Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
      • Data URIs are supported only for the following elements and/or attributes[4]:
        • object (images only)
        • img
        • input type=image
        • link
      • CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
      • Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
      • TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme

    http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

    How to make spring inject value into a static field

    As these answers are old, I found this alternative. It is very clean and works with just java annotations:

    To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class GlobalValue {
    
    public static String DATABASE;
    
    @Value("${mongodb.db}")
    public void setDatabase(String db) {
        DATABASE = db;
    }
    }
    

    https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

    Detect if user is scrolling

    window.addEventListener("scroll",function(){
        window.lastScrollTime = new Date().getTime()
    });
    function is_scrolling() {
        return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
    }
    

    Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".

    (addEventListener is better than onScroll because the former can coexist nicely with any other code that uses onScroll.)

    Error Dropping Database (Can't rmdir '.test\', errno: 17)

    just go to data directory in my case path is "wamp\bin\mysql\mysql5.6.17\data" here you will see all databases folder just delete this your database folder the db will automatically drooped :)

    String.Replace(char, char) method in C#

    If you use

    string temp = mystring.Replace("\r\n", "").Replace("\n", "");
    

    then you won't have to worry about where your string is coming from.

    Including a css file in a blade template?

    You should try this :

    {{ Html::style('css/styles.css') }}
    

    OR

    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">
    

    Hope this help for you !!!

    SQL Server: how to create a stored procedure

    Create this way.

    Create procedure dept_count(dept_name varchar(20),d_count integer)
       begin
         select count(*) into d_count
         from instructor
         where instructor.dept_name=dept_count.dept_name
       end
    

    Remove NA values from a vector

    You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

    subquery in codeigniter active record

    I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

    $subquery = 'SELECT id_cer FROM revokace';
    
    $this->db->select('*');
    $this->db->where_not_in(id, $subquery);
    $this->db->from('certs');
    $query = $this->db->get();
    

    Count number of times value appears in particular column in MySQL

    Take a look at the Group by function.

    What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.

    MySQL Documentation

    You can also use the group by function with a good number of other function define by MySQL (see the above link).

    mysql> SELECT student_name, AVG(test_score)
        ->        FROM student
        ->        GROUP BY student_name;
    

    Defining and using a variable in batch file

    input location.bat

    @echo off
    cls
    
    set /p "location"="bob"
    echo We're working with %location%
    pause
    

    output

    We're working with bob
    

    (mistakes u done : space and " ")

    registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

    So it turns out that because AnyObject is the spiritual successor to id, you can call any message you want on AnyObject. That's the equivalent of sending a message to id. Ok, fair enough. But now we add in the concept that all methods are optional on AnyObject, and we have something we can work with.

    Given the above, I was hopeful I could just cast UIApplication.sharedApplication() to AnyObject, then create a variable equal to the method signature, set that variable to the optional method, then test the variable. This didn't seem to work. My guess is that when compiled against the iOS 8.0 SDK, the compiler knows where it thinks that method should be, so it optimizes this all down to a memory lookup. Everything works fine until I try to test the variable, at which point I get a EXC_BAD_ACCESS.

    However, in the same WWDC talk where I found the gem about all methods being optional, they use Optional Chaining to call an optional method - and this seems to work. The lame part is that you have to actually attempt to call the method in order to know if it exists, which in the case of registering for notifications is a problem because you're trying to figure out if this method exists before you go creating a UIUserNotificationSettings object. It seems like calling that method with nil though is okay, so the solution that seems to be working for me is:

    var ao: AnyObject = UIApplication.sharedApplication()
    if let x:Void = ao.registerUserNotificationSettings?(nil) {
        // It's iOS 8
        var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
        var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    } else {
        // It's older
        var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
    }
    

    After much searching related to this, the key info came from this WWDC talk https://developer.apple.com/videos/wwdc/2014/#407 right in the middle at the section about "Optional Methods in Protocols"

    In Xcode 6.1 beta the above code does not work anymore, the code below works:

       if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
            // It's iOS 8
            var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
           var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
           UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        } else {
            // It's older
            var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
            UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
        }
    

    Java enum with multiple value types

    First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

    Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

    Here's how you should do it with all the suggestions above:

    public enum States {
        ...
        MASSACHUSETTS("Massachusetts",  "MA",   true),
        MICHIGAN     ("Michigan",       "MI",   false),
        ...; // all 50 of those
    
        private final String full;
        private final String abbr;
        private final boolean originalColony;
    
        private States(String full, String abbr, boolean originalColony) {
            this.full = full;
            this.abbr = abbr;
            this.originalColony = originalColony;
        }
    
        public String getFullName() {
            return full;
        }
    
        public String getAbbreviatedName() {
            return abbr;
        }
    
        public boolean isOriginalColony(){
            return originalColony;
        }
    }
    

    PHP How to fix Notice: Undefined variable:

    It looks like you don't have any records that match your query, so you'd want to return an empty array (or null or something) if the number of rows == 0.

    How to convert upper case letters to lower case

    You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.

    w.strip(',.').lower()
    

    How to clear APC cache entries?

    A good solution for me was to simply not using the outdated user cache any more after deploy.

    If you add prefix to each of you keys you can change the prefix on changing the data structure of cache entries. This will help you to get the following behavior on deploy:

    1. Don't use outdated cache entries after deploy of only updated structures
    2. Don't clean the whole cache on deploy to not slow down your page
    3. Some old cached entries can be reused after reverting your deploy (If the entries wasn't automatically removed already)
    4. APC will remove old cache entries after expire OR on missing cache space

    This is possible for user cache only.

    How to pass multiple parameters in json format to a web service using jquery?

    Found the solution:

    It should be:

    "{'Id1':'2','Id2':'2'}"
    

    and not

    "{'Id1':'2'},{'Id2':'2'}"
    

    Instantiating a generic class in Java

    I really need to instantiate a T in Foo using a parameter-less constructor

    Simple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.

    How can one work around Java's limitation?

    One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of Foo<T>. Or you could have a method setBar(T theInstanceofT); to get your T instead of instantiating in the class it self.

    How to make padding:auto work in CSS?

    You can reset the padding (and I think everything else) with initial to the default.

    p {
        padding: initial;
    }
    

    Removing leading zeroes from a field in a SQL statement

    select CASE
             WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
               THEN ''
               ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
           END
    

    How to uninstall a Windows Service when there is no executable for it left on the system?

    found here

    I just tried on windows XP, it worked

    local computer: sc \\. delete [service-name]

      Deleting services in Windows Server 2003
    
      We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.
    
      To delete a service: 
    
      Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.
    
      Enter command:
    
      sc servername delete servicename
    
      For instance, sc \\dc delete myservice
    
      (Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)
    
      Below is the official help of all sc functions:
    
      DESCRIPTION:
        SC is a command line program used for communicating with the
        NT Service Controller and services. 
      USAGE:
              sc
    

    ArrayList - How to modify a member of an object?

    Assuming Customer has a setter for email - myList.get(3).setEmail("[email protected]")

    CSS: stretching background image to 100% width and height of screen?

    You need to set the height of html to 100%

    body {
        background-image:url("../images/myImage.jpg");
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }
    html {
        height: 100%
    }
    

    http://jsfiddle.net/8XUjP/

    Checking for Undefined In React

    In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

    if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
        //
    }
    

    And, when an undefined , empty or null value is not expected; you can make it more concise:

    if (nextProps.blog && nextProps.blog.content) {
        //
    }
    

    java.lang.ClassNotFoundException: HttpServletRequest

    I do have same problem when i was trying out with first Spring MVC webapp . What i had done was downloaded the jar files given from the link(Download spring framework). Among the jars on the zip extracted folder,the jar files I was expected to use were

    • org.springframework.asm-3.0.1.RELEASE-A.jar

    • org.springframework.beans-3.0.1.RELEASE-A.jar

    • org.springframework.context-3.0.1.RELEASE-A.jar

    • org.springframework.core-3.0.1.RELEASE-A.jar

    • org.springframework.expression-3.0.1.RELEASE-A.jar

    • org.springframework.web.servlet-3.0.1.RELEASE-A.jar

    • org.springframework.web-3.0.1.RELEASE-A.jar

    But as I get the Error, looking out for solution, I figured out that I also need the following jar too.

    • commons-logging-1.0.4.jar

    • jstl-1.2.jar

    Then I searched and downloaded the two jar files separately and include them in /WEB-INF/lib folder. And finally I was able to get my webapp running using the Tomcat server. :)

    This project references NuGet package(s) that are missing on this computer

    One solution would be to remove from the .csproj file the following:

    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
    <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
      <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
      </PropertyGroup>
      <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
    </Target>
    

    How?

    1. Right click on project. Unload Project.
    2. Right click on project. Edit csproj.
    3. Remove the part from the file. Save.
    4. Right click on project. Reload Project.

    Why does one use dependency injection?

    First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:

    Interfaces are adjectives; classes are nouns.

    (Actually, there are interfaces that are nouns as well, but I want to generalize here.)

    So, e.g. an interface may be something such as IDisposable, IEnumerable or IPrintable. A class is an actual implementation of one or more of these interfaces: List or Map may both be implementations of IEnumerable.

    To get the point: Often your classes depend on each other. E.g. you could have a Database class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class Logger, then Database has a dependency to Logger.

    So far, so good.

    You can model this dependency inside your Database class with the following line:

    var logger = new Logger();
    

    and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...

    And of course you do NOT want to change all your code (meanwhile you have gazillions of it) and replace all lines

    var logger = new Logger();
    

    by:

    var logger = new TcpLogger();
    

    First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?

    Obviously it's a quite good idea to introduce an interface ICanLog (or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:

    ICanLog logger = new Logger();
    

    Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have new Logger() over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:

    ICanLog logger = LoggerFactory.Create();
    

    The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it once: Inside the factory.

    Now, of course, you can generalize this factory, and make it work for any type:

    ICanLog logger = TypeFactory.Create<ICanLog>();
    

    Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!

    To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.

    And now, when you replace names a little bit, you end up with a simple implementation of a Service Locator, which is one of two patterns for Inversion of Control (since you invert control over who decides what exact class to instantiate).

    All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.

    Dependency injection is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.

    With dependency injection, your Database class now has a constructor that requires a parameter of type ICanLog:

    public Database(ICanLog logger) { ... }
    

    Now your database always has a logger to use, but it does not know any more where this logger comes from.

    And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the Application class requires an ICanPersistData implementation, an instance of Database is injected - but for that it must first create an instance of the kind of logger which is configured for ICanLog. And so on ...

    So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).

    In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.

    But basically, that's it.

    P.S.: What I described here is a technique called constructor injection, there is also property injection where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.

    Counting how many times a certain char appears in a string before any other char appears

    The simplest approach would be to use LINQ:

    var count = text.TakeWhile(c => c == '$').Count();
    

    There are certainly more efficient approaches, but that's probably the simplest.

    JRE installation directory in Windows

    In the command line you can type java -version

    Convert XML to JSON (and back) using Javascript

    Xml-to-json library has methods jsonToXml(json) and xmlToJson(xml).

    Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

    Simply fetch the data through this URL:

    http://graph.facebook.com/userid_here/picture

    Replace userid_here with id of the user you want to get the photo of. You can also use HTTPS as well.

    You can use the PHP's file_get_contents function to read that URL and process the retrieved data.

    Resource:

    http://developers.facebook.com/docs/api

    Note: In php.ini, you need to make sure that the OpenSSL extension is enabled to use thefile_get_contents function of PHP to read that URL.

    Python Requests and persistent sessions

    The documentation says that get takes in an optional cookies argument allowing you to specify cookies to use:

    from the docs:

    >>> url = 'http://httpbin.org/cookies'
    >>> cookies = dict(cookies_are='working')
    
    >>> r = requests.get(url, cookies=cookies)
    >>> r.text
    '{"cookies": {"cookies_are": "working"}}'
    

    http://docs.python-requests.org/en/latest/user/quickstart/#cookies

    Cloning a private Github repo

    When cloning from private repos with 2FA enable, there is a simple steps which you need to follow

    1. Go to your Git account
    2. Go to Settings-> Developer Settings->Personal Access Token
    3. Click on Generate new token
    4. Create a token with title you want and with the functionalities
    5. When you are cloning the private repo, by using git clone repoName, after entering your user name, give personal access token as the password.

    Follow same steps when you get Authentication failed error message for Private repo

    Search for a string in Enum and return the Enum

    (MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
    (int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
    

    Javascript sleep/delay/wait function

    Here's a solution using the new async/await syntax.

    async function testWait() {
        alert('going to wait for 5 second');
        await wait(5000);
        alert('finally wait is over');
    }
    
    function wait(time) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    }
    

    Note: You can call function wait only in async functions

    Subset dataframe by multiple logical conditions of rows to remove

    And also

    library(dplyr)
    data %>% filter(!v1 %in% c("b", "d", "e"))
    

    or

    data %>% filter(v1 != "b" & v1 != "d" & v1 != "e")
    

    or

    data %>% filter(v1 != "b", v1 != "d", v1 != "e")
    

    Since the & operator is implied by the comma.

    Div show/hide media query

    It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    

    http://www.w3schools.com/css/css_rwd_viewport.asp

    Parsing domain from a URL

    function getTrimmedUrl($link)
    {
        $str = str_replace(["www.","https://","http://"],[''],$link);
        $link = explode("/",$str);
        return strtolower($link[0]);                
    }
    

    Create an ArrayList of unique values

    You can easily do this with a Hashmap. You obviously have a key (which is the String data) and some values.

    Loop on all your lines and add them to your Map.

    Map<String, List<Integer>> map = new HashMap<>();
    ...
    while (s.hasNext()){
      String stringData = ...
      List<Integer> values = ...
      map.put(stringData,values);
    }
    

    Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData); before putting in the map.

    How to disable right-click context-menu in JavaScript

    If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag

    <body oncontextmenu="return false;">
    

    This will block all access to the context menu (not just from the right mouse button but from the keyboard as well)

    However, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.

    Show / hide div on click with CSS

    You can find <div> by id, look at it's style.display property and toggle it from none to block and vice versa.

    _x000D_
    _x000D_
    function showDiv(Div) {_x000D_
        var x = document.getElementById(Div);_x000D_
        if(x.style.display=="none") {_x000D_
            x.style.display = "block";_x000D_
        } else {_x000D_
            x.style.display = "none";_x000D_
        }_x000D_
    }
    _x000D_
    <div id="welcomeDiv" style="display:none;" class="answer_list">WELCOME</div>_x000D_
    <input type="button" name="answer" value="Show Div" onclick="showDiv('welcomeDiv')" />
    _x000D_
    _x000D_
    _x000D_

    PHP Get all subdirectories of a given directory

    you can use glob() with GLOB_ONLYDIR option

    or

    $dirs = array_filter(glob('*'), 'is_dir');
    print_r( $dirs);
    

    Simple Pivot Table to Count Unique Values

    My approach to this problem was a little different than what I see here, so I'll share.

    1. (Make a copy of your data first)
    2. Concatenate the columns
    3. Remove duplicates on the concatenated column
    4. Last - pivot on the resulting set

    Note: I would like to include images to make this even easier to understand but cant because this is my first post ;)

    What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

    INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

    LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

    RIGHT JOIN is like the above but gets all records in the RIGHT table.

    FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

    What are the new features in C++17?

    Language features:

    Templates and Generic Code

    Lambda

    Attributes

    Syntax cleanup

    Cleaner multi-return and flow control

    • Structured bindings

      • Basically, first-class std::tie with auto
      • Example:
        • const auto [it, inserted] = map.insert( {"foo", bar} );
        • Creates variables it and inserted with deduced type from the pair that map::insert returns.
      • Works with tuple/pair-likes & std::arrays and relatively flat structs
      • Actually named structured bindings in standard
    • if (init; condition) and switch (init; condition)

      • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
      • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
    • Generalizing range-based for loops

      • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
    • if constexpr

      • Much requested feature to simplify almost-generic code.

    Misc

    Library additions:

    Data types

    Invoke stuff

    File System TS v1

    New algorithms

    • for_each_n

    • reduce

    • transform_reduce

    • exclusive_scan

    • inclusive_scan

    • transform_exclusive_scan

    • transform_inclusive_scan

    • Added for threading purposes, exposed even if you aren't using them threaded

    Threading

    (parts of) Library Fundamentals TS v1 not covered above or below

    Container Improvements

    Smart pointer changes

    Other std datatype improvements:

    Misc

    Traits

    Deprecated

    Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

    Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

    Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

    Additional entries pillaged from SD-6 feature-test list.

    clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

    these slides had some features missing elsewhere.

    While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

    Removed:

    There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

    Papers not yet integrated into above:

    • P0505R0 (constexpr chrono)

    • P0418R2 (atomic tweaks)

    • P0512R0 (template argument deduction tweaks)

    • P0490R0 (structured binding tweaks)

    • P0513R0 (changes to std::hash)

    • P0502R0 (parallel exceptions)

    • P0509R1 (updating restrictions on exception handling)

    • P0012R1 (make exception specifications be part of the type system)

    • P0510R0 (restrictions on variants)

    • P0504R0 (tags for optional/variant/any)

    • P0497R0 (shared ptr tweaks)

    • P0508R0 (structured bindings node handles)

    • P0521R0 (shared pointer use count and unique changes?)

    Spec changes:

    Further reference:

    How to add directory to classpath in an application run profile in IntelliJ IDEA?

    You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."

    Passing an array as parameter in JavaScript

    JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

    Using an IF Statement in a MySQL SELECT query

    try this code worked for me

    SELECT user_display_image AS user_image,
           user_display_name AS user_name,
           invitee_phone,
           (CASE WHEN invitee_status = 1 THEN "attending"
                 WHEN invitee_status = 2 THEN "unsure"
                 WHEN invitee_status = 3 THEN "declined"
                 WHEN invitee_status = 0 THEN "notreviwed"
           END) AS invitee_status
      FROM your_table
    

    mysql -> insert into tbl (select from another table) and some default values

    With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:

    INSERT INTO course_payment 
    SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
    FROM orders ORDER BY order_id DESC LIMIT 10;
    

    ASP.Net MVC: How to display a byte array image from model

    This worked for me

    <img src="data:image;base64,@System.Convert.ToBase64String(Model.CategoryPicture.Content)" width="80" height="80"/>     
    

    WordPress Get the Page ID outside the loop

    You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

    <?php
    
    /**
     * @uses WP_Query
     * @uses get_queried_object()
     * @see get_the_ID()
     * @return int
     */
    function get_the_post_id() {
      if (in_the_loop()) {
           $post_id = get_the_ID();
      } else {
           global $wp_query;
           $post_id = $wp_query->get_queried_object_id();
             }
      return $post_id;
    } ?>
    

    And simply do:

    $page_id = get_the_post_id();
    

    Using File.listFiles with FileNameExtensionFilter

    Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

    Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

    Why do Sublime Text 3 Themes not affect the sidebar?

    In Material theme 3.1.4 you can change theme like this: Tools->Metherial Theme->Material Theme Config. Its very easy.

    How to create correct JSONArray in Java using JSONObject

    Here is some code using java 6 to get you started:

    JSONObject jo = new JSONObject();
    jo.put("firstName", "John");
    jo.put("lastName", "Doe");
    
    JSONArray ja = new JSONArray();
    ja.put(jo);
    
    JSONObject mainObj = new JSONObject();
    mainObj.put("employees", ja);
    

    Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

    An example of this using the builder pattern in java 7 looks something like this:

    JsonObject jo = Json.createObjectBuilder()
      .add("employees", Json.createArrayBuilder()
        .add(Json.createObjectBuilder()
          .add("firstName", "John")
          .add("lastName", "Doe")))
      .build();
    

    Apply CSS style attribute dynamically in Angular JS

    On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.

    <span ng-if="selectedItem==item.id"
          ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)',
                    'background-size':'52px 57px',
                    'padding-top':'70px',
                    'background-repeat':'no-repeat',
                    'background-position': 'center'}">
     </span>
     <span ng-if="selectedItem!=item.id"
           ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)',
                    'background-size':'52px 57px',
                    'padding-top':'70px',
                    'background-repeat':'no-repeat',
                    'background-position': 'center'}">
     </span>
    

    In Java, should I escape a single quotation mark (') in String (double quoted)?

    It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

    The only times you should need to escape are when trying to put " inside a string, or ' in a character:

    String quotes = "He said \"Hello, World!\"";
    char quote = '\'';
    

    How to call same method for a list of objects?

    This will work

    all = [a1, b1, b2, a2,.....]
    
    map(lambda x: x.start(),all)    
    

    simple example

    all = ["MILK","BREAD","EGGS"]
    map(lambda x:x.lower(),all)
    >>>['milk','bread','eggs']
    

    and in python3

    all = ["MILK","BREAD","EGGS"]
    list(map(lambda x:x.lower(),all))
    >>>['milk','bread','eggs']
    

    Store a cmdlet's result value in a variable in Powershell

    Just access the Priority property of the object returned from the pipeline:

    $var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
    

    (This won't work if Get-WSManInstance returns multiple objects.2)

    For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

    $var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
    

    and then use, assuming only one process:

    $var.Priority
    

    and

    $var.ProcessID
    

    If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

    $var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
    

    and then use:

    $var[0].Priority
    $var[0].ProcessID
    

    1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

    2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

    Access the css ":after" selector with jQuery

    If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

    $('.active').after().click(function () {
        alert('clickable!');
    });
    

    See the jQuery documentation.

    How to apply CSS to iframe?

    Edit: This does not work cross domain unless the appropriate CORS header is set.

    There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

    <iframe name="iframe1" id="iframe1" src="empty.htm" 
            frameborder="0" border="0" cellspacing="0"
            style="border-style: none;width: 100%; height: 120px;"></iframe>
    

    The style of the page embedded in the iframe must be either set by including it in the child page:

    <link type="text/css" rel="Stylesheet" href="Style/simple.css" />
    

    Or it can be loaded from the parent page with Javascript:

    var cssLink = document.createElement("link");
    cssLink.href = "style.css"; 
    cssLink.rel = "stylesheet"; 
    cssLink.type = "text/css"; 
    frames['iframe1'].document.head.appendChild(cssLink);
    

    Laravel $q->where() between dates

    @Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records

    $projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();
    

    it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.

    How can one check to see if a remote file exists using PHP?

    This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contentsDocs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):

    $url = 'http://example.com/';
    $code = FALSE;
    
    $options['http'] = array(
        'method' => "HEAD",
        'ignore_errors' => 1
    );
    
    $body = file_get_contents($url, NULL, stream_context_create($options));
    
    foreach($http_response_header as $header)
        sscanf($header, 'HTTP/%*d.%*d %d', $code);
    
    echo "Status code: $code";
    

    If you don't want to follow redirects, you can do it similar (Demo):

    $url = 'http://example.com/';
    $code = FALSE;
    
    $options['http'] = array(
        'method' => "HEAD",
        'ignore_errors' => 1,
        'max_redirects' => 0
    );
    
    $body = file_get_contents($url, NULL, stream_context_create($options));
    
    sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
    
    echo "Status code: $code";
    

    Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.

    Javascript window.open pass values using POST

    Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.

    js:

    //example: params={id:'123',name:'foo'};
    
    mapInput.name = "data";
    mapInput.value = JSON.stringify(params); 
    

    php:

    $data=json_decode($_POST['data']); 
    
    echo $data->id;
    echo $data->name;
    

    Hibernate: hbm2ddl.auto=update in production?

    • In my case (Hibernate 3.5.2, Postgresql, Ubuntu), setting hibernate.hbm2ddl.auto=update only created new tables and created new columns in already existing tables.

    • It did neither drop tables, nor drop columns, nor alter columns. It can be called a safe option, but something like hibernate.hbm2ddl.auto=create_tables add_columns would be more clear.

    C#: Waiting for all threads to complete

    Off the top of my head, why don't you just Thread.Join(timeout) and remove the time it took to join from the total timeout?

    // pseudo-c#:
    
    TimeSpan timeout = timeoutPerThread * threads.Count();
    
    foreach (Thread thread in threads)
    {
        DateTime start = DateTime.Now;
    
        if (!thread.Join(timeout))
            throw new TimeoutException();
    
        timeout -= (DateTime.Now - start);
    }
    

    Edit: code is now less pseudo. don't understand why you would mod an answer -2 when the answer you modded +4 is exactly the same, only less detailed.

    Permutation of array

    Here is an implementation of the Permutation in Java:

    Permutation - Java

    You should have a check on it!

    Edit: code pasted below to protect against link-death:

    // Permute.java -- A class generating all permutations
    
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    import java.lang.reflect.Array;
    
    public class Permute implements Iterator {
    
       private final int size;
       private final Object [] elements;  // copy of original 0 .. size-1
       private final Object ar;           // array for output,  0 .. size-1
       private final int [] permutation;  // perm of nums 1..size, perm[0]=0
    
       private boolean next = true;
    
       // int[], double[] array won't work :-(
       public Permute (Object [] e) {
          size = e.length;
          elements = new Object [size];    // not suitable for primitives
          System.arraycopy (e, 0, elements, 0, size);
          ar = Array.newInstance (e.getClass().getComponentType(), size);
          System.arraycopy (e, 0, ar, 0, size);
          permutation = new int [size+1];
          for (int i=0; i<size+1; i++) {
             permutation [i]=i;
          }
       }
    
       private void formNextPermutation () {
          for (int i=0; i<size; i++) {
             // i+1 because perm[0] always = 0
             // perm[]-1 because the numbers 1..size are being permuted
             Array.set (ar, i, elements[permutation[i+1]-1]);
          }
       }
    
       public boolean hasNext() {
          return next;
       }
    
       public void remove() throws UnsupportedOperationException {
          throw new UnsupportedOperationException();
       }
    
       private void swap (final int i, final int j) {
          final int x = permutation[i];
          permutation[i] = permutation [j];
          permutation[j] = x;
       }
    
       // does not throw NoSuchElement; it wraps around!
       public Object next() throws NoSuchElementException {
    
          formNextPermutation ();  // copy original elements
    
          int i = size-1;
          while (permutation[i]>permutation[i+1]) i--;
    
          if (i==0) {
             next = false;
             for (int j=0; j<size+1; j++) {
                permutation [j]=j;
             }
             return ar;
          }
    
          int j = size;
    
          while (permutation[i]>permutation[j]) j--;
          swap (i,j);
          int r = size;
          int s = i+1;
          while (r>s) { swap(r,s); r--; s++; }
    
          return ar;
       }
    
       public String toString () {
          final int n = Array.getLength(ar);
          final StringBuffer sb = new StringBuffer ("[");
          for (int j=0; j<n; j++) {
             sb.append (Array.get(ar,j).toString());
             if (j<n-1) sb.append (",");
          }
          sb.append("]");
          return new String (sb);
       }
    
       public static void main (String [] args) {
          for (Iterator i = new Permute(args); i.hasNext(); ) {
             final String [] a = (String []) i.next();
             System.out.println (i);
          }
       }
    }
    

    Printing image with PrintDocument. how to adjust the image to fit paper size

    The solution provided by BBoy works fine. But in my case I had to use

    e.Graphics.DrawImage(memoryImage, e.PageBounds);
    

    This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!

    How to index into a dictionary?

    actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

    Just watch:

    list = ['a', 'b', 'c']
    dictionary = {}
    counter = 0
    for i in list:
       dictionary[i] = counter
       counter += 1
    
    print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}
    

    Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)

    How to add action listener that listens to multiple buttons

    Here is a modified form of the source based on my comment. Note that GUIs should be constructed & updated on the EDT, though I did not go that far.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    
    public class Calc {
    
        public static void main(String[] args) {
    
            JFrame calcFrame = new JFrame();
    
            // usually a good idea.
            calcFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
            final JButton button1 = new JButton("1");
            button1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    JOptionPane.showMessageDialog(
                        button1, "..is the loneliest number");
                }
            });
    
            calcFrame.add(button1);
    
            // don't do this..
            // calcFrame.setSize(100, 100);
    
            // important!
            calcFrame.pack();
    
            calcFrame.setVisible(true);
        }
    }