Programs & Examples On #Lexical closures

Lexical closures are functions, often anonymous, that capture, or close over, their lexical environment. Lexical closures are used extensively in functional programming techniques that involve higher-order functions.

Getting a Request.Headers value

if (Request.Headers["XYZComponent"].Count() > 0)

... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:

Use this instead:

if(Request.Headers["XYZComponent"] != null)

Or if you want to treat blank or empty strings as not set then use:

if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)

The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.

A variation of your second attempt will also work:

if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))

Edit: Sorry didn't realise you were explicitly checking for the value true:

bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;

Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'

How to convert date to string and to date again?

Convert Date to String using this function

public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return dateStr;
    }

From Convert Date to String in Java . And convert string to date again

public Date convertStringToDate(String dateStr, String format) {
        Date date = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            date = df.parse(dateStr);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return date;
    }

From Convert String to date in Java

Python code to remove HTML tags from a string

Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

import re

TAG_RE = re.compile(r'<[^>]+>')

def remove_tags(text):
    return TAG_RE.sub('', text)

However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

Custom format for time command

Use the bash built-in variable SECONDS. Each time you reference the variable it will return the elapsed time since the script invocation.

Example:

echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"

Output:

Start 0
Middle 10
End 20

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

jquery to change style attribute of a div class

In order to change the attribute of the class conditionally,

var css_val = $(".handle").css('left');
if(css_val == '336px')
{
  $(".handle").css('left','300px');
}

If id is given as following,

<a id="handle" class="handle" href="#" style="left: 336px;"></a>

Here is an alternative solution:

var css_val = $("#handle").css('left');
if(css_val == '336px')
{
  $("#handle").css('left','300px');
}

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

HTML table needs spacing between columns, not rows

The better approach uses Shredder's css rule: padding: 0 15px 0 15px only instead of inline css, define a css rule that applies to all tds. Do This by using a style tag in your page:

<style type="text/css">
td
{
    padding:0 15px;
}
</style>

or give the table a class like "paddingBetweenCols" and in the site css use

.paddingBetweenCols td
{
    padding:0 15px;
}

The site css approach defines a central rule that can be reused by all pages.

If your doing to use the site css approach, it would be best to define a class like above and apply the padding to the class...unless you want all td's on the entire site to have the same rule applied.

Fiddle for using style tag

Fiddle for using site css

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

    {
        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    }
    
  • Save and close "keybindings.json"


Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. - https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

Maven dependency for Servlet 3.0 API?

This seems to be added recently:

https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

Using underscores in Java variables and method names

using 'm_' or '_' in the front of a variable makes it easier to spot member variables in methods throughout an object.

As a side benefit typing 'm_' or '_' will make intellsense pop them up first ;)

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

Excel Reference To Current Cell

Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )

How to clear react-native cache?

I went into this issue today, too. The cause was kinda silly -- vscode auto imported something from express-validator and caused the bug.

Just mentioning this in case anyone has done all the steps to clear cache/ delete modules or what not.

Reset select2 value and show placeholder

You can clear te selection by

$('#object').empty();

But it wont turn you back to your placeholder.

So its a half solution

Print newline in PHP in single quotes

I wonder why no one added the alternative of using the function chr():

echo 'Hello World!' . chr(10);

or, more efficient if you're going to repeat it a million times:

define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;

This avoids the silly-looking notation of concatenating a single- and double-quoted string.

Open Source Alternatives to Reflector?

Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.

I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.

I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.

How do I serialize a C# anonymous type to a JSON string?

Assuming you are using this for a web service, you can just apply the following attribute to the class:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

Updating a local repository with changes from a GitHub repository

This should work for every default repo:

git pull origin master

If your default branch is different than master, you will need to specify the branch name:

git pull origin my_default_branch_name

How to fix UITableView separator on iOS 7?

UITableView has a property separatorInset. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.

[tableView setSeparatorInset:UIEdgeInsetsZero];

Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

Uploading multiple files using formData()

This one worked for me

_x000D_
_x000D_
//Javascript part_x000D_
//file_input is a file input id_x000D_
var formData = new FormData();_x000D_
var filesLength=document.getElementById('file_input').files.length;_x000D_
for(var i=0;i<filesLength;i++){_x000D_
 formData.append("file[]", document.getElementById('file_input').files[i]);_x000D_
}_x000D_
$.ajax({_x000D_
   url: 'upload.php',_x000D_
   type: 'POST',_x000D_
   data: formData,_x000D_
   contentType: false,_x000D_
   cache: false,_x000D_
   processData: false,_x000D_
   success: function (html) {_x000D_
   _x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?php_x000D_
//PHP part_x000D_
$file_names = $_FILES["file"]["name"];_x000D_
for ($i = 0; $i < count($file_names); $i++) {_x000D_
   $file_name=$file_names[$i];_x000D_
   $extension = end(explode(".", $file_name));_x000D_
   $original_file_name = pathinfo($file_name, PATHINFO_FILENAME);_x000D_
   $file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;_x000D_
 move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);_x000D_
}
_x000D_
_x000D_
_x000D_

How do I align a label and a textarea?

You need to put them both in some container element and then apply the alignment on it.

For example:

_x000D_
_x000D_
.formfield * {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<p class="formfield">_x000D_
  <label for="textarea">Label for textarea</label>_x000D_
  <textarea id="textarea" rows="5">Textarea</textarea>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to make a Java thread wait for another thread's output?

public class ThreadEvent {

    private final Object lock = new Object();

    public void signal() {
        synchronized (lock) {
            lock.notify();
        }
    }

    public void await() throws InterruptedException {
        synchronized (lock) {
            lock.wait();
        }
    }
}

Use this class like this then:

Create a ThreadEvent:

ThreadEvent resultsReady = new ThreadEvent();

In the method this is waiting for results:

resultsReady.await();

And in the method that is creating the results after all the results have been created:

resultsReady.signal();

EDIT:

(Sorry for editing this post, but this code has a very bad race condition and I don't have enough reputation to comment)

You can only use this if you are 100% sure that signal() is called after await(). This is the one big reason why you cannot use Java object like e.g. Windows Events.

The if the code runs in this order:

Thread 1: resultsReady.signal();
Thread 2: resultsReady.await();

then thread 2 will wait forever. This is because Object.notify() only wakes up one of the currently running threads. A thread waiting later is not awoken. This is very different from how I expect events to work, where an event is signalled until a) waited for or b) explicitly reset.

Note: Most of the time, you should use notifyAll(), but this is not relevant to the "wait forever" problem above.

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

Using FFmpeg in .net?

You can use this nuget package:

Install-Package Xabe.FFmpeg

I'm trying to make easy to use, cross-platform FFmpeg wrapper.

You can find more information about this at Xabe.FFmpeg

More info in documentation

Conversion is simple:

IConversionResult result = await Conversion.ToMp4(Resources.MkvWithAudio, output).Start();

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

Get a specific bit from byte

This

public static bool GetBit(this byte b, int bitNumber) {
   return (b & (1 << bitNumber)) != 0;
}

should do it, I think.

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

How can I get query string values in JavaScript?

The following code will create an object which has two methods:

  1. isKeyExist: Check if a particular parameter exist
  2. getValue: Get the value of a particular parameter.

 

var QSParam = new function() {
       var qsParm = {};
       var query = window.location.search.substring(1);
       var params = query.split('&');
       for (var i = 0; i < params.length; i++) {
           var pos = params[i].indexOf('=');
           if (pos > 0) {
               var key = params[i].substring(0, pos);
               var val = params[i].substring(pos + 1);
               qsParm[key] = val;
           }
       }
       this.isKeyExist = function(query){
           if(qsParm[query]){
               return true;
           }
           else{
              return false;
           }
       };
       this.getValue = function(query){
           if(qsParm[query])
           {
               return qsParm[query];
           }
           throw "URL does not contain query "+ query;
       }
};

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Don't include the whole play services library but use the one that you need.Replace the line in your build.gradle:

compile 'com.google.android.gms:play-services:9.6.1'

with the appropriate one from Google Play Services APIs,like for example:

compile 'com.google.android.gms:play-services-gcm:9.6.1'

What does '--set-upstream' do?

When you push to a remote and you use the --set-upstream flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.

Adding a remote tracking branch means that git then knows what you want to do when you git fetch, git pull or git push in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.

You could achieve the same thing with git branch --set-upstream-to or git checkout --track. See the git help pages on tracking branches for more information.

Batch / Find And Edit Lines in TXT file

You can always use "FAR" = "Find and Replace". It's written under java, so it works where Java works (pretty much everywhere). Works with directories and subdirectories, searches and replaces within files, also can renames them. Also can rename bulk files.Licence = free, for both individuals or comapnies. Very fast and maintained by the developer. Find it here: http://findandreplace.sourceforge.net/

Also you can use GrepWin. Works pretty much the same. You can find it here: http://tools.tortoisesvn.net/grepWin.html

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

C# how to wait for a webpage to finish loading before continuing

Task method worked for me, except Browser.Task.IsCompleted has to be changed to PageLoaded.Task.IsCompleted.

Sorry I didnt add comment, that is because I need higher reputation to add comments.

Laravel 5 – Clear Cache in Shared Hosting Server

Use the code below with the new clear cache commands: php artisan cache clear

//Clear route cache:
 Route::get('/route-cache', function() {
     // EDIT - the linked article uses route:cache, it should be route:clear
     // $exitCode = Artisan::call('route:cache');
     $exitCode = Artisan::call('route:clear');
     return 'Routes cache cleared';
 });

 //Clear config cache:
 Route::get('/config-cache', function() {
     $exitCode = Artisan::call('config:clear');
     return 'Config cache cleared';
 }); 

// Clear application cache:
 Route::get('/clear-cache', function() {
     $exitCode = Artisan::call('cache:clear');
     return 'Application cache cleared';
 });

 // Clear view cache:
 Route::get('/view-clear', function() {
     $exitCode = Artisan::call('view:clear');
     return 'View cache cleared';
 });

Iterating through all nodes in XML file

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}

Naming returned columns in Pandas aggregate function?

If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:

newidx = []
for (n1,n2) in df.columns.ravel():
    newidx.append("%s-%s" % (n1,n2))
df.columns=newidx

It will change your dataframe from:

    I                       V
    mean        std         first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

to

    I-mean      I-std       V-first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

Delete rows with blank values in one particular column

Alternative solution can be to remove the rows with blanks in one variable:

df <- subset(df, VAR != "")

Copy Data from a table in one Database to another separate database

We can three part naming like database_name..object_name

The below query will create the table into our database(with out constraints)

SELECT * 
INTO DestinationDB..MyDestinationTable 
FROM SourceDB..MySourceTable 

Alternatively you could:

INSERT INTO DestinationDB..MyDestinationTable 
SELECT * FROM SourceDB..MySourceTable

If your destination table exists and is empty.

How do I get list of methods in a Python class?

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

So

print find_defining_class(car, 'speedometer') 

Think Python page 210

Provisioning Profiles menu item missing from Xcode 5

After searching a few times in google, i found one software for provisioning profiles.

Install this iPhone configuration utility software and manage your all provisioning profiles in MAC.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

Get element from within an iFrame

If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:

What's the most concise way to read query parameters in AngularJS?

$location.search() will work only with HTML5 mode turned on and only on supporting browser.

This will work always:

$window.location.search

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

How do you Encrypt and Decrypt a PHP String?

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

Get the string within brackets in Python

This should do the job:

re.match(r"[^[]*\[([^]]*)\]", yourstring).groups()[0]

Editable text to string

If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

SELECTING with multiple WHERE conditions on same column

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

Define constant variables in C++ header

You generally shouldn't use e.g. const int in a header file, if it's included in several source files. That is because then the variables will be defined once per source file (translation units technically speaking) because global const variables are implicitly static, taking up more memory than required.

You should instead have a special source file, Constants.cpp that actually defines the variables, and then have the variables declared as extern in the header file.

Something like this header file:

// Protect against multiple inclusions in the same source file
#ifndef CONSTANTS_H
#define CONSTANTS_H

extern const int CONSTANT_1;

#endif

And this in a source file:

const int CONSTANT_1 = 123;

How to display custom view in ActionBar?

The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.

But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:

https://stackoverflow.com/a/16517395/614880

His code at bottom worked perfectly for me.

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Unable to launch the IIS Express Web server

In my situation, the IIS Express applicationhost.config file had a typo in the managedRuntimeVersion attribute of several elements. This was happening for both Visual Studio 2012 and Visual Studio 2013. I only received the first part of the message, stating:

Unable to launch the IIS Express Web server.

It logged an error in the event log with the message:

The worker process failed to pre-load .Net Runtime version v4.030319.

The correct runtime version is v4.0.30319 (note the second period.)

The steps I took to correct:

  1. Navigate to C:\Users\\Documents\IISExpress\config
  2. Edit applicationhost.config
  3. Find the config section
  4. Correct any references to "v4.030319" to read "v4.0.30319"

Visual Studio successfully started IIS Express the next time I debugged a web application.

Fastest way to write huge data in text file Java

Only for the sake of statistics:

The machine is old Dell with new SSD

CPU: Intel Pentium D 2,8 Ghz

SSD: Patriot Inferno 120GB SSD

4000000 'records'
175.47607421875 MB

Iteration 0
Writing raw... 3.547 seconds
Writing buffered (buffer size: 8192)... 2.625 seconds
Writing buffered (buffer size: 1048576)... 2.203 seconds
Writing buffered (buffer size: 4194304)... 2.312 seconds

Iteration 1
Writing raw... 2.922 seconds
Writing buffered (buffer size: 8192)... 2.406 seconds
Writing buffered (buffer size: 1048576)... 2.015 seconds
Writing buffered (buffer size: 4194304)... 2.282 seconds

Iteration 2
Writing raw... 2.828 seconds
Writing buffered (buffer size: 8192)... 2.109 seconds
Writing buffered (buffer size: 1048576)... 2.078 seconds
Writing buffered (buffer size: 4194304)... 2.015 seconds

Iteration 3
Writing raw... 3.187 seconds
Writing buffered (buffer size: 8192)... 2.109 seconds
Writing buffered (buffer size: 1048576)... 2.094 seconds
Writing buffered (buffer size: 4194304)... 2.031 seconds

Iteration 4
Writing raw... 3.093 seconds
Writing buffered (buffer size: 8192)... 2.141 seconds
Writing buffered (buffer size: 1048576)... 2.063 seconds
Writing buffered (buffer size: 4194304)... 2.016 seconds

As we can see the raw method is slower the buffered.

WAMP/XAMPP is responding very slow over localhost

I had the same problem. Response times were extremly slow and refreshes worked quickly, most of the time. All suggestions made by bicycle didn't help. What seems to help best so far (no slow response times for the last 30mins) was to reset winsock as explained here: http://www.devside.net/wamp-server/wamp-is-running-very-slow

netsh winsock reset
netsh int ip reset C:\resetlog.txt

You need to restart after this.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

I changed my web.config file to use HTTPMODULE in two forms:

IIS: 6

<httpModules>
    <add name="Module" type="app.Module,app"/>
</httpModules>

IIS: 7.5

<system.webServer>
    <modules>
       <add name="Module" type="app.Module,app"/>
    </modules>
</system.webServer>

Uninstall Django completely

On Windows, I had this issue with static files cropping up under pydev/eclipse with python 2.7, due to an instance of django (1.8.7) that had been installed under cygwin. This caused a conflict between windows style paths and cygwin style paths. So, unfindable static files despite all the above fixes. I removed the extra distribution (so that all packages were installed by pip under windows) and this fixed the issue.

Get device token for push notification

To get Token Device you can do by some steps:

1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.

2) Redownload both Developer Provisioning and Distribute Provisioning file.

3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.

4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     [self.window addSubview:viewController.view];
     [self.window makeKeyAndVisible];

     NSLog(@"Registering for push notifications...");    
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
     return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
     NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
     NSLog(@"%@", str);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
     NSString *str = [NSString stringWithFormat: @"Error: %@", err];
     NSLog(@"%@",str);
}

Recommended add-ons/plugins for Microsoft Visual Studio

Not free, but ReSharper is definitely one recommendation.

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

Get escaped URL parameter

If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:

function getParameters() {
  var searchString = window.location.search.substring(1),
      params = searchString.split("&"),
      hash = {};

  if (searchString == "") return {};
  for (var i = 0; i < params.length; i++) {
    var val = params[i].split("=");
    hash[unescape(val[0])] = unescape(val[1]);
  }
  return hash;
}

Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:

{
  date:   '9/10/11',
  author: 'nilbus'
}

I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:

Function pointer as a member of a C struct

You can use also "void*" (void pointer) to send an address to the function.

typedef struct pstring_t {
    char * chars;
    int(*length)(void*);
} PString;

int length(void* self) {
    return strlen(((PString*)self)->chars);
}

PString initializeString() {
    PString str;
    str.length = &length;
    return str;
}

int main()
{
    PString p = initializeString();

    p.chars = "Hello";

    printf("Length: %i\n", p.length(&p));

    return 0;
}

Output:

Length: 5

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.

Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>.

There is no difference between python -m pip install, and pip install as long as you're using default installation settings and single python installation. python pip actually tries to run file pip in the current directory.

Edit. See the pipwin comment for automated way of using Mr Goblke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy.

cannot load such file -- bundler/setup (LoadError)

I had this because something bad was in my vendor/bundle. Nothing to do with Apache, just in local dev env.

To fix, I deleted vendor\bundle, and also deleted the reference to it in my .bundle/config so it wouldn't get re-used.

Then, I re-bundled (which then installed to GEM_HOME instead of vendor/bundle and the problem went away.

ImportError: No module named scipy

I recommend you to remove scipy via

apt-get purge scipy

and then to install it by

pip install scipy

If you do both then you might confuse you deb package manager due to possibly differing versions.

Cannot access a disposed object - How to fix?

I had the same problem and solved it using a boolean flag that gets set when the form is closing (the System.Timers.Timer does not have an IsDisposed property). Everywhere on the form I was starting the timer, I had it check this flag. If it was set, then don't start the timer. Here's the reason:

The Reason:

I was stopping and disposing of the timer in the form closing event. I was starting the timer in the Timer_Elapsed() event. If I were to close the form in the middle of the Timer_Elapsed() event, the timer would immediately get disposed by the Form_Closing() event. This would happen before the Timer_Elapsed() event would finish and more importantly, before it got to this line of code:

_timer.Start()

As soon as that line was executed an ObjectDisposedException() would get thrown with the error you mentioned.

The Solution:

Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
    ' set the form closing flag so the timer doesn't fire even after the form is closed.
    _formIsClosing = True
    _timer.Stop()
    _timer.Dispose()
End Sub

Here's the timer elapsed event:

Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed
    ' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)
    _timer.Stop()

    ' do work here

    ' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.
    If Not _formIsClosing Then
        _timer.Interval = _refreshInterval
        _timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.
    End If
End Sub

The interesting thing to know, even though it would throw the ObjectDisposedException when attempting to start the timer, the timer would still get started causing it to run even when the form was closed (the thread would only stop when the application was closed).

How to hide columns in an ASP.NET GridView with auto-generated columns?

As said by others, RowDataBound or RowCreated event should work but if you want to avoid events declaration and put the whole code just below DataBind function call, you can do the following:

GridView1.DataBind()
If GridView1.Rows.Count > 0 Then
    GridView1.HeaderRow.Cells(0).Visible = False
    For i As Integer = 0 To GridView1.Rows.Count - 1
        GridView1.Rows(i).Cells(0).Visible = False
    Next
End If

How do you comment out code in PowerShell?

Single line comments start with a hash symbol, everything to the right of the # will be ignored:

# Comment Here

In PowerShell 2.0 and above multi-line block comments can be used:

<# 
  Multi 
  Line 
#> 

You could use block comments to embed comment text within a command:

Get-Content -Path <# configuration file #> C:\config.ini

Note: Because PowerShell supports Tab Completion you need to be careful about copying and pasting Space + TAB before comments.

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

Take a char input from the Scanner

you just need to write this for getting value in char type.

char c = reader.next().charAt(0);

How can I hide the Android keyboard using JavaScript?

rdougan's post did not work for me but it was a good starting point for my solution.

function androidSoftKeyHideFix(selectorName){
    $(selectorName).on('focus', function (event) {
        $(selectorName).off('focus')
        $('body').on('touchend', function (event) {
            $('body').off('touchend')
            $('.blurBox').focus();
            setTimeout(function() {
                $('.blurBox').blur();
                $('.blurBox').focus();
                $('.blurBox').blur();
                androidSoftKeyHideFix(selectorName); 
            },1)
        });
    });
}    

You need an input element at the top of the body, I classed as 'blurBox'. It must not be display:none. So give it opacity:0, and position:absolute. I tried placing it at the bottom of the body and it didn't work.

I found it necessary to repeat the .focus() .blur() sequence on the blurBox. I tried it without and it doesn't work.

This works on my 2.3 Android. I imagine that custom keyboard apps could still have issues.

I encountered a number of issues before arriving at this. There was a bizarre issue with subsequent focuses retriggering a blur/focus, which seemed like an android bug. I used a touchend listener instead of a blur listener to get around the function refiring closing the keyboard immediately after a non-initial opening. I also had an issue with keyboard typing making the scroll jump around...which is realted to a 3d transform used on a parent. That emerged from an attempt to workaround the blur-refiring issue, where I didn't unblur the blurBox at the end. So this is a delicate solution.

When do you use map vs flatMap in RxJava?

FlatMap behaves very much like map, the difference is that the function it applies returns an observable itself, so it's perfectly suited to map over asynchronous operations.

In the practical sense, the function Map applies just makes a transformation over the chained response (not returning an Observable); while the function FlatMap applies returns an Observable<T>, that is why FlatMap is recommended if you plan to make an asynchronous call inside the method.

Summary:

  • Map returns an object of type T
  • FlatMap returns an Observable.

A clear example can be seen here: http://blog.couchbase.com/why-couchbase-chose-rxjava-new-java-sdk .

Couchbase Java 2.X Client uses Rx to provide asynchronous calls in a convenient way. Since it uses Rx, it has the methods map and FlatMap, the explanation in their documentation might be helpful to understand the general concept.

To handle errors, override onError on your susbcriber.

Subscriber<String> mySubscriber = new Subscriber<String>() {
    @Override
    public void onNext(String s) { System.out.println(s); }

    @Override
    public void onCompleted() { }

    @Override
    public void onError(Throwable e) { }
};

It might help to look at this document: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

A good source about how to manage errors with RX can be found at: https://gist.github.com/daschl/db9fcc9d2b932115b679

package android.support.v4.app does not exist ; in Android studio 0.8

In my case the problem was solved by appending the string cordova.system.library.2=com.android.support:support-v4:+ to platforms/android/project.properties file

How to declare an array of strings in C++?

You can directly declare an array of strings like string s[100];. Then if you want to access specific elements, you can get it directly like s[2][90]. For iteration purposes, take the size of string using the s[i].size() function.

How can I filter a date of a DateTimeField in Django?

assuming active_on is a date object, increment it by 1 day then do range

next_day = active_on + datetime.timedelta(1)
queryset = queryset.filter(date_created__range=(active_on, next_day) )

Create dataframe from a matrix

Using dplyr and tidyr:

library(dplyr)
library(tidyr)

df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
  gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
  select(name, time, val)         # reorder the columns

df
# A tibble: 6 x 3
   name  time   val
  <chr> <dbl> <dbl>
1   C_0   0.0   0.1
2   C_0   0.5   0.2
3   C_0   1.0   0.3
4   C_1   0.0   0.3
5   C_1   0.5   0.4
6   C_1   1.0   0.5

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your bean or pojo class should implements parcelable interface.

For example:

public class BeanClass implements Parcelable{
    String name;
    int age;
    String sex;

    public BeanClass(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    } 
     public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
        @Override
        public BeanClass createFromParcel(Parcel in) {
            return new BeanClass(in);
        }

        @Override
        public BeanClass[] newArray(int size) {
            return new BeanClass[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(sex);
    }
}

Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code

Activity1:

ArrayList<BeanClass> list=new ArrayList<BeanClass>();

private ArrayList<BeanClass> getList() {
    for(int i=0;i<5;i++) {

        list.add(new BeanClass("xyz", 25, "M"));
    }
    return list;
}
private void gotoNextActivity() {
    Intent intent=new Intent(this,Activity2.class);
    /* Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST",(Serializable)list);
    intent.putExtra("BUNDLE",args);*/

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("StudentDetails", list);
    intent.putExtras(bundle);
    startActivity(intent);
}

Activity2:

ArrayList<BeanClass> listFromActivity1=new ArrayList<>();

listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");

if (listFromActivity1 != null) {

    Log.d("listis",""+listFromActivity1.toString());
}

I think this basic to understand the concept.

How to semantically add heading to a list

Try defining a new class, ulheader, in css. p.ulheader ~ ul selects all that immediately follows My Header

p.ulheader ~ ul {
   margin-top:0;
{
p.ulheader {
   margin-bottom;0;
}

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

_x000D_
_x000D_
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
_x000D_
_x000D_

Looping through array and removing items, without breaking for loop

Here is another example for the proper use of splice. This example is about to remove 'attribute' from 'array'.

for (var i = array.length; i--;) {
    if (array[i] === 'attribute') {
        array.splice(i, 1);
    }
}

biggest integer that can be stored in a double

9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)

Program

#include <math.h>
#include <stdio.h>

int main(void) {
  double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
  while (dbl + 1 != dbl) dbl++;
  printf("%.0f\n", dbl - 1);
  printf("%.0f\n", dbl);
  printf("%.0f\n", dbl + 1);
  return 0;
}

Result

9007199254740991
9007199254740992
9007199254740992

Abort a Git Merge

If you do "git status" while having a merge conflict, the first thing git shows you is how to abort the merge.

output of git status while having a merge conflict

Why is conversion from string constant to 'char*' valid in C but invalid in C++

It's valid in C for historical reasons. C traditionally specified that the type of a string literal was char * rather than const char *, although it qualified it by saying that you're not actually allowed to modify it.

When you use a cast, you're essentially telling the compiler that you know better than the default type matching rules, and it makes the assignment OK.

HTML not loading CSS file

With HTML5 all you need is the rel, not even the type.

<link href="custom.css" rel="stylesheet"></link>

How to use NULL or empty string in SQL

by this function:

ALTER FUNCTION [dbo].[isnull](@input nvarchar(50),@ret int = 0)
RETURNS int
AS
BEGIN

    return (case when @input='' then @ret when @input is null then @ret else @input end)

END

and use this:

dbo.isnull(value,0)

What are the differences between a program and an application?

I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)

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

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

Unicode character for "X" cancel / close?

This is probably pedantry, but so far no one has really given a solution "to create a close button using CSS only." only. Here you go:

#close:before {
  content: "?";
  border: 1px solid gray;
  background-color:#eee;
  padding:0.5em;
  cursor: pointer;
}

http://codepen.io/anon/pen/VaWqYg

Open a new tab in the background?

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

How to copy to clipboard in Vim?

I have struggled a lot in copying to clipboard. Inside Vim it is quite simple using visual mode but if you want to copy to the clipboard things are quite messsed. I have simple method of copying using xclip utility. For this you must have to install xclip first.

for the whole file it is very simple

xclip -sel clip filename

but if you want to copy only a particular range of line numbers
tail -n +[n1] filename | head -n [n2] | xclip -sel clip

you can make use of ~/.bashrc to simplify this

#rangecp copy lines from n1 to n2 from a given file to clipboard
function rangecp()
{
    if [ -f $1 ]
    then
        if [ ! -z $3 ]
        then
            diff=$(($3 - $2 + 1))
            #diff=`expr $3 - $2 + 1`
            tail -n +$2  $1 | head -n $diff | xclip -sel clip
        elif [ ! -z $2 ]
        then
            tail -n +$2  $1 | xclip -sel clip
        else
            echo "Provide a range from [n1] lines to [n2] lines"
        fi
    else
        echo "[ $1 ] file doesn't exist"
    fi
}

then

source ~/.bashrc
How to use

rangecp filename.txt 50 89
rangecp filename.txt 50

How to use graphics.h in codeblocks?

AFAIK, in the epic DOS era there is a header file named graphics.h shipped with Borland Turbo C++ suite. If it is true, then you are out of luck because we're now in Windows era.

How to remove text from a string?

Using match() and Number() to return a number variable:

Number(("data-123").match(/\d+$/));

// strNum = 123

Here's what the statement above does...working middle-out:

  1. str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
  2. Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.

How to Use -confirm in PowerShell

Write-Warning "This is only a test warning." -WarningAction Inquire

from: https://serverfault.com/a/1015583/584478

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Unit testing click event in Angular

Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

Below is a very basic example to test the click event using fakeAsync.

The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

Here I am testing a method that is invoked by the click event.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

Below is what Angular docs have to say:

The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

There are limitations. For example, you cannot make an XHR call from within a fakeAsync

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Add transaction-manager to your <annotation-driven/> in spring-servlet.xml:

<tx:annotation-driven transaction-manager="yourTransactionBeanID"/>

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

How to know elastic search installed version from kibana?

from the Chrome Rest client make a GET request or curl -XGET 'http://localhost:9200' in console

rest client: http://localhost:9200

{
    "name": "node",
    "cluster_name": "elasticsearch-cluster",
    "version": {
        "number": "2.3.4",
        "build_hash": "dcxbgvzdfbbhfxbhx",
        "build_timestamp": "2016-06-30T11:24:31Z",
        "build_snapshot": false,
        "lucene_version": "5.5.0"
    },
    "tagline": "You Know, for Search"
}

where number field denotes the elasticsearch version. Here elasticsearch version is 2.3.4

Remove insignificant trailing zeros from a number?

I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

In addition to trimming the trailing zeros, I also had the need to round off and format the output for the user's current locale (i.e. 123,456.789).

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js


Usage Examples:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)


Updated - August, 2018


All modern browsers now support the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

let formatters = {
    default: new Intl.NumberFormat(),
    currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
    twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};

formatters.twoDecimal.format(1234.5678);  // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"

For older browsers, you can use this polyfill: https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en

Add/delete row from a table

jQuery has a nice function for removing elements from the DOM.

The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."

$(this).closest("tr").remove();

Each delete button could run that very succinct code with a function call.

Find the number of downloads for a particular app in apple appstore

Updated answer now that xyo.net has been bought and shut down.

appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

Outdated answer:

Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

xyo.net

How do you reverse a string in place in JavaScript?

without converting string to array;

String.prototype.reverse = function() {

    var ret = "";
    var size = 0;

    for (var i = this.length - 1; -1 < i; i -= size) {

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            size = 2;
            ret += this[i - 1] + this[i];
        } else {
            size = 1;
            ret += this[i];
        }
    }

    return ret;
}

console.log('ana~nam anañam' === 'mañana man~ana'.reverse());

using Array.reverse without converting characters to code points;

String.prototype.reverse = function() {

    var array = this.split("").reverse();

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

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            array[i - 1] = array[i - 1] + array[i];
            array[i] = array[i - 1].substr(0, 1);
            array[i - 1] = array[i - 1].substr(1, 1);
        }

    }

    return array.join("");
}

console.log('ana~nam anañam' === 'mañana man~ana'.reverse());

Pycharm/Python OpenCV and CV2 install error

You are getting those errors because opencv and cv2 are not the python package names.

These are both included as part of the opencv-python package available to install from pip.

If you are using python 2 you can install with pip:

 pip install opencv-python

Or use the equivilent for python 3:

pip3 install opencv-python

After running the appropriate pip command your package should be available to use from python.

In Javascript/jQuery what does (e) mean?

It's a reference to the current event object

It is more efficient to use if-return-return or if-else-return?

I know the question is tagged python, but it mentions dynamic languages so thought I should mention that in ruby the if statement actually has a return type so you can do something like

def foo
  rv = if (A > B)
         A+1
       else
         A-1
       end
  return rv 
end

Or because it also has implicit return simply

def foo 
  if (A>B)
    A+1
  else 
    A-1
  end
end

which gets around the style issue of not having multiple returns quite nicely.

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

Is there a WebSocket client implemented for Python?

http://pypi.python.org/pypi/websocket-client/

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()

Sample server code:

#!/usr/bin/python
import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(30000):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

How to store standard error in a variable

Here's how I did it :

#
# $1 - name of the (global) variable where the contents of stderr will be stored
# $2 - command to be executed
#
captureStderr()
{
    local tmpFile=$(mktemp)

    $2 2> $tmpFile

    eval "$1=$(< $tmpFile)"

    rm $tmpFile
}

Usage example :

captureStderr err "./useless.sh"

echo -$err-

It does use a temporary file. But at least the ugly stuff is wrapped in a function.

How do you clone a Git repository into a specific folder?

Although all of the answers above are good, I would like to propose a new method instead of using the symbolic link method in public html directory as proposed BEST in the accepted answer. You need to have access to your server virtual host configurations.

It is about configuring virtual host of your web server directly pointing to the repository directory. In Apache you can do it like:

DocumentRoot /var/www/html/website/your-git-repo

Here is an example of a virtual host file:

<VirtualHost *:443>
    ServerName example.com

    DocumentRoot /path/to/your-git-repo
    ...
    ...
    ...
    ...
</VirtualHost>

Tomcat 7 is not running on browser(http://localhost:8080/ )

When you start tomcat independently and type http://localhost:8080/, tomcat show its default page (tomcat has its default page at TOMCAT_ROOT_DIRECTORY\webapps\ROOT\index.jsp).

When you start tomcat from eclipse, eclipse doesn't have any default page for url http://localhost:8080/ so it show error message. This doesn't mean that tomcat7 is not running.when you put your project specific url like http://localhost:8080/PROJECT_NAME_YOU_HAVE_CREATE_USING_ECLIPSE will display the default page of your web project.

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

Authenticated HTTP proxy with Java

http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:

Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.

This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.

He suggests the following fix.

// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            String prot = getRequestingProtocol().toLowerCase();
            String host = System.getProperty(prot + ".proxyHost", "");
            String port = System.getProperty(prot + ".proxyPort", "80");
            String user = System.getProperty(prot + ".proxyUser", "");
            String password = System.getProperty(prot + ".proxyPassword", "");

            if (getRequestingHost().equalsIgnoreCase(host)) {
                if (Integer.parseInt(port) == getRequestingPort()) {
                    // Seems to be OK.
                    return new PasswordAuthentication(user, password.toCharArray());  
                }
            }
        }
        return null;
    }  
});

I haven't tried it yet, but it looks good to me.

I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).

Quicksort with Python

This is a version of the quicksort using Hoare partition scheme and with fewer swaps and local variables

def quicksort(array):
    qsort(array, 0, len(array)-1)

def qsort(A, lo, hi):
    if lo < hi:
        p = partition(A, lo, hi)
        qsort(A, lo, p)
        qsort(A, p + 1, hi)

def partition(A, lo, hi):
    pivot = A[lo]
    i, j = lo-1, hi+1
    while True:
      i += 1
      j -= 1
      while(A[i] < pivot): i+= 1
      while(A[j] > pivot ): j-= 1

      if i >= j: 
          return j

      A[i], A[j] = A[j], A[i]


test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

php how to go one level up on dirname(__FILE__)

Try this

dirname(dirname( __ FILE__))

Edit: removed "./" because it isn't correct syntax. Without it, it works perfectly.

Yahoo Finance All Currencies quote API Documentation

I have used this URL to obtain multiple currency market quotes.

http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X

"USD",1.0000
"CAD",1.2458
"EUR",0.8396

They can be parsed in PHP like this:

$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');

$quote = array_map( 'str_getcsv', file($url) );

foreach ($quote as $key => $symb) {
    $symbol = $quote[$key][0];
    $value = $quote[$key][1];
}

where is create-react-app webpack config and files?

Assuming you don't want to eject and you just want to look at the config you will find them in /node_modules/react-scripts/config

webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

scp files from local to remote machine error: no such file or directory

In my case I had to specify the Port Number using

scp -P 2222 username@hostip:/directory/ /localdirectory/

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

What does 'const static' mean in C and C++?

It's a small space optimization.

When you say

const int foo = 42;

You're not defining a constant, but creating a read-only variable. The compiler is smart enough to use 42 whenever it sees foo, but it will also allocate space in the initialized data area for it. This is done because, as defined, foo has external linkage. Another compilation unit can say:

extern const int foo;

To get access to its value. That's not a good practice since that compilation unit has no idea what the value of foo is. It just knows it's a const int and has to reload the value from memory whenever it is used.

Now, by declaring that it is static:

static const int foo = 42;

The compiler can do its usual optimization, but it can also say "hey, nobody outside this compilation unit can see foo and I know it's always 42 so there is no need to allocate any space for it."

I should also note that in C++, the preferred way to prevent names from escaping the current compilation unit is to use an anonymous namespace:

namespace {
    const int foo = 42; // same as static definition above
}

What is the (function() { } )() construct in JavaScript?

It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum lets make the add function into an IIFE,

Step 1: Define the function

function add (a, b){
    return a+b;
}
add(5,5);

Step2: Call the function by wrap the entire functtion declaration into parentheses

(function add (a, b){
    return a+b;
})
//add(5,5);

Step 3: To invock the function immediatly just remove the 'add' text from the call.

(function add (a, b){
    return a+b;
})(5,5);

The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
        const document = "hi there";
        console.log(document);
    </script> 
</body>

you will endup in a SyntaxError: redeclaration of non-configurable global property document.

But if your desire is to declear a variable name documet you can do it by using IFFE.

<body>
    <div id = 'demo'></div>
    <script>
        (function(){
            const document = "hi there";
            this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
            console.log(document);
        })();
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

Output:

enter image description here

Let's try by an another example, suppose we have an calculator object like bellow-

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
    </script> 
</body>

Well it's working like a charm, what if we accidently re-assigne the value of calculator object.

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
        calculator = "scientific calculator";
        console.log(calculator.mul(5,5));
    </script> 
</body>

yes you will endup with a TypeError: calculator.mul is not a function iffe.html

But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        var cal = (function(){
            var calculator = {
                sub:function(a,b){
                    return a-b;
                },
                div:function(a,b){
                    return a/b;
                }
            }
            console.log(this.calculator.mul(5,10));
            console.log(calculator.sub(10,5));
            return calculator;
        })();
        console.log(calculator.add(5,10));
        console.log(cal.div(10,5));
    </script> 
</body>

Output: enter image description here

How to change the color of a CheckBox?

You should try below code. It is working for me.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checked" 
          android:state_checked="true">
        <color android:color="@color/yello" />
    </item>
    <!-- checked -->
    <item android:drawable="@drawable/unchecked" 
          android:state_checked="false">
        <color android:color="@color/black"></color>
    </item>
    <!-- unchecked -->
    <item android:drawable="@drawable/checked" 
          android:state_focused="true">
        <color android:color="@color/yello"></color>
    </item>
    <!-- on focus -->
    <item android:drawable="@drawable/unchecked">
        <color android:color="@color/black"></color>
    </item>
    <!-- default -->
</selector>

and CheckBox

<CheckBox
    Button="@style/currentcy_check_box_style"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
    android:text="@string/step_one_currency_aud" />

How do I add to the Windows PATH variable using setx? Having weird problems

Sadly with OOTB tools, you cannot append either the system path or user path directly/easily. If you want to stick with OOTB tools, you have to query either the SYSTEM or USER path, save that value as a variable, then appends your additions and save it using setx. The two examples below show how to retrieve either, save them, and append your additions. Don't get mess with %PATH%, it is a concatenation of USER+SYSTEM, and will cause a lot of duplication in the result. You have to split them as shown below...

Append to System PATH

for /f "usebackq tokens=2,*" %A in (`reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) do set SYSPATH=%B

setx PATH "%SYSPATH%;C:\path1;C:\path2" /M

Append to User PATH

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set userPATH=%B

setx PATH "%userPATH%;C:\path3;C:\path4"

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

Receiving "Attempted import error:" in react app

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e

export const addPost = (id) =>{
  ...
 }

Note while importing you need to wrap it in curly braces i.e. import {addPost} from '../URL';

But when using export default i.e

const addPost = (id) =>{
  ...
 }

export default addPost,

Then you can import without curly braces i.e. import addPost from '../url';

export default addPost

I hope this helps anyone who got confused as me.

How create table only using <div> tag and Css

If there is anything in <table> you don't like, maybe you could use reset file?

or

if you need this for layout of the page check out the cssplay layout examples for designing websites without tables.

How do I remove diacritics (accents) from a string in .NET?

What this person said:

Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(text));

It actually splits the likes of å which is one character (which is character code 00E5, not 0061 plus the modifier 030A which would look the same) into a plus some kind of modifier, and then the ASCII conversion removes the modifier, leaving the only a.

How do I disable right click on my web page?

I know I am late, but I want to create some assumptions and explainations for the answer I am going to provide.

Can I disable right-click

Can I disable right click on my web page without using Javascript?

Yes, by using JavaScript you can disable any event that happens and you can do that mostly only by javaScript. How, all you need is:

  1. A working hardware

  2. A website or somewhere from which you can learn about the keycodes. Because you're gonna need them.

Now lets say you wanna block the enter key press here is the code:

function prevententer () {
 if(event.keyCode == 13) {
  return false;
 }
}

For the right click use this:

event.button == 2

in the place of event.keyCode. And you'll block it.

I want to ask this because most browsers allow users to disable it by Javascript.

You're right, browsers allow you to use JavaScript and javascript does the whole job for you. You donot need to setup anything, just need the script attribute in the head.

Why you should not disable it?

The main and the fast answer to that would be, users won't like it. Everyone needs freedom, no-one I mean no-one wants to be blocked or disabled, a few minutes ago I was at a site, which had blocked me from right clicking and I felt why? Do you need to secure your source code? Then here ctrl+shift+J I have opened the Console and now I can go to HTML-code tab. Go ahead and stop me. This won't add any of the security layer to your app.

There are alot of userful menus in the Right Click, like Copy, Paste, Search Google for 'text' (In Chrome) and many more. So user would like to get ease of access instead of remembering alot of keyboard shortcuts. Anyone can still copy the context, save the image or do whatever he wants.

Browsers use Mouse Navigation: Some browsers such as Opera uses mouse navigation, so if you disable it, user would definitely hate your User Interface and the scripts.

So that was the basic, I was going to write some more about saving the source code hehehe but, let it be the answer to your question.

Reference to the keycodes:

Key and mouse button code:

http://www.w3schools.com/jsref/event_button.asp

https://developer.mozilla.org/en-US/docs/Web/API/event.button (would be appreciated by the users too).

Why not to disable right click:

http://www.sitepoint.com/dont-disable-right-click/

What's the difference between the 'ref' and 'out' keywords?

I am going to try my hand at an explanation:

I think we understand how the value types work right? Value types are (int, long, struct etc.). When you send them in to a function without a ref command it COPIES the data. Anything you do to that data in the function only affects the copy, not the original. The ref command sends the ACTUAL data and any changes will affect the data outside the function.

Ok on to the confusing part, reference types:

Lets create a reference type:

List<string> someobject = new List<string>()

When you new up someobject, two parts are created:

  1. The block of memory that holds data for someobject.
  2. A reference (pointer) to that block of data.

Now when you send in someobject into a method without ref it COPIES the reference pointer, NOT the data. So you now have this:

(outside method) reference1 => someobject
(inside method)  reference2 => someobject

Two references pointing to the same object. If you modify a property on someobject using reference2 it will affect the same data pointed to by reference1.

 (inside method)  reference2.Add("SomeString");
 (outside method) reference1[0] == "SomeString"   //this is true

If you null out reference2 or point it to new data it will not affect reference1 nor the data reference1 points to.

(inside method) reference2 = new List<string>();
(outside method) reference1 != null; reference1[0] == "SomeString" //this is true

The references are now pointing like this:
reference2 => new List<string>()
reference1 => someobject

Now what happens when you send someobject by ref to a method? The actual reference to someobject gets sent to the method. So you now have only one reference to the data:

(outside method) reference1 => someobject;
(inside method)  reference1 => someobject;

But what does this mean? It acts exactly the same as sending someobject not by ref except for two main thing:

1) When you null out the reference inside the method it will null the one outside the method.

 (inside method)  reference1 = null;
 (outside method) reference1 == null;  //true

2) You can now point the reference to a completely different data location and the reference outside the function will now point to the new data location.

 (inside method)  reference1 = new List<string>();
 (outside method) reference1.Count == 0; //this is true

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I'm using ASP.Net CORE 2.1 and I got this error when I ran by selecting a .csproj from a list of about 40 in a big repo. When I opened the csproj file individually, the error was resolved. Something with how the program was launched was different when the csproj was opened.

CSS media query to target only iOS devices

Short answer No. CSS is not specific to brands.

Below are the articles to implement for iOS using media only.

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

http://stephen.io/mediaqueries/

Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance

http://www.kevinleary.net/php-detect-ios-mobile-users/

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

How to add a second x-axis in matplotlib

Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?" Yes, it is.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)

ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")

ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])

plt.show()

You'll get: enter image description here

Remove characters from a string

ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

remove item from stored array in angular 2

Don't use delete to remove an item from array and use splice() instead.

this.data.splice(this.data.indexOf(msg), 1);

See a similar question: How do I remove a particular element from an array in JavaScript?

Note, that TypeScript is a superset of ES6 (arrays are the same in both TypeScript and JavaScript) so feel free to look for JavaScript solutions even when working with TypeScript.

Difference between Eclipse Europa, Helios, Galileo

Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).

jQuery .on('change', function() {} not triggering for dynamically created inputs

Use this

$('body').on('change', '#id', function() {
  // Action goes here.
});

How to get the first word in the string

You shoud do something like :

print line.split()[0]

Excel how to fill all selected blank cells with text

OK, what you can try is

Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.

That should replace all blank cells in the USED range with NULL

Regular expressions in C: examples?

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

How to put Google Maps V2 on a Fragment using ViewPager

By using this code we can setup MapView anywhere, inside any ViewPager or Fragment or Activity.

In the latest update of Google for Maps, only MapView is supported for fragments. MapFragment & SupportMapFragment doesn't work. I might be wrong but this is what I saw after trying to implement MapFragment & SupportMapFragment.

Setting up the layout for showing the map in the file location_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Now, we code the Java class for showing the map in the file MapViewFragment.java:

public class MapViewFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.location_fragment, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;

                // For showing a move to my location button
                googleMap.setMyLocationEnabled(true);

                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

Finally you need to get the API Key for your app by registering your app at Google Cloud Console. Register your app as Native Android App.

How to apply a function to two columns of Pandas dataframe

The method you are looking for is Series.combine. However, it seems some care has to be taken around datatypes. In your example, you would (as I did when testing the answer) naively call

df['col_3'] = df.col_1.combine(df.col_2, func=get_sublist)

However, this throws the error:

ValueError: setting an array element with a sequence.

My best guess is that it seems to expect the result to be of the same type as the series calling the method (df.col_1 here). However, the following works:

df['col_3'] = df.col_1.astype(object).combine(df.col_2, func=get_sublist)

df

   ID   col_1   col_2   col_3
0   1   0   1   [a, b]
1   2   2   4   [c, d, e]
2   3   3   5   [d, e, f]

How do I center align horizontal <UL> menu?

div {
     text-align: center;
}
div ul {
     display: inline-table;
}

ul as inline-table fixes the with issue. I used the parent div to align the text to center. this way it looks good even in other languages (translation, different width)

How to declare a constant map in Golang?

And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

   // romanNumeralDict returns map[int]string dictionary, since the return
       // value is always the same it gives the pseudo-constant output, which
       // can be referred to in the same map-alike fashion.
       var romanNumeralDict = func() map[int]string { return map[int]string {
            1000: "M",
            900:  "CM",
            500:  "D",
            400:  "CD",
            100:  "C",
            90:   "XC",
            50:   "L",
            40:   "XL",
            10:   "X",
            9:    "IX",
            5:    "V",
            4:    "IV",
            1:    "I",
          }
        }

        func printRoman(key int) {
          fmt.Println(romanNumeralDict()[key])
        }

        func printKeyN(key, n int) {
          fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
        }

        func main() {
          printRoman(1000)
          printRoman(50)
          printKeyN(10, 3)
        }

Try this at play.golang.org.

ORDER BY date and time BEFORE GROUP BY name in mysql

This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.

I came to this thread, when I wanted to find the latest row(which is order by date desc but get the only one result for a particular column type, which is group by column name).

One other approach to solve such problem is to make use of aggregation.

So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc, which will give the latest date, with grouped by the same column.

Suppose, you want to find the data of a particular column now and max aggregation cannot be done. In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column, and while you're accessing it, you can split/explode the new_column field.

Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.

Not sure of the complexity as well, may be someone can put some light on that.

Regards :)

Javascript variable access in HTML

It is also possible to use span tag instead of a tag:

<html>
<script>
   var simpleText = "hello_world";
   var finalSplitText = simpleText.split("_");
   var splitText = finalSplitText[0];

   document.getElementById('someId').InnerHTML = splitText;
</script>

 <body>
  <span id="someId"></span>
 </body>

</html>

It worked well for me

Concatenating strings in C, which method is more efficient?

The difference is unlikely to matter:

  • If your strings are small, the malloc will drown out the string concatenations.
  • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.

That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

How to convert a number to string and vice versa in C++

I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

// make_string
class make_string {
public:
  template <typename T>
  make_string& operator<<( T const & val ) {
    buffer_ << val;
    return *this;
  }
  operator std::string() const {
    return buffer_.str();
  }
private:
  std::ostringstream buffer_;
};

And then you use it as;

string str = make_string() << 6 << 8 << "hello";

Quite nifty!

Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
  std::stringstream buf;
  buf << str;
  RETURN_TYPE val;
  buf >> val;
  return val;
}

Use as:

int x = parse_string<int>("78");

You might also want versions for wstrings.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.

Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.

Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)

Good luck.

How to determine the installed webpack version

Just another way not mentioned yet:

If you installed it locally to a project then open up the node_modules folder and check your webpack module.

$cd /node_modules/webpack/package.json

Open the package.json file and look under version

enter image description here

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):

./gradlew wrapper --gradle-version 5.5

Moreover, you can use --distribution-type parameter with either bin or all value to choose a distribution type. Use all distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:

./gradlew wrapper --gradle-version 5.5 --distribution-type all

Or you can create a custom wrapper task

task wrapper(type: Wrapper) {
    gradleVersion = '5.5'
}

and run ./gradlew wrapper.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

It could be that the gradle-2.1 distribution specified by the wrapper was not downloaded properly. This was the root cause of the same problem in my environment.

Look into this directory:

ls -l ~/.gradle/wrapper/dists/

In there you should find a gradle-2.1 folder. Delete it like so:

rm -rf ~/.gradle/wrapper/dists/gradle-2.1-bin/

Restart IntelliJ, after that it will restart the download from the beginning and hopefully work.

Thanks, Ioannis

How to call a View Controller programmatically?

Import the view controller class which you want to show and use the following code

KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];

How do I erase an element from std::vector<> by index?

To delete a single element, you could do:

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);

Is there any publicly accessible JSON data source to test with real world data?

Tumblr has a public API that provides JSON. You can get a dump of posts using a simple url like http://puppygifs.tumblr.com/api/read/json.

How can I see the raw SQL queries Django is running?

The following returns the query as valid SQL, based on https://code.djangoproject.com/ticket/17741:

def str_query(qs):
    """
    qs.query returns something that isn't valid SQL, this returns the actual
    valid SQL that's executed: https://code.djangoproject.com/ticket/17741
    """
    cursor = connections[qs.db].cursor()
    query, params = qs.query.sql_with_params()
    cursor.execute('EXPLAIN ' + query, params)
    res = str(cursor.db.ops.last_executed_query(cursor, query, params))
    assert res.startswith('EXPLAIN ')
    return res[len('EXPLAIN '):]

Calling Web API from MVC controller

Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below

public class ProductsController : Controller
    {
        // GET: Products
        public async Task<ActionResult> Index()
        {
            string apiUrl = "http://localhost:58764/api/values";

            using (HttpClient client=new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();
                    var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);

                }


            }
            return View();

        }
    }

PHP: Calling another class' method

//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How to extract hours and minutes from a datetime.datetime object?

datetime has fields hour and minute. So to get the hours and minutes, you would use t1.hour and t1.minute.

However, when you subtract two datetimes, the result is a timedelta, which only has the days and seconds fields. So you'll need to divide and multiply as necessary to get the numbers you need.

How do I get the file extension of a file in Java?

Java has a built-in way of dealing with this, in the java.nio.file.Files class, that may work for your needs:

File f = new File("/path/to/file/foo.txt");
String ext = Files.probeContentType(f.toPath());
if(ext.equalsIgnoreCase("txt")) do whatever;

Note that this static method uses the specifications found here to retrieve "content type," which can vary.

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

What's the difference between an Angular component and module

enter image description here

Simplest Explanation:

Module is like a big container containing one or many small containers called Component, Service, Pipe

A Component contains :

  • HTML template or HTML code

  • Code(TypeScript)

  • Service: It is a reusable code that is shared by the Components so that rewriting of code is not required

  • Pipe: It takes in data as input and transforms it to the desired output

Reference: https://scrimba.com/

Installing Bootstrap 3 on Rails App

gem bootstrap-sass

bootstrap-sass is easy to drop into Rails with the asset pipeline.

In your Gemfile you need to add the bootstrap-sass gem, and ensure that the sass-rails gem is present - it is added to new Rails applications by default.

gem 'sass-rails', '>= 3.2' # sass-rails needs to be higher than 3.2 gem 'bootstrap-sass', '~> 3.0.3.0'

bundle install and restart your server to make the files available through the pipeline.

Source: http://rubydoc.info/gems/bootstrap-sass/3.0.3.0/frames

What is the difference between CSS and SCSS?

Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css. An example of such a feature is allowing definition of variables that can be re-used in different styles.

The language has two alternative syntaxes:

  • A JSON like syntax that is kept in files ending with .scss
  • A YAML like syntax that is kept in files ending with .sass

Either of these must be compiled to .css files which are recognized by browsers.

See https://sass-lang.com/ for further information.

Python Regex - How to Get Positions and Values of Matches

Taken from

Regular Expression HOWTO

span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.

>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

Combine that with:

In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.

>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)

you should be able to do something on the order of

for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

React - changing an uncontrolled input

An update for this. For React Hooks use const [name, setName] = useState(" ")

Find provisioning profile in Xcode 5

If it's sufficient to use the following criteria to locate the profile:

<key>Name</key>
<string>iOS Team Provisioning Profile: *</string>

you can scan the directory using awk. This one-liner will find the first file that contains the name starting with "iOS Team".

awk 'BEGIN{e=1;pat="<string>"tolower("iOS Team")}{cur=tolower($0);if(cur~pat &&prev~/<key>name<\/key>/){print FILENAME;e=0;exit};if($0!~/^\s*$/)prev=cur}END{exit e}' *

Here's a script that also returns the first match, but is easier to work with.

#!/bin/bash

if [ $# != 1 ] ; then
    echo Usage: $0 \<start of provisioning profile name\>
    exit 1
fi

read -d '' script << 'EOF'
BEGIN {
    e = 1
    pat = "<string>"tolower(prov)
}
{
    cur = tolower($0)
    if (cur ~ pat && prev ~ /<key>name<\\/key>/) {
        print FILENAME
        e = 0
        exit
    }
    if ($0 !~ /^\s*$/) {
        prev = cur
    }
}
END {
 exit e
}
EOF


awk -v "prov=$1" "$script" *

It can be called from within the profiles directory, $HOME/Library/MobileDevice/Provisioning Profiles:

~/findprov "iOS Team"

To use the script, save it to a suitable location and remember to set the executable mode; e.g., chmod ugo+x

Insert null/empty value in sql datetime column by default

if there is no value inserted, the default value should be null,empty

In the table definition, make this datetime column allows null, be not defining NOT NULL:

...
DateTimeColumn DateTime,
...

I HAVE ALLOWED NULL VARIABLES THOUGH.

Then , just insert NULL in this column:

INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);

Or, you can make use of the DEFAULT constaints:

...
DateTimeColumn DateTime DEFAULT NULL,
...

Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:

INSERT INTO Table(name, ...)
VALUES('foo bar', ..);

sudo: npm: command not found

I had the same problem; here are the commands to fix it:

  • sudo ln -s /usr/local/bin/node /usr/bin/node
  • sudo ln -s /usr/local/lib/node /usr/lib/node
  • sudo ln -s /usr/local/bin/npm /usr/bin/npm
  • sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

What is the difference between require and require-dev sections in composer.json?

  1. According to composer's manual:

    require-dev (root-only)

    Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

    So running composer install will also download the development dependencies.

  2. The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.

Two values from one input in python?

You have to use the split() method which splits the input into two different inputs. Whatever you pass into the split is looked for and the input is split from there. In most cases its the white space.

For example, You give the input 23 24 25. You expect 3 different inputs like

num1 = 23
num2 = 24
num3 = 25

So in Python, You can do

num1,num2,num3 = input().split(" ")

XML serialization in Java?

Usually I use jaxb or XMLBeans if I need to create objects serializable to XML. Now, I can see that XStream might be very useful as it's nonintrusive and has really simple api. I'll play with it soon and probably use it. The only drawback I noticed is that I can't create object's id on my own for cross referencing.

@Barak Schiller
Thanks for posting link to XStream!

Could not find main class HelloWorld

It looks that you had done all setup properly but there might be one area where it might be causing problem

Check the value of your "CLASSPATH" variable and make sure at the end you kept ;.

Note: ; is for end separator . is for including existing path at the end