Programs & Examples On #Metrics

Software metrics are quantitative data related to software.

Eclipse count lines of code

Install the Eclipse Metrics Plugin. To create a HTML report (with optional XML and CSV) right-click a project -> Export -> Other -> Metrics.

You can adjust the Lines of Code metrics by ignoring blank and comment-only lines or exclude Javadoc if you want. To do this check the tab at Preferences -> Metrics -> LoC.

That's it. There is no special option to exclude curly braces {}.

The plugin offers an alternative metric to LoC called Number of Statements. This is what the author has to say about it:

This metric represents the number of statements in a method. I consider it a more robust measure than Lines of Code since the latter is fragile with respect to different formatting conventions.

Edit:

After you clarified your question, I understand that you need a view for real-time metrics violations, like compiler warnings or errors. You also need a reporting functionality to create reports for your boss. The plugin I described above is for reporting because you have to export the metrics when you want to see them.

Mythical man month 10 lines per developer day - how close on large projects?

Good planning, good design and good programmers. You get all that togheter and you will not spend 30 minutes to write one line. Yes, all projects require you to stop and plan,think over,discuss, test and debug but at two lines per day every company would need an army to get tetris to work...

Bottom line, if you were working for me at 2 lines per hours, you'd better be getting me a lot of coffes andmassaging my feets so you didn't get fired.

How to count lines of Java code using IntelliJ IDEA?

Just like Neil said:

Ctrl-Shift-F -> Text to find = '\n' -> Find.

With only one improvement, if you enter "\n+", you can search for non-empty lines

If lines with only whitespace can be considered empty too, then you can use the regex "(\s*\n\s*)+" to not count them.

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

C# Numeric Only TextBox Control

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.

How to close the current fragment by using Button like the back button?

if you need in 2020

    Objects.requireNonNull(getActivity()).onBackPressed();

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

Run a single test method with maven

As of surefire plugin version 2.22.1 (possibly earlier) you can run single test using testnames property when using testng.xml

Given a following testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="all-tests">
        <classes>
            <class name="server.Atest"/>
            <class name="server.Btest"/>
            <class name="server.Ctest"/>
        </classes>
    </test>
    <test name="run-A-test">
        <classes>
            <class name="server.Atest"/>
        </classes>
    </test>
    <test name="run-B-test">
        <classes>
            <class name="server.Btest"/>
        </classes>
    </test>
    <test name="run-C-test">
        <classes>
            <class name="server.Ctest"/>
        </classes>
    </test>
</suite> 

with the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    [...]
    <properties>
        <selectedTests>all-tests</selectedTests>
    </properties>
    [...]
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
            <configuration>
                <suiteXmlFiles>
                    <file>src/test/resources/testng.xml</file>
                </suiteXmlFiles>
                <properties>
                    <property>
                        <name>testnames</name>
                        <value>${selectedTests}</value>
                    </property>
                </properties>
            </configuration>
        </plugin>
    </plugins>
    [...]
</project>

From command line

mvn clean test -DselectedTests=run-B-test

Further reading - Maven surefire plugin using testng

bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in .container, .row and .col-md-x classes like this one

<div class="container">
   <div class="row">
     <div class="col-md-12">
     <!-- or use any other number .col-md- -->
         <div class="table-responsive">
             <div class="table">
             </div>
         </div>
     </div>
   </div>
</div>

With this, you can still use <p> tags and even make it responsive.

Please see the Bootply example here

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

How to count objects in PowerShell?

This will get you count:

get-alias | measure

You can work with the result as with object:

$m = get-alias | measure
$m.Count

And if you would like to have aliases in some variable also, you can use Tee-Object:

$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases

Some more info on Measure-Object cmdlet is on Technet.

Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)

How to use XPath in Python?

Another library is 4Suite: http://sourceforge.net/projects/foursuite/

I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned.

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

Open Facebook page from Android app?

A more reusable approach.

This is a functionality we generally use in most of our apps. Hence here is a reusable piece of code to achieve this.

(Similar to other answers in terms for facts. Posting it here just to simplify and make the implementation reusable)

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions. (Like mentioned in another answer here)

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) { //newer versions of fb app
                return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
            } else { //older versions of fb app
                return "fb://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

That's all you need.

Default interface methods are only supported starting with Android N

You should use Java 8 to solve this, based on the Android documentation you can do this by

clicking File > Project Structure

and change Source Compatibility and Target Compatibility.

enter image description here

and you can also configure it directly in the app-level build.gradle file:

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

How can I unstage my files again after making a local commit?

For unstaging all the files in your last commit -

git reset HEAD~

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

Ubuntu defaults to the OpenJDK packages. If you want to install Oracle's JDK, then you need to visit their download page, and grab the package from there.

Once you've installed the Oracle JDK, you also need to update the following (system defaults will point to OpenJDK):

export JAVA_HOME=/my/path/to/oracle/jdk
export PATH=$JAVA_HOME/bin:$PATH

If you want the Oracle JDK to be the default for your system, you will need to remove the OpenJDK packages, and update your profile environment variables.

I get Access Forbidden (Error 403) when setting up new alias

Apache 2.4 virtual hosts hack

1.In http.conf specify the ports , below “Listen”

Listen 80
Listen 4000
Listen 7000
Listen 9000
  1. In httpd-vhosts.conf

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"  
    ServerName hitesh_web.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
    Allow from all
    Require all granted
    </Directory>
    
    </VirtualHost>
    

    this is 2nd virtual host

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "E:/dabkick_git/DabKickWebsite"
    ServerName  www.my_mobile.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "E:/dabkick_git/DabKickWebsite">
     Allow from all
     Require all granted
     </Directory>
    </VirtualHost>
    
  2. In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”

    127.0.0.1             localhost
    127.0.0.1             hitesh_web.dev
    127.0.0.1             www.my_mobile.dev
    127.0.0.1             demo.multisite.dev
    

4.now type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path

5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache

   <VirtualHost *:4000>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>

</VirtualHost>

this is the 2nd vhost

<VirtualHost *:7000>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName  www.dabkick_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>

Note: for port number given virtual hosts you have to ping in browser like “http://hitesh_web.dev:4000/” or “http://www.dabkick_mobile.dev:7000/

6.After doing all those changes you have to save the files and restart apache respectively.

How to use enums in C++

This code is wrong:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days.Saturday;
if (day == Days.Saturday)

Because Days is not a scope, nor object. It is a type. And Types themselves don't have members. What you wrote is the equivalent to std::string.clear. std::string is a type, so you can't use . on it. You use . on an instance of a class.

Unfortunately, enums are magical and so the analogy stops there. Because with a class, you can do std::string::clear to get a pointer to the member function, but in C++03, Days::Sunday is invalid. (Which is sad). This is because C++ is (somewhat) backwards compatable with C, and C had no namespaces, so enumerations had to be in the global namespace. So the syntax is simply:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Saturday;
if (day == Saturday)

Fortunately, Mike Seymour observes that this has been addressed in C++11. Change enum to enum class and it gets its own scope; so Days::Sunday is not only valid, but is the only way to access Sunday. Happy days!

When is JavaScript synchronous?

Definition

The term "asynchronous" can be used in slightly different meanings, resulting in seemingly conflicting answers here, while they are actually not. Wikipedia on Asynchrony has this definition:

Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be "outside" events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.

non-JavaScript code can queue such "outside" events to some of JavaScript's event queues. But that is as far as it goes.

No Preemption

There is no external interruption of running JavaScript code in order to execute some other JavaScript code in your script. Pieces of JavaScript are executed one after the other, and the order is determined by the order of events in each event queue, and the priority of those queues.

For instance, you can be absolutely sure that no other JavaScript (in the same script) will ever execute while the following piece of code is executing:

let a = [1, 4, 15, 7, 2];
let sum = 0;
for (let i = 0; i < a.length; i++) {
    sum += a[i];
}

In other words, there is no preemption in JavaScript. Whatever may be in the event queues, the processing of those events will have to wait until such piece of code has ran to completion. The EcmaScript specification says in section 8.4 Jobs and Jobs Queues:

Execution of a Job can be initiated only when there is no running execution context and the execution context stack is empty.

Examples of Asynchrony

As others have already written, there are several situations where asynchrony comes into play in JavaScript, and it always involves an event queue, which can only result in JavaScript execution when there is no other JavaScript code executing:

  • setTimeout(): the agent (e.g. browser) will put an event in an event queue when the timeout has expired. The monitoring of the time and the placing of the event in the queue happens by non-JavaScript code, and so you could imagine this happens in parallel with the potential execution of some JavaScript code. But the callback provided to setTimeout can only execute when the currently executing JavaScript code has ran to completion and the appropriate event queue is being read.

  • fetch(): the agent will use OS functions to perform an HTTP request and monitor for any incoming response. Again, this non-JavaScript task may run in parallel with some JavaScript code that is still executing. But the promise resolution procedure, that will resolve the promise returned by fetch(), can only execute when the currently executing JavaScript has ran to completion.

  • requestAnimationFrame(): the browser's rendering engine (non-JavaScript) will place an event in the JavaScript queue when it is ready to perform a paint operation. When JavaScript event is processed the callback function is executed.

  • queueMicrotask(): immediately places an event in the microtask queue. The callback will be executed when the call stack is empty and that event is consumed.

There are many more examples, but all these functions are provided by the host environment, not by core EcmaScript. With core EcmaScript you can synchronously place an event in a Promise Job Queue with Promise.resolve().

Language Constructs

EcmaScript provides several language constructs to support the asynchrony pattern, such as yield, async, await. But let there be no mistake: no JavaScript code will be interrupted by an external event. The "interruption" that yield and await seem to provide is just a controlled, predefined way of returning from a function call and restoring its execution context later on, either by JS code (in the case of yield), or the event queue (in the case of await).

DOM event handling

When JavaScript code accesses the DOM API, this may in some cases make the DOM API trigger one or more synchronous notifications. And if your code has an event handler listening to that, it will be called.

This may come across as pre-emptive concurrency, but it is not: once your event handler(s) return(s), the DOM API will eventually also return, and the original JavaScript code will continue.

In other cases the DOM API will just dispatch an event in the appropriate event queue, and JavaScript will pick it up once the call stack has been emptied.

See synchronous and asynchronous events

Android and Facebook share intent

This solution works aswell. If there is no Facebook installed, it just runs the normal share-dialog. If there is and you are not logged in, it goes to the login screen. If you are logged in, it will open the share dialog and put in the "Share url" from the Intent Extra.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Share url");
intent.setType("text/plain");

List<ResolveInfo> matches = getMainFragmentActivity().getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().contains("facebook")) {
        intent.setPackage(info.activityInfo.packageName);
    }
}

startActivity(intent);

Vue js error: Component template should contain exactly one root element

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

// or

import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
  <fragment>
    <tr class="hola">
      ...
    </tr>
    <tr class="hello">
      ...
    </tr>
  </fragment>
</template>

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

How can I indent multiple lines in Xcode?

For code indentation first select the lines of code then press:

command + alt + [

command + alt + ]

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params) instead of two * (**params). This will explode the list/tuple into the proper amount of arguments.

Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params), because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).

super(HStoreDictionary, self).__init__(value, **params)

Hope this helps!

Extract a single (unsigned) integer from a string

for utf8 str:

function unicodeStrDigits($str) {
    $arr = array();
    $sub = '';
    for ($i = 0; $i < strlen($str); $i++) { 
        if (is_numeric($str[$i])) {
            $sub .= $str[$i];
            continue;
        } else {
            if ($sub) {
                array_push($arr, $sub);
                $sub = '';
            }
        }
    }

    if ($sub) {
        array_push($arr, $sub); 
    }

    return $arr;
}

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

JSON

An alternative Solution could be converting your collection in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString().

Example using Google's Gson:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

...

    printJsonString(stack);

...
public static void printJsonString(Object o) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    /*
     * Some options for GsonBuilder like setting dateformat or pretty printing
     */
    Gson gson = gsonBuilder.create();
    String json= gson.toJson(o);
    System.out.println(json);
}

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

Mysql - delete from multiple tables with one query

You can define foreign key constraints on the tables with ON DELETE CASCADE option.

Then deleting the record from parent table removes the records from child tables.

Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

Change background color of iframe issue

Put the Iframe between aside tags

<aside style="background-color:#FFF"> your IFRAME </aside>

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

Switch statement for greater-than/less-than

An alternative:

var scrollleft = 1000;
switch (true)
{
    case (scrollleft > 1000):
      alert('gt');
      break;
    case (scrollleft <= 1000):
      alert('lt');
      break; 
}

Demo: http://jsfiddle.net/UWYzr/

How to update the value stored in Dictionary in C#?

You can follow this approach:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKey to check the existance and update the value using dic[key] = val + newValue; then you are accessing the dictionary twice.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I had the same issue. I have Windows xp box and when I would type mvn -version at the command line prompt I got the dreaded error message

"Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/plexus/classworlds/launcher/Launcher"

I confirmed that my M2_HOME variable was set to the path where Maven was installed on pc and that the echo %path% confirmed that Maven was in my path.

I have been searching for a solution for hours when I stumbled on to my solution (I say my solution because I know this probably won't be the solution for everyone that is getting the same error).

I copied the path that was assigned to my M2_HOME variable. I opened a cmd window and typed cd and pasted the path I got from my M2_HOME variable. At that point I knew that the path was correct because the path was displayed in the window. At this point I entered the dir command and to my surprise, I got the error File Not Found.

I went to that path via Explorer and sure enough there were files present. I noticed that the folders were faded out, but I could access them and see the files within each folder (I have admin rights on my pc). I looked at the properties of the parent folder for Maven and saw that the Hidden box was checked. I removed the check and applied and tried my dir command again with success.

Next I tried the mvn –version command again, but this time I got back the expected results.

C:\>mvn -version
Apache Maven 3.0.3 (r1075438; 2011-02-28 11:31:09-0600)
Maven home: C:\Program Files\apache-maven-3.0.3
Java version: 1.5.0_16, vendor: Sun Microsystems Inc.
Java home: C:\Java\jdk1.5.0_16\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows xp", version: "5.1", arch: "x86", family: "windows"

Finally I created a jar and war file and my web app ran successfully on my local Tomcat.

I hope this helps some of you out there.

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

Setting an image for a UIButton in code

You can put the image in either of the way:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self 
           action:@selector(goToOne) 
 forControlEvents:UIControlEventTouchUpInside];


[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];

//OR setting as background image

[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] 
                  forState:UIControlStateNormal];

[self.view addSubview:btnTwo];

How to create a property for a List<T>

T must be defined within the scope in which you are working. Therefore, what you have posted will work if your class is generic on T:

public class MyClass<T>
{
    private List<T> newList;

    public List<T> NewList
    {
        get{return newList;}
        set{newList = value;}
    }
}

Otherwise, you have to use a defined type.

EDIT: Per @lKashef's request, following is how to have a List property:

private List<int> newList;

public List<int> NewList
{
    get{return newList;}
    set{newList = value;}
}

This can go within a non-generic class.

Edit 2: In response to your second question (in your edit), I would not recommend using a list for this type of data handling (if I am understanding you correctly). I would put the user settings in their own class (or struct, if you wish) and have a property of this type on your original class:

public class UserSettings
{
 string FirstName { get; set; }
 string LastName { get; set; }
 // etc.
}

public class MyClass
{
 string MyClassProperty1 { get; set; }
 // etc.

 UserSettings MySettings { get; set; }
}

This way, you have named properties that you can reference instead of an arbitrary index in a list. For example, you can reference MySettings.FirstName as opposed to MySettingsList[0].

Let me know if you have any further questions.

EDIT 3: For the question in the comments, your property would be like this:

public class MyClass
{
    public List<KeyValuePair<string, string>> MySettings { get; set; } 
}

EDIT 4: Based on the question's edit 2, following is how I would use this:

public class MyClass
{
    // note that this type of property declaration is called an "Automatic Property" and
    // it means the same thing as you had written (the private backing variable is used behind the scenes, but you don't see it)
    public List<KeyValuePair<string, string> MySettings { get; set; } 
}

public class MyConsumingClass
{
    public void MyMethod
    {
        MyClass myClass = new MyClass();
        myClass.MySettings = new List<KeyValuePair<string, string>>();
        myClass.MySettings.Add(new KeyValuePair<string, string>("SomeKeyValue", "SomeValue"));

        // etc.
    }
}

You mentioned that "the property still won't appear in the object's instance," and I am not sure what you mean. Does this property not appear in IntelliSense? Are you sure that you have created an instance of MyClass (like myClass.MySettings above), or are you trying to access it like a static property (like MyClass.MySettings)?

Difference between multitasking, multithreading and multiprocessing?

Multi-programming :-

More than one task(job) process can reside into main memory at a time. It is basically design to reduce CPU wastage during I/O operation , example : if a job is executing currently and need I/O operation . I/O operation is done using DMA and processor assign to some Other job from the job queue till I/O operation of job1 completed . then job1 continue again . In this way it reduce CPU wastage .

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

python variable NameError

Your if statements are checking for int values. raw_input returns a string. Change the following line:

tSizeAns = raw_input() 

to

tSizeAns = int(raw_input()) 

Python append() vs. + operator on lists, why do these give different results?

you should use extend()

>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

other info: append vs. extend

Compare two different files line by line in python

If order is preserved between files you might also prefer difflib. Although Rob?'s result is the bona-fide standard for intersections you might actually be looking for a rough diff-like:

from difflib import Differ

with open('cfg1.txt') as f1, open('cfg2.txt') as f2:
    differ = Differ()

    for line in differ.compare(f1.readlines(), f2.readlines()):
        if line.startswith(" "):
            print(line[2:], end="")

That said, this has a different behaviour to what you asked for (order is important) even though in this instance the same output is produced.

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

How to change font-color for disabled input?

You can't for Internet Explorer.

See this comment I wrote on a related topic:

There doesn't seem to be a good way, see: How to change color of disabled html controls in IE8 using css - you can set the input to readonly instead, but that has other consequences (such as with readonly, the input will be sent to the server on submit, but with disabled, it won't be): http://jsfiddle.net/wCFBw/40

Also, see: Changing font colour in Textboxes in IE which are disabled

Use PHP to convert PNG to JPG with compression?

You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.

HTH.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.

That said, please try the following filter and see if you're getting the entries that you think you should be getting:

dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7

Iterating through a range of dates in Python

I have a similar problem, but I need to iterate monthly instead of daily.

This is my solution

import calendar
from datetime import datetime, timedelta

def days_in_month(dt):
    return calendar.monthrange(dt.year, dt.month)[1]

def monthly_range(dt_start, dt_end):
    forward = dt_end >= dt_start
    finish = False
    dt = dt_start

    while not finish:
        yield dt.date()
        if forward:
            days = days_in_month(dt)
            dt = dt + timedelta(days=days)            
            finish = dt > dt_end
        else:
            _tmp_dt = dt.replace(day=1) - timedelta(days=1)
            dt = (_tmp_dt.replace(day=dt.day))
            finish = dt < dt_end

Example #1

date_start = datetime(2016, 6, 1)
date_end = datetime(2017, 1, 1)

for p in monthly_range(date_start, date_end):
    print(p)

Output

2016-06-01
2016-07-01
2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

Example #2

date_start = datetime(2017, 1, 1)
date_end = datetime(2016, 6, 1)

for p in monthly_range(date_start, date_end):
    print(p)

Output

2017-01-01
2016-12-01
2016-11-01
2016-10-01
2016-09-01
2016-08-01
2016-07-01
2016-06-01

Getting error "The package appears to be corrupt" while installing apk file

In my case by making build, from Build> Build apks, it worked.

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

How to work with complex numbers in C?

This code will help you, and it's fairly self-explanatory:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

  with:

creal(z1): get the real part (for float crealf(z1), for long double creall(z1))

cimag(z1): get the imaginary part (for float cimagf(z1), for long double cimagl(z1))

Another important point to remember when working with complex numbers is that functions like cos(), exp() and sqrt() must be replaced with their complex forms, e.g. ccos(), cexp(), csqrt().

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Close android studio and open it again. Then try compiling the same code. I was getting the same error and it worked for me. Hope it helps.

How do I order my SQLITE database in descending order, for an android app?

This a terrible thing! It costs my a few hours! this is my table rows :

private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";

Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);

Every time when I update the table , I will update the CURRENT_TIME for sort. But I found that it is not work.The result is not sorted what I want. Finally, I found that, the column "current_time" is the default row of sqlite.

The solution is, rename the column "cur_time" instead of "current_time".

Android Studio: Gradle: error: cannot find symbol variable

If you are using multiple flavors?

-make sure the resource file is not declared/added both in only one of the flavors and in main.

Example: a_layout_file.xml file containing the symbol variable(s)

src:

flavor1/res/layout/(no file)

flavor2/res/layout/a_layout_file.xml

main/res/layout/a_layout_file.xml

This setup will give the error: cannot find symbol variable, this is because the resource file can only be in both flavors or only in the main.

Javascript find json value

Just use the ES6 find() function in a functional way:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_

or Lodash _.find:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

npm install from Git in a specific version

If by version you mean a tag or a release, then github provides download links for those. For example, if I want to install fetch version 0.3.2 (it is not available on npm), then I add to my package.json under dependencies:

"fetch": "https://github.com/github/fetch/archive/v0.3.2.tar.gz",

The only disadvantage when compared with the commit hash approach is that a hash is guaranteed not to represent changed code, whereas a tag could be replaced. Thankfully this rarely happens.

Update:

These days the approach I use is the compact notation for a GitHub served dependency:

"dependencies": {
  "package": "github:username/package#commit"
}

Where commit can be anything commitish, like a tag. In the case of GitHub you can even drop the initial github: since it's the default.

Convert date from String to Date format in Dataframes

Find the below-mentioned code, it might be helpful for you.

   val stringDate = spark.sparkContext.parallelize(Seq("12/16/2019")).toDF("StringDate")
                    val dateCoversion = stringDate.withColumn("dateColumn", to_date(unix_timestamp($"StringDate", "dd/mm/yyyy").cast("Timestamp")))
                    dateCoversion.show(false)
+----------+----------+
|StringDate|dateColumn|
+----------+----------+
|12/16/2019|2019-01-12|
+----------+----------+

IIS: Display all sites and bindings in PowerShell

If you just want to list all the sites (ie. to find a binding)

Change the working directory to "C:\Windows\system32\inetsrv"

cd c:\Windows\system32\inetsrv

Next run "appcmd list sites" (plural) and output to a file. e.g c:\IISSiteBindings.txt

appcmd list sites > c:\IISSiteBindings.txt

Now open with notepad from your command prompt.

notepad c:\IISSiteBindings.txt

Is there a splice method for strings?

Simply use substr for string

ex.

var str = "Hello world!";
var res = str.substr(1, str.length);

Result = ello world!

Unknown column in 'field list' error on MySQL Update query

You might check your choice of quotes (use double-/ single quotes for values, strings, etc and backticks for column-names).

Since you only want to update the table master_user_profile I'd recommend a nested query:

UPDATE
   master_user_profile
SET
   master_user_profile.fellow = 'y'
WHERE
   master_user_profile.user_id IN (
      SELECT tran_user_branch.user_id
      FROM tran_user_branch WHERE tran_user_branch.branch_id = 17);

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

Serialize

jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2

This will enable you to keep the information for which elements were checked as well.

Accessing inventory host variable in Ansible playbook

I struggled with this, too. My specific setup is: Your host.ini (with the modern names):

[test3]
test3-1 ansible_host=abc.def.ghi.pqr ansible_port=1212
test3-2 ansible_host=abc.def.ghi.stu ansible_port=1212

plus a play fill_file.yml

---
- remote_user: ec2-user
  hosts: test3
  tasks:
   - name: fill file
     template:
       src: file.j2
       dest: filled_file.txt

plus a template file.j2 , like

{% for host in groups['test3'] %}
   {{ hostvars[host].ansible_host }}
{% endfor %}

This worked for me, the result is

abc.def.ghi.pqr
abc.def.ghi.stu

I have to admit it's ansible 2.7, not 2.1. The template is a variation of an example in https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html.

The accepted answer didn't work in my setup. With a template

{{ hostvars['test3'].ansible_host }}

my play fails with "AnsibleUndefinedVariable: \"hostvars['test3']\" is undefined" .

Remark: I tried some variations, but failed, occasionally with "ansible.vars.hostvars.HostVars object has no element "; Some of this might be explained by what they say. in https://github.com/ansible/ansible/issues/13343#issuecomment-160992631

hostvars emulates a dictionary [...]. hostvars is also lazily loaded

How to change the type of a field?

The only way to change the $type of the data is to perform an update on the data where the data has the correct type.

In this case, it looks like you're trying to change the $type from 1 (double) to 2 (string).

So simply load the document from the DB, perform the cast (new String(x)) and then save the document again.

If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {}) syntax.


In response to the second comment below. Change the field bad from a number to a string in collection foo.

db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {   
  x.bad = new String(x.bad); // convert field to string
  db.foo.save(x);
});

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

Find nginx version?

In my case, I try to add sudo

sudo nginx -v

enter image description here

Bootstrap 3: how to make head of dropdown link clickable in navbar

This 100% works:

HTML:

<li class="dropdown">
          <a href="https://www.bkweb.co.in/" class="dropdown-toggle" >bkWeb.co.in Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>

CSS:

@media (min-width:991px){
  ul.nav li.dropdown:hover ul.dropdown-menu {
    display: block;
  }
}

EXAMPLE in CODEPEN

The term "Add-Migration" is not recognized

These are the steps I followed and it solved the problem

1)Upgraded my Power shell from version 2 to 3

2)Closed the PM Console

3)Restarted Visual Studio

4)Ran the below command in PM Console dotnet restore

5)Add-Migration InitialMigration

It worked !!!

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:

"first_Name"

Values (string literals / constants) are enclosed in single quotes:

'xyz'

So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

Read the manual on identifiers here.

My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

Writelines writes lines without newline, Just fills the file

This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log-related stuff) add them.

So, there's a lot of Python code out there that does things like:

fw.write('\n'.join(line_list) + '\n')

or

fw.write(line + '\n' for line in line_list)

Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…

But you should only do this if you can't avoid it.

It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:

line_list.append(new_line + "\n")

And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.

For example, right after defining fw, you might do this:

cw = csv.writer(fw, delimiter='|')

Then, instead of this:

new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)

You do this:

row_list.append(d[looking_for] + columns[1:])

And at the end, instead of this:

fw.writelines(line_list)

You do this:

cw.writerows(row_list)

Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open all the way to the opposite end of the program from the write, you've pretty much lost any benefits of all-at-once.)

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

Convert tabs to spaces in Notepad++

Settings -> Preference -> Edit Components (tab) -> Tab Setting (group) -> Replace by space

In version 5.6.8 (and above):

Settings -> Preferences... -> Language Menu/Tab Settings -> Tab Settings (group) -> Replace by space

How can I remove an entry in global configuration with git config?

You can use the --unset flag of git config to do this like so:

git config --global --unset user.name
git config --global --unset user.email

If you have more variables for one config you can use:

git config --global --unset-all user.name

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

How do I convert an integer to binary in JavaScript?

This is the solution . Its quite simple as a matter of fact

function binaries(num1){ 
        var str = num1.toString(2)
        return(console.log('The binary form of ' + num1 + ' is: ' + str))
     }
     binaries(3

)

        /*
         According to MDN, Number.prototype.toString() overrides 
         Object.prototype.toString() with the useful distinction that you can 
         pass in a single integer argument. This argument is an optional radix, 
         numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to 
         get a string representation of the binary for the base 10 number 100, 
         i.e. 1100100.
        */

How to compare DateTime in C#?

MSDN: DateTime.Compare

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM

How do I compare two hashes?

If you need a quick and dirty diff between hashes which correctly supports nil in values you can use something like

def diff(one, other)
  (one.keys + other.keys).uniq.inject({}) do |memo, key|
    unless one.key?(key) && other.key?(key) && one[key] == other[key]
      memo[key] = [one.key?(key) ? one[key] : :_no_key, other.key?(key) ? other[key] : :_no_key]
    end
    memo
  end
end

Set the selected index of a Dropdown using jQuery

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Addendum

As recommended in the comments use :

$("select#elem").prop('selectedIndex', 0);

Converting from byte to int in java

I thought it would be:

byte b = (byte)255;
int i = b &255;

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

jQuery UI themes and HTML tables

dochoffiday's answer is a great starting point, but for me it did not cut it (the CSS part needed a buff) so I made a modified version with several improvements.

See it in action, then come back for the description.

JavaScript

(function ($) {
    $.fn.styleTable = function (options) {
        var defaults = {
            css: 'ui-styled-table'
        };
        options = $.extend(defaults, options);

        return this.each(function () {
            $this = $(this);
            $this.addClass(options.css);

            $this.on('mouseover mouseout', 'tbody tr', function (event) {
                $(this).children().toggleClass("ui-state-hover",
                                               event.type == 'mouseover');
            });

            $this.find("th").addClass("ui-state-default");
            $this.find("td").addClass("ui-widget-content");
            $this.find("tr:last-child").addClass("last-child");
        });
    };
})(jQuery);

Differences with the original version:

  • the default CSS class has been changed to ui-styled-table (it sounds more consistent)
  • the .live call was replaced with the recommended .on for jQuery 1.7 upwards
  • the explicit conditional has been replaced by .toggleClass (a terser equivalent)
  • code that sets the misleadingly-named CSS class first on table cells has been removed
  • the code that dynamically adds .last-child to the last table row is necessary to fix a visual glitch on Internet Explorer 7 and Internet Explorer 8; for browsers that support :last-child it is not necessary

CSS

/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td  { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }

/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
        to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
    font-weight: inherit;
    *font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}

/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }

/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }

/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }

Notes

I have tested this on Internet Explorer 7 and upwards, Firefox 11 and Google Chrome 18 and confirmed that it works perfectly. I have not tested reasonably earlier versions of Firefox and Chrome or any version of Opera; however, those browsers are well-known for good CSS support and since we are not using any bleeding-edge functionality here I assume it will work just fine there as well.

If you are not interested in Internet Explorer 7 support there is one CSS attribute (introduced with the star hack) that can go.

If you are not interested in Internet Explorer 8 support either, the CSS and JavaScript related to adding and targeting the last-child CSS class can go as well.

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

How to print binary tree diagram?

I know you guys all have great solution; I just want to share mine - maybe that is not the best way, but it is perfect for myself!

With python and pip on, it is really quite simple! BOOM!

On Mac or Ubuntu (mine is mac)

  1. open terminal
  2. $ pip install drawtree
  3. $python, enter python console; you can do it in other way
  4. from drawtree import draw_level_order
  5. draw_level_order('{2,1,3,0,7,9,1,2,#,1,0,#,#,8,8,#,#,#,#,7}')

DONE!

        2
       / \
      /   \
     /     \
    1       3
   / \     / \
  0   7   9   1
 /   / \     / \
2   1   0   8   8
       /
      7

Source tracking:

Before I saw this post, I went google "binary tree plain text"

And I found this https://www.reddit.com/r/learnpython/comments/3naiq8/draw_binary_tree_in_plain_text/, direct me to this https://github.com/msbanik/drawtree

Selector on background color of TextView

For who is searching to do it without creating a background sector, just add those lines to the TextView

android:background="?android:attr/selectableItemBackground"
android:clickable="true"

Also to make it selectable use:

android:textIsSelectable="true"

Prevent double submission of forms in jQuery

There is a possibility to improve Nathan Long's approach. You can replace the logic for detection of already submitted form with this one:

var lastTime = $(this).data("lastSubmitTime");
if (lastTime && typeof lastTime === "object") {
    var now = new Date();
    if ((now - lastTime) > 2000) // 2000ms
        return true;
    else
        return false;
}
$(this).data("lastSubmitTime", new Date());
return true; // or do an ajax call or smth else

ORA-00918: column ambiguously defined in SELECT *

You can also see this error when selecting for a union where corresponding columns can be null.

select * from (select D.dept_no, D.nullable_comment
                  from dept D
       union
               select R.dept_no, NULL
                 from redundant_dept R
)

This apparently confuses the parser, a solution is to assign a column alias to the always null column.

select * from (select D.dept_no, D.comment
                  from dept D
       union
               select R.dept_no, NULL "nullable_comment"
                 from redundant_dept R
)

The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.

Sorting A ListView By Column

I sort using column name to set any sorting specifics that may need to be handled based on data type stored in the column and or if the column has already been sorted on(asc/desc). Here's a snippet from my ColumnClick event handler.

private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListViewItemComparer sorter = GetListViewSorter(e.Column);

        listView.ListViewItemSorter = sorter;
        listView.Sort();
    }

    private ListViewItemComparer GetListViewSorter(int columnIndex)
    {
        ListViewItemComparer sorter = (ListViewItemComparer)listView.ListViewItemSorter;
        if (sorter == null)
        {
            sorter = new ListViewItemComparer();
        }

        sorter.ColumnIndex = columnIndex;

        string columnName = packagedEstimateListView.Columns[columnIndex].Name;
        switch (columnName)
        {
            case ApplicationModel.DisplayColumns.DateCreated:
            case ApplicationModel.DisplayColumns.DateUpdated:
                sorter.ColumnType = ColumnDataType.DateTime;
                break;
            case ApplicationModel.DisplayColumns.NetTotal:
            case ApplicationModel.DisplayColumns.GrossTotal:
                sorter.ColumnType = ColumnDataType.Decimal;
                break;
            default:
                sorter.ColumnType = ColumnDataType.String;
                break;
        }

        if (sorter.SortDirection == SortOrder.Ascending)
        {
            sorter.SortDirection = SortOrder.Descending;
        }
        else
        {
            sorter.SortDirection = SortOrder.Ascending;
        }

        return sorter;
    }

Below is my ListViewItemComparer

public class ListViewItemComparer : IComparer
{
    private int _columnIndex;
    public int ColumnIndex
    {
        get
        {
            return _columnIndex;
        }
        set
        {
            _columnIndex = value;
        }
    }

    private SortOrder _sortDirection;
    public SortOrder SortDirection
    {
        get
        {
            return _sortDirection;
        }
        set
        {
            _sortDirection = value;
        }
    }

    private ColumnDataType _columnType;
    public ColumnDataType ColumnType
    {
        get
        {
            return _columnType;
        }
        set
        {
            _columnType = value;
        }
    }


    public ListViewItemComparer()
    {
        _sortDirection = SortOrder.None;
    }

    public int Compare(object x, object y)
    {
        ListViewItem lviX = x as ListViewItem;
        ListViewItem lviY = y as ListViewItem;

        int result;

        if (lviX == null && lviY == null)
        {
            result = 0;
        }
        else if (lviX == null)
        {
            result = -1;
        }

        else if (lviY == null)
        {
            result = 1;
        }

        switch (ColumnType)
        {
            case ColumnDataType.DateTime:
                DateTime xDt = DataParseUtility.ParseDate(lviX.SubItems[ColumnIndex].Text);
                DateTime yDt = DataParseUtility.ParseDate(lviY.SubItems[ColumnIndex].Text);
                result = DateTime.Compare(xDt, yDt);
                break;

            case ColumnDataType.Decimal:
                Decimal xD = DataParseUtility.ParseDecimal(lviX.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                Decimal yD = DataParseUtility.ParseDecimal(lviY.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                result = Decimal.Compare(xD, yD);
                break;
            case ColumnDataType.Short:
                short xShort = DataParseUtility.ParseShort(lviX.SubItems[ColumnIndex].Text);
                short yShort = DataParseUtility.ParseShort(lviY.SubItems[ColumnIndex].Text);
                result = xShort.CompareTo(yShort);
                break;
            case ColumnDataType.Int:
                int xInt = DataParseUtility.ParseInt(lviX.SubItems[ColumnIndex].Text);
                int yInt = DataParseUtility.ParseInt(lviY.SubItems[ColumnIndex].Text);
                return xInt.CompareTo(yInt);
                break;
            case ColumnDataType.Long:
                long xLong = DataParseUtility.ParseLong(lviX.SubItems[ColumnIndex].Text);
                long yLong = DataParseUtility.ParseLong(lviY.SubItems[ColumnIndex].Text);
                return xLong.CompareTo(yLong);
                break;
            default:

                result = string.Compare(
                    lviX.SubItems[ColumnIndex].Text,
                    lviY.SubItems[ColumnIndex].Text,
                    false);

                break;
        }

        if (SortDirection == SortOrder.Descending)
        {
            return -result;
        }
        else
        {
            return result;
        }
    }
}

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

C linked list inserting node at the end

I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.

void Append(List * l, Node * n)
{
    Node ** next = &list->Head;
    while (*next != NULL) next = &(*next)->Next;
    *next = n;
    n->Next = NULL;
}

How do I get the classes of all columns in a data frame?

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

Eclipse error "ADB server didn't ACK, failed to start daemon"

The best and the most efficient way without restarting any device or software is:

Run the following:

adt-bundle-windows-x86_64\sdk\platform-tools\adb.exe

And one more thing.. ADB is a self-dependent thing. You cannot do anything until unless it wants itself to work. There is one more way which I found out: Leave the device connected for 5-6 minutes and wait. Soon the device gets connected and tries to launch.

How to programmatically send SMS on the iPhone?

You need to use the MFMessageComposeViewController if you want to show creating and sending the message in your own app.

Otherwise, you can use the sharedApplication method.

Convert from List into IEnumerable format

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.

How do you uninstall the package manager "pip", if installed from source?

That way you haven't installed pip, you installed just the easy_install i.e. setuptools.

First you should remove all the packages you installed with easy_install using (see uninstall):

easy_install -m PackageName

This includes pip if you installed it using easy_install pip.

After this you remove the setuptools following the instructions from here:

If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:

setuptools-*.egg

If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:

pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/

How to apply two CSS classes to a single element

1) Use multiple classes inside the class attribute, separated by whitespace (ref):

<a class="c1 c2">aa</a>

2) To target elements that contain all of the specified classes, use this CSS selector (no space) (ref):

.c1.c2 {
}

nodeJs callbacks simple example

A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.

The simplest example I can think of in JavaScript is the setTimeout() function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);

You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);

Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs library to read a file. The fs module exposes two unique API functions: readFile and readFileSync.

The readFile function is asynchronous while readFileSync is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile and readFileSync instead of readFile and readFileAsync. Here is an example of using both functions.

Synchronous:

var data = fs.readFileSync('test.txt');
console.log(data);

The code above blocks thread execution until all the contents of test.txt are read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.

Asynchronous (with callback):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);

First we create a callback function that accepts two arguments err and data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err has a value before you do anything else. If so, stop execution of the callback and log the error.

Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch block.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}

In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.

In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.

Safe Area of Xcode 9

Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.

Refer link for more information.

Is it possible to have SSL certificate for IP address, not domain name?

The answer I guess, is yes. Check this link for instance.

Issuing an SSL Certificate to a Public IP Address

An SSL certificate is typically issued to a Fully Qualified Domain Name (FQDN) such as "https://www.domain.com". However, some organizations need an SSL certificate issued to a public IP address. This option allows you to specify a public IP address as the Common Name in your Certificate Signing Request (CSR). The issued certificate can then be used to secure connections directly with the public IP address (e.g., https://123.456.78.99.).

How to get height and width of device display in angular2 using typescript?

export class Dashboard {
    innerHeight: any;
    innerWidth: any;
    constructor() {
        this.innerHeight = (window.screen.height) + "px";
        this.innerWidth = (window.screen.width) + "px";
    }
}

Rails - How to use a Helper Inside a Controller

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to run Python script on terminal?

You need python installed on your system. Then you can run this in the terminal in the correct directory:

python gameover.py

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

Reading PDF documents in .Net

You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.

Alex

How to get the size of a JavaScript object?

Many thanks to everyone that has been working on code for this!

I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.

Anyway, I use it for something something like:

var myCache = {
    cache: {},
    order: [],
    size: 0,
    maxSize: 2 * 1024 * 1024, // 2mb

    add: function(key, object) {
        // Otherwise add new object
        var size = this.getObjectSize(object);
        if (size > this.maxSize) return; // Can't store this object

        var total = this.size + size;

        // Check for existing entry, as replacing it will free up space
        if (typeof(this.cache[key]) !== 'undefined') {
            for (var i = 0; i < this.order.length; ++i) {
                var entry = this.order[i];
                if (entry.key === key) {
                    total -= entry.size;
                    this.order.splice(i, 1);
                    break;
                }
            }
        }

        while (total > this.maxSize) {
            var entry = this.order.shift();
            delete this.cache[entry.key];
            total -= entry.size;
        }

        this.cache[key] = object;
        this.order.push({ size: size, key: key });
        this.size = total;
    },

    get: function(key) {
        var value = this.cache[key];
        if (typeof(value) !== 'undefined') { // Return this key for longer
            for (var i = 0; i < this.order.length; ++i) {
                var entry = this.order[i];
                if (entry.key === key) {
                    this.order.splice(i, 1);
                    this.order.push(entry);
                    break;
                }
            }
        }
        return value;
    },

    getObjectSize: function(object) {
        // Code from above estimating functions
    },
};

It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
 print "Please choose what you'd like to do:"

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

AngularJS ng-repeat handle empty list case

i usually use ng-show

<li ng-show="variable.length"></li>

where variable you define for example

<div class="list-group-item" ng-repeat="product in store.products">
   <li ng-show="product.length">show something</li>
</div>

NSCameraUsageDescription in iOS 10.0 runtime crash?

I checked the plist and found it is not working, only in the "project" info, you need to add the "Privacy - Camera ....", then it should work. Hope to help you.

How to set a header in an HTTP response?

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

========================

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

Java parsing XML document gives "Content not allowed in prolog." error

The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.

Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).

Comparing two dataframes and getting the differences

One important detail to notice is that your data has duplicate index values, so to perform any straightforward comparison we need to turn everything as unique with df.reset_index() and therefore we can perform selections based on conditions. Once in your case the index is defined, I assume that you would like to keep de index so there are a one-line solution:

[~df2.reset_index().isin(df1.reset_index())].dropna().set_index('Date')

Once the objective from a pythonic perspective is to improve readability, we can break a little bit:

# keep the index name, if it does not have a name it uses the default name
index_name = df.index.name if df.index.name else 'index' 

# setting the index to become unique
df1 = df1.reset_index()
df2 = df2.reset_index()

# getting the differences to a Dataframe
df_diff = df2[~df2.isin(df1)].dropna().set_index(index_name)

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

How to find the .NET framework version of a Visual Studio project?

It's as easy as in your Visual studio.

  1. go to the 4th menu option on top, 'website'.
  2. under websites go to option, 'start options'.
  3. under start options, go to 'build' option.
  4. change the target framework there to what so ever framework.

Popup window in winform c#

Forms in C# are classes that inherit the Form base class.

You can show a popup by creating an instance of the class and calling ShowDialog().

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

C# adding a character in a string

Remember a string is immutable so you will need to create a new string.

Strings are IEnumerable so you should be able to run a for loop over it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            var builder = new StringBuilder();
            int count = 0;
            foreach (var c in alpha)
            {
                builder.Append(c);
                if ((++count % 5) == 0)
                {
                    builder.Append('-');
                }
            }
            Console.WriteLine("Before: {0}", alpha);
            alpha = builder.ToString();
            Console.WriteLine("After: {0}", alpha);
        }
    }
}

Produces this:

Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

How to print like printf in Python3?

The most recommended way to do is to use format method. Read more about it here

a, b = 1, 2

print("a={0},b={1}".format(a, b))

W3WP.EXE using 100% CPU - where to start?

If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.

What does -z mean in Bash?

-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

PHP/MySQL Insert null values

This is one example where using prepared statements really saves you some trouble.

In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', NULL);

However, if you want to insert a value in that field, you must now branch your code to add the single quotes:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', 'String Value');

Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:

$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);

$field1 = "String Value";
$field2 = null;

$stmt->execute();

It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Liquibase lock - reasons?

Sometimes if the update application is abruptly stopped, then the lock remains stuck.

Then running

UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

against the database helps.

You may also need to replace LOCKED=0 with LOCKED=FALSE.

Or you can simply drop the DATABASECHANGELOGLOCK table, it will be recreated.

What's the right way to decode a string that has special HTML entities in it?

There's JS function to deal with &#xxxx styled entities:
function at GitHub

// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
  return str.replace(/&#(\d+);/g, function(match, dec) {
    return String.fromCharCode(dec);
  });
};

var encodeHtmlEntity = function(str) {
  var buf = [];
  for (var i=str.length-1;i>=0;i--) {
    buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
  }
  return buf.join('');
};

var entity = '&#39640;&#32423;&#31243;&#24207;&#35774;&#35745;';
var str = '??????';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true

How to break lines in PowerShell?

Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n

How to loop through all but the last item of a list?

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])):

Convert wchar_t to char

In general, no. int(wchar_t(255)) == int(char(255)) of course, but that just means they have the same int value. They may not represent the same characters.

You would see such a discrepancy in the majority of Windows PCs, even. For instance, on Windows Code page 1250, char(0xFF) is the same character as wchar_t(0x02D9) (dot above), not wchar_t(0x00FF) (small y with diaeresis).

Note that it does not even hold for the ASCII range, as C++ doesn't even require ASCII. On IBM systems in particular you may see that 'A' != 65

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;

...

div {
    height: ~"calc(100vh - "@some-variable-height~")";
}

compiles to

div {
    height: calc(100vh - 10px );
}

How to use std::sort to sort an array in C++

In C++0x/11 we get std::begin and std::end which are overloaded for arrays:

#include <algorithm>

int main(){
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}

If you don't have access to C++0x, it isn't hard to write them yourself:

// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
  return c.begin();
}

template<class Cont>
typename Cont::iterator end(Cont& c){
  return c.end();
}

// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
  return c.begin();
}

template<class Cont>
typename Cont::const_iterator end(Cont const& c){
  return c.end();
}

// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
  return &arr[0];
}

template<class T, std::size_t N>
T* end(T (&arr)[N]){
  return arr + N;
}

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

Data binding to SelectedItem in a WPF Treeview

I know this thread is 10 years old but the problem still exists....

The original question was 'to retrieve' the selected item. I also needed to "get" the selected item in my viewmodel (not set it). Of all the answers in this thread, the one by 'Wes' is the only one that approaches the problem differently: If you can use the 'Selected Item' as a target for databinding use it as a source for databinding. Wes did it to another view property, I will do it to a viewmodel property:

We need two things:

  • Create a dependency property in the viewmodel (in my case of type 'MyObject' as my treeview is bound to object of the 'MyObject' type)
  • Bind from the Treeview.SelectedItem to this property in the View's constructor (yes that is code behind but, it's likely that you will init your datacontext there as well)

Viewmodel:

public static readonly DependencyProperty SelectedTreeViewItemProperty = DependencyProperty.Register("SelectedTreeViewItem", typeof(MyObject), typeof(MyViewModel), new PropertyMetadata(OnSelectedTreeViewItemChanged));

    private static void OnSelectedTreeViewItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as MyViewModel).OnSelectedTreeViewItemChanged(e);
    }

    private void OnSelectedTreeViewItemChanged(DependencyPropertyChangedEventArgs e)
    {
        //do your stuff here
    }

    public MyObject SelectedWorkOrderTreeViewItem
    {
        get { return (MyObject)GetValue(SelectedTreeViewItemProperty); }
        set { SetValue(SelectedTreeViewItemProperty, value); }
    }

View constructor:

Binding binding = new Binding("SelectedItem")
        {
            Source = treeView, //name of tree view in xaml
            Mode = BindingMode.OneWay
        };

        BindingOperations.SetBinding(DataContext, MyViewModel.SelectedTreeViewItemProperty, binding);

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

I used this command and it worked fine with me:

>git push -f origin master

But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME

Spark java.lang.OutOfMemoryError: Java heap space

Setting these exact configurations helped resolving the issue.

spark-submit --conf spark.yarn.maxAppAttempts=2 --executor-memory 10g --num-executors 50 --driver-memory 12g

How to import and use image in a Vue single file component?

These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">

Paste text on Android Emulator

Using Visual Studio Emulator, Here's my method.

First Mound a virtual sd card:

  1. Use the Additional Tools (small >> icon) for the emulator and go to the SD Card tab.
  2. Select a folder on your computer to sync with the virtual SD card.
  3. Pull from SD card, which will create a folder structure on the selected folder.

Set up a text file to transfer text:

  1. Use Google Play Store to install a text editor of your choice
  2. Create a text file containing your text on you computer in the download directory of the virtual sd card directory you created before.

Whenever I need to send text to the clip board.

  1. Edit the text file created above.
  2. Go to Additional Tools (small >> icon) and chose Push To SD Card.
  3. Open the text file in the text editor I installed and copy the text to the clip board. (Hold down the mouse when the dialog opens, choose select all and then click the copy icon)

Once set up it pretty easy to repeat. The same method would be applicable to other emulators by you may need to use a different method to push your text file to emulator.

Are there any Java method ordering conventions?

Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)

What uses are there for "placement new"?

See the fp.h file in the xll project at http://xll.codeplex.com It solves the "unwarranted chumminess with the compiler" issue for arrays that like to carry their dimensions around with them.

typedef struct _FP
{
    unsigned short int rows;
    unsigned short int columns;
    double array[1];        /* Actually, array[rows][columns] */
} FP;

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

Using setattr() in python

To add to the other answers, a common use case I have found for setattr() is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:

configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }

If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:

MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...

However, it is much easier and less verbose to loop over the configs, and setattr() like so:

for name, val in configs.items():
    setattr(MyClass, name, val)

As long as your dictionary keys have the proper names, this works very well and is nice and tidy.

*Note, the dict keys need to be strings as they will be the class object names.

Anonymous method in Invoke call

Because Invoke/BeginInvoke accepts Delegate (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; MethodInvoker (2.0) or Action (3.5) are common choices (note they have the same signature); like so:

control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});

If you need to pass in parameters, then "captured variables" are the way:

string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});

(caveat: you need to be a bit cautious if using captures async, but sync is fine - i.e. the above is fine)

Another option is to write an extension method:

public static void Invoke(this Control control, Action action)
{
    control.Invoke((Delegate)action);
}

then:

this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });

You can of course do the same with BeginInvoke:

public static void BeginInvoke(this Control control, Action action)
{
    control.BeginInvoke((Delegate)action);
}

If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a Form base-class.

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

Implicit type conversion rules in C++ operators

Arithmetic operations involving float results in float.

int + float = float
int * float = float
float * int = float
int / float = float
float / int = float
int / int = int

For more detail answer. Look at what the section §5/9 from the C++ Standard says

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)

— Then, if either operand is unsigned long the other shall be converted to unsigned long.

— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.

— Otherwise, if either operand is long, the other shall be converted to long.

— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int ]

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

Read file from resources folder in Spring Boot

See my answer here: https://stackoverflow.com/a/56854431/4453282

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

Use these 2 imports.

Declare

@Autowired
ResourceLoader resourceLoader;

Use this in some function

Resource resource=resourceLoader.getResource("classpath:preferences.json");

In your case, as you need the file you may use following

File file = resource.getFile()

Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

If you press CTRL + I it will just format tabs/whitespaces in code and pressing CTRL + SHIFT + F format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

This is a "feature" of the M2E plugin that had been introduced a while ago. It's not directly related to the JBoss EAR plugin but also happens with most other Maven plugins.

If you have a plugin execution defined in your pom (like the execution of maven-ear-plugin:generate-application-xml), you also need to add additional config information for M2E that tells M2E what to do when the build is run in Eclipse, e.g. should the plugin execution be ignored or executed by M2E, should it be also done for incremental builds, ... If that information is missing, M2E complains about it by showing this error message:

"Plugin execution not covered by lifecycle configuration"

See here for a more detailed explanation and some sample config that needs to be added to the pom to make that error go away:

https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

First, checkout parent branch.Then type

git fetch --all --prune 
git checkout <your branch>

Hope it helps!.

How to download videos from youtube on java?

Regarding the format (mp4 or flv) decide which URL you want to use. Then use this tutorial to download the video and save it into a local directory.

Combine two tables that have no common fields

There are a number of ways to do this, depending on what you really want. With no common columns, you need to decide whether you want to introduce a common column or get the product.

Let's say you have the two tables:

parts:              custs:
+----+----------+   +-----+------+
| id | desc     |   |  id | name |
+----+----------+   +-----+------+
|  1 | Sprocket |   | 100 | Bob  |
|  2 | Flange   |   | 101 | Paul |
+----+----------+   +-----+------+

Forget the actual columns since you'd most likely have a customer/order/part relationship in this case; I've just used those columns to illustrate the ways to do it.

A cartesian product will match every row in the first table with every row in the second:

> select * from parts, custs;
      id desc     id  name
      -- ----     --- ----
      1  Sprocket 101 Bob
      1  Sprocket 102 Paul
      2  Flange   101 Bob
      2  Flange   102 Paul

That's probably not what you want since 1000 parts and 100 customers would result in 100,000 rows with lots of duplicated information.

Alternatively, you can use a union to just output the data, though not side-by-side (you'll need to make sure column types are compatible between the two selects, either by making the table columns compatible or coercing them in the select):

> select id as pid, desc, null as cid, null as name from parts
  union
  select null as pid, null as desc, id as cid, name from custs;
    pid desc     cid name
    --- ----     --- ----
                 101 Bob 
                 102 Paul
    1   Sprocket
    2   Flange

In some databases, you can use a rowid/rownum column or pseudo-column to match records side-by-side, such as:

id desc     id  name
-- ----     --- ----
1  Sprocket 101 Bob
2  Flange   101 Bob

The code would be something like:

select a.id, a.desc, b.id, b.name
from parts a, custs b
where a.rownum = b.rownum;

It's still like a cartesian product but the where clause limits how the rows are combined to form the results (so not a cartesian product at all, really).

I haven't tested that SQL for this since it's one of the limitations of my DBMS of choice, and rightly so, I don't believe it's ever needed in a properly thought-out schema. Since SQL doesn't guarantee the order in which it produces data, the matching can change every time you do the query unless you have a specific relationship or order by clause.

I think the ideal thing to do would be to add a column to both tables specifying what the relationship is. If there's no real relationship, then you probably have no business in trying to put them side-by-side with SQL.

If you just want them displayed side-by-side in a report or on a web page (two examples), the right tool to do that is whatever generates your report or web page, coupled with two independent SQL queries to get the two unrelated tables. For example, a two-column grid in BIRT (or Crystal or Jasper) each with a separate data table, or a HTML two column table (or CSS) each with a separate data table.

SyntaxError: Unexpected token function - Async Await Nodejs

include and specify the node engine version to the latest, say at this time I did add version 8.

{
  "name": "functions",
  "dependencies": {
    "firebase-admin": "~7.3.0",
    "firebase-functions": "^2.2.1",
  },
  "engines": {
    "node": "8"
  },
  "private": true
}

in the following file

package.json

MySQL - Rows to Columns

I make that into Group By hostId then it will show only first row with values,
like:

A   B  C
1  10
2      3

ListBox with ItemTemplate (and ScrollBar!)

I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?

If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible" then the scroll bars only appear when you have need of them.

Where do I find the definition of size_t?

As for "Why not use int or unsigned int?", simply because it's semantically more meaningful not to. There's the practical reason that it can be, say, typedefd as an int and then upgraded to a long later, without anyone having to change their code, of course, but more fundamentally than that a type is supposed to be meaningful. To vastly simplify, a variable of type size_t is suitable for, and used for, containing the sizes of things, just like time_t is suitable for containing time values. How these are actually implemented should quite properly be the implementation's job. Compared to just calling everything int, using meaningful typenames like this helps clarify the meaning and intent of your program, just like any rich set of types does.

Clear the form field after successful submission of php form

They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.

<input name="firstname" type="text" placeholder="First Name" required="required" 
value="<?php echo $_POST['firstname'];?>">
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE

Just remove this, or if you want a condition to not do so make a if statement to that echo or just cleanup the $_POST fields.

$_POST = array(); // lets pretend nothing was posted

Or, if successful, redirect the user to another page:

header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script

Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

It is located on the Android Studio folder itself, on where you installed it.

enter image description here

cat, grep and cut - translated to python

In Python, without external dependencies, it is something like this (untested):

with open("filename") as origin:
    for line in origin:
        if not "something" in line:
           continue
        try:
            print line.split('"')[1]
        except IndexError:
            print

How do I get a value of datetime.today() in Python that is "timezone aware"?

Here is a solution using a readable timezone and that works with today():

from pytz import timezone

datetime.now(timezone('Europe/Berlin'))
datetime.now(timezone('Europe/Berlin')).today()

You can list all timezones as follows:

import pytz

pytz.all_timezones
pytz.common_timezones # or

how to merge 200 csv files in Python

Over the solution that made @Adders and later on improved by @varun, I implemented some little improvement too leave the whole merged CSV with only the main header:

from glob import glob

filename = 'main.csv'

with open(filename, 'a') as singleFile:
    first_csv = True
    for csv in glob('*.csv'):
        if csv == filename:
            pass
        else:
            header = True
            for line in open(csv, 'r'):
                if first_csv and header:
                    singleFile.write(line)
                    first_csv = False
                    header = False
                elif header:
                    header = False
                else:
                    singleFile.write(line)
    singleFile.close()

Best regards!!!

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Another insidious problem is that it appears that binding redirects can just silently fail if the element has an incorrect configuration on any other dependentAssembly elements.

Ensure that you only have one element under each element.

In some instances, VS generates this:

  <dependentAssembly>
    <assemblyIdentity ...
    <assemblyIdentity ...
  </dependentAssembly>

Instead of

  <dependentAssembly>
    <assemblyIdentity ...
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity ...
  </dependentAssembly>

Took me a long time to realise this was the problem!

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Completing the solution of Ranadheer, using Server.MapPath to locate the file

System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);

How to dynamically insert a <script> tag via jQuery after page load?

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem.

As it turned out, I ran mvn clean package install.

Correct way is mvn clean install

How can I remove an SSH key?

If you're trying to perform an SSH-related operation and get the following error:

$ git fetch
no such identity: <ssh key path>: No such file or directory

You can remove the missing SSH key from your SSH agent with the following:

$ eval `ssh-agent -s`  # start ssh agent
$ ssh-add -D <ssh key path>  # delete ssh key

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

Frame Buster Buster ... buster code needed

Ok, so we know that were in a frame. So we location.href to another special page with the path as a GET variable. We now explain to the user what is going on and provide a link with a target="_TOP" option. It's simple and would probably work (haven't tested it), but it requires some user interaction. Maybe you could point out the offending site to the user and make a hall of shame of click jackers to your site somewhere.. Just an idea, but it night work..

keypress, ctrl+c (or some combo like that)

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});

Distribution certificate / private key not installed

If you are being stuck on this problem. After switch the computer and not able to upload your build to App Store. Simply click manage certificate on the error page, the + plus on the bottom left corner and create a new distribution certificate. Then you'll be good to go.

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

You need to stop the event from reaching (bubbling to) the parent (the div). See the part about bubbling here, and jQuery-specific API info here.

How do I add all new files to SVN

This will add all unknown (except ignored) files under the specified directory tree:

svn add --force path/to/dir

This will add all unknown (except ignored) files in the current directory and below:

svn add --force .

How to Iterate over a Set/HashSet without an Iterator?

There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

Method 2

for (String movie : movies) {
  System.out.println(movie);
}

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

Method 4

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

Method 5

// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));

Method 6

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");

What is (functional) reactive programming?

Dude, this is a freaking brilliant idea! Why didn't I find out about this back in 1998? Anyway, here's my interpretation of the Fran tutorial. Suggestions are most welcome, I am thinking about starting a game engine based on this.

import pygame
from pygame.surface import Surface
from pygame.sprite import Sprite, Group
from pygame.locals import *
from time import time as epoch_delta
from math import sin, pi
from copy import copy

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption('Functional Reactive System Demo')

class Time:
    def __float__(self):
        return epoch_delta()
time = Time()

class Function:
    def __init__(self, var, func, phase = 0., scale = 1., offset = 0.):
        self.var = var
        self.func = func
        self.phase = phase
        self.scale = scale
        self.offset = offset
    def copy(self):
        return copy(self)
    def __float__(self):
        return self.func(float(self.var) + float(self.phase)) * float(self.scale) + float(self.offset)
    def __int__(self):
        return int(float(self))
    def __add__(self, n):
        result = self.copy()
        result.offset += n
        return result
    def __mul__(self, n):
        result = self.copy()
        result.scale += n
        return result
    def __inv__(self):
        result = self.copy()
        result.scale *= -1.
        return result
    def __abs__(self):
        return Function(self, abs)

def FuncTime(func, phase = 0., scale = 1., offset = 0.):
    global time
    return Function(time, func, phase, scale, offset)

def SinTime(phase = 0., scale = 1., offset = 0.):
    return FuncTime(sin, phase, scale, offset)
sin_time = SinTime()

def CosTime(phase = 0., scale = 1., offset = 0.):
    phase += pi / 2.
    return SinTime(phase, scale, offset)
cos_time = CosTime()

class Circle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
    @property
    def size(self):
        return [self.radius * 2] * 2
circle = Circle(
        x = cos_time * 200 + 250,
        y = abs(sin_time) * 200 + 50,
        radius = 50)

class CircleView(Sprite):
    def __init__(self, model, color = (255, 0, 0)):
        Sprite.__init__(self)
        self.color = color
        self.model = model
        self.image = Surface([model.radius * 2] * 2).convert_alpha()
        self.rect = self.image.get_rect()
        pygame.draw.ellipse(self.image, self.color, self.rect)
    def update(self):
        self.rect[:] = int(self.model.x), int(self.model.y), self.model.radius * 2, self.model.radius * 2
circle_view = CircleView(circle)

sprites = Group(circle_view)
running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
    screen.fill((0, 0, 0))
    sprites.update()
    sprites.draw(screen)
    pygame.display.flip()
pygame.quit()

In short: If every component can be treated like a number, the whole system can be treated like a math equation, right?

"Correct" way to specifiy optional arguments in R functions

You could also use missing() to test whether or not the argument y was supplied:

fooBar <- function(x,y){
    if(missing(y)) {
        x
    } else {
        x + y
    }
}

fooBar(3,1.5)
# [1] 4.5
fooBar(3)
# [1] 3

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

Fatal error: Call to undefined function mb_detect_encoding()

Mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option.

In case your php version is 7.0:

sudo apt-get install php7.0-mbstring

sudo service apache2 restart

In case your php version is 5.6:

sudo apt-get install php5.6-mbstring

sudo service apache2 restart

Border Height on CSS

I have another possibility. This is of course a "newer" technique, but for my projects works sufficient.

It only works if you need one or two borders. I've never done it with 4 borders... and to be honest, I don't know the answer for that yet.

.your-item {
  position: relative;
}

.your-item:after {
  content: '';
  height: 100%; //You can change this if you want smaller/bigger borders
  width: 1px;

  position: absolute;
  right: 0;
  top: 0; // If you want to set a smaller height and center it, change this value

  background-color: #000000; // The color of your border
}

I hope this helps you too, as for me, this is an easy workaround.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

Python recursive folder read

I've found the following to be the easiest

from glob import glob
import os

files = [f for f in glob('rootdir/**', recursive=True) if os.path.isfile(f)]

Using glob('some/path/**', recursive=True) gets all files, but also includes directory names. Adding the if os.path.isfile(f) condition filters this list to existing files only

What is the error "Every derived table must have its own alias" in MySQL?

Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever), which can the be used to refer to it in the rest of the outer query.

SELECT ID FROM (
    SELECT ID, msisdn FROM (
        SELECT * FROM TT2
    ) AS T
) AS T

In your case, of course, the entire query could be replaced with:

SELECT ID FROM TT2

getting a checkbox array value from POST

I just used the following code:

<form method="post">
    <input id="user1" value="user1"  name="invite[]" type="checkbox">
    <input id="user2" value="user2"  name="invite[]" type="checkbox">
    <input type="submit">
</form>

<?php
    if(isset($_POST['invite'])){
        $invite = $_POST['invite'];
        print_r($invite);
    }
?>

When I checked both boxes, the output was:

Array ( [0] => user1 [1] => user2 )

I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

Understanding REST: Verbs, error codes, and authentication

re 1: This looks fine so far. Remember to return the URI of the newly created user in a "Location:" header as part of the response to POST, along with a "201 Created" status code.

re 2: Activation via GET is a bad idea, and including the verb in the URI is a design smell. You might want to consider returning a form on a GET. In a Web app, this would be an HTML form with a submit button; in the API use case, you might want to return a representation that contains a URI to PUT to to activate the account. Of course you can include this URI in the response on POST to /users, too. Using PUT will ensure your request is idempotent, i.e. it can safely be sent again if the client isn't sure about success. In general, think about what resources you can turn your verbs into (sort of "nounification of verbs"). Ask yourself what method your specific action is most closely aligned with. E.g. change_password -> PUT; deactivate -> probably DELETE; add_credit -> possibly POST or PUT. Point the client to the appropriate URIs by including them in your representations.

re 3. Don't invent new status codes, unless you believe they're so generic they merit being standardized globally. Try hard to use the most appropriate status code available (read about all of them in RFC 2616). Include additional information in the response body. If you really, really are sure you want to invent a new status code, think again; if you still believe so, make sure to at least pick the right category (1xx -> OK, 2xx -> informational, 3xx -> redirection; 4xx-> client error, 5xx -> server error). Did I mention that inventing new status codes is a bad idea?

re 4. If in any way possible, use the authentication framework built into HTTP. Check out the way Google does authentication in GData. In general, don't put API keys in your URIs. Try to avoid sessions to enhance scalability and support caching - if the response to a request differs because of something that has happened before, you've usually tied yourself to a specific server process instance. It's much better to turn session state into either client state (e.g. make it part of subsequent requests) or make it explicit by turning it into (server) resource state, i.e. give it its own URI.

CSS for grabbing cursors (drag & drop)

I think move would probably be the closest standard cursor value for what you're doing:

move
Indicates something is to be moved.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

How to handle the `onKeyPress` event in ReactJS?

render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Awaiting multiple Tasks with different results

Use Task.WhenAll and then await the results:

var tCat = FeedCat();
var tHouse = SellHouse();
var tCar = BuyCar();
await Task.WhenAll(tCat, tHouse, tCar);
Cat cat = await tCat;
House house = await tHouse;
Tesla car = await tCar; 
//as they have all definitely finished, you could also use Task.Value.

Inserting NOW() into Database with CodeIgniter's Active Record

Using the date helper worked for me

$this->load->helper('date');

You can find documentation for date_helper here.

$data = array(
  'created' => now(),
  'modified' => now()
);

$this->db->insert('TABLENAME', $data);

Skip a submodule during a Maven build

The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.

Suppose your project is structured as:

project-root
  |
  + --- ci
  |
  + --- client
  |
  + --- server

The project-root/pom.xml defines modules

<modules>
  <module>ci</module>
  <module>client</module>
  <module>server</module>
</modules>

The ci/pom.xml defines profiles such as:

... 
<profiles>
  <profile>
    <id>default</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>true</skip>
       </configuration>
     </plugin>
  </profile>
  <profile>
    <id>CI</id>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>false</skip>
       </configuration>
     </plugin>
  </profile>
</profiles>

This will result in Maven skipping tests in this module except when the profile named CI is active. Your CI server must be instructed to execute mvn clean package -P CI. The Maven web site has an in-depth explanation of the profiling mechanism.

What does the "@" symbol do in SQL?

@ followed by a number is the parameters in the order they're listed in a function.

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}