Programs & Examples On #Simple machines forum

Free internet forum written in PHP using an SQL database backend.

Copy every nth line from one sheet to another

Highlight the 7th line. Paintbrush the format for the first 7 lines a few times. Then do a bigger chunk of paintbrush copying the format until you are done. Every 7th line should be highlighted. Filter by color and then copy and paste (paste the values) from the highlighted cells into a new sheet.

Bootstrap col-md-offset-* not working

If you are ok with small tweak - we know that bootstrap works with a width of 12

<div class="row">
      <div class="col-md-1">
            Keep it blank it becomes left offset
      </div> 
      <div class="col-md-5">
      </div>
      <div class="col-md-5">
      </div>
      <div class="col-md-1">
            Keep it blank it becomes right offset
      </div
</div>

I am sure there is a better way to do this, but i was in a hurry so used this trick

Git ignore file for Xcode projects

We did find that even if you add the .gitignore and the .gitattribte the *.pbxproj file can get corrupted. So we have a simple plan.

Every person that codes in office simply discards the changes made to this file. In the commit we simple mention the files that are added into the source. And then push to the server. Our integration manager than pulls and sees the commit details and adds the files into the resources.

Once he updates the remote everyone will always have a working copy. In case something is missing then we inform him to add it in and then pull once again.

This has worked out for us without any issues.

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

Parse usable Street Address, City, State, Zip from a string

I've done this in the past.

Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors.

Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy.

For automation, you need a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually.

Do get a copy of Postal Addressing Standards (USPS) at http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf and notice it is 130+ pages long. Regexes to implement that would be nuts.

For international addresses, all bets are off. US-based workers would not be able to validate.

Alternatively, use a data service. I have, however, no recommendations.

Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and update the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail)

Finally, when you have scrubbed data, look for duplicates.

ASP.NET Custom Validator Client side & Server Side validation not firing

Use this:

<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>

To validate an empty field.

You don't need to add 2 validators !

Two values from one input in python?

This solution is being used for converting multiple string like ("22 44 112 2 34") to an integer list and you can access to the values in a list.

n = input("") # Like : "22 343 455 54445 22332"

if n[:-1] != " ":
n += " "

char = ""
list = []

for i in n :
    if i != " ":
        char += i
    elif i == " ":
        list.append(int(char))
        char = ""

print(list) # Be happy :))))

What is a loop invariant?

It is hard to keep track of what is happening with loops. Loops which don't terminate or terminate without achieving their goal behavior is a common problem in computer programming. Loop invariants help. A loop invariant is a formal statement about the relationship between variables in your program which holds true just before the loop is ever run (establishing the invariant) and is true again at the bottom of the loop, each time through the loop (maintaining the invariant). Here is the general pattern of the use of Loop Invariants in your code:

... // the Loop Invariant must be true here
while ( TEST CONDITION ) {
// top of the loop
...
// bottom of the loop
// the Loop Invariant must be true here
}
// Termination + Loop Invariant = Goal
...
Between the top and bottom of the loop, headway is presumably being made towards reaching the loop's goal. This might disturb (make false) the invariant. The point of Loop Invariants is the promise that the invariant will be restored before repeating the loop body each time. There are two advantages to this:

Work is not carried forward to the next pass in complicated, data dependent ways. Each pass through the loop in independent of all others, with the invariant serving to bind the passes together into a working whole. Reasoning that your loop works is reduced to reasoning that the loop invariant is restored with each pass through the loop. This breaks the complicated overall behavior of the loop into small simple steps, each which can be considered separately. The test condition of the loop is not part of the invariant. It is what makes the loop terminate. You consider separately two things: why the loop should ever terminate, and why the loop achieves its goal when it terminates. The loop will terminate if each time through the loop you move closer to satisfying the termination condition. It is often easy to assure this: e.g. stepping a counter variable by one until it reaches a fixed upper limit. Sometimes the reasoning behind termination is more difficult.

The loop invariant should be created so that when the condition of termination is attained, and the invariant is true, then the goal is reached:

invariant + termination => goal
It takes practice to create invariants which are simple and relate which capture all of goal attainment except for termination. It is best to use mathematical symbols to express loop invariants, but when this leads to over-complicated situations, we rely on clear prose and common-sense.

Decoding a Base64 string in Java

The following should work with the latest version of Apache common codec

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

Get Specific Columns Using “With()” Function in Laravel Eloquent

You can try this code . It is tested in laravel 6 version.

Controller code
 public function getSection(Request $request)
{

  Section::with(['sectionType' => function($q) {
      $q->select('id', 'name');
  }])->where('position',1)->orderBy('serial_no', 'asc')->get(['id','name','','description']);
  return response()->json($getSection);
}
Model code
public function sectionType(){
    return $this->belongsTo(Section_Type::class, 'type_id');
}

Can I use library that used android support with Androidx projects.

Add the lines in the gradle.properties file

android.useAndroidX=true
android.enableJetifier=true

enter image description here enter image description here Refer also https://developer.android.com/jetpack/androidx

Apache HttpClient Interim Error: NoHttpResponseException

Accepted answer is right but lacks solution. To avoid this error, you can add setHttpRequestRetryHandler (or setRetryHandler for apache components 4.4) for your HTTP client like in this answer.

How to add a line break within echo in PHP?

You have to use br when using echo , like this :

echo "Thanks for your email" ."<br>". "Your orders details are below:"

and it will work properly

SQL Server 2008 - Case / If statements in SELECT Clause

CASE is the answer, but you will need to have a separate case statement for each column you want returned. As long as the WHERE clause is the same, there won't be much benefit separating it out into multiple queries.

Example:

SELECT
    CASE @var
        WHEN 'xyz' THEN col1
        WHEN 'zyx' THEN col2
        ELSE col7
    END,
    CASE @var
        WHEN 'xyz' THEN col2
        WHEN 'zyx' THEN col3
        ELSE col8
    END
FROM Table
...

Integer division: How do you produce a double?

I don't like casting primitives, who knows what may happen.

Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.

You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:

double d = num / (double) denom;

How can I add new dimensions to a Numpy array?

You're asking how to add a dimension to a NumPy array, so that that dimension can then be grown to accommodate new data. A dimension can be added as follows:

image = image[..., np.newaxis]

Runnable with a parameter?

You have two options:

  1. Define a named class. Pass your parameter to the constructor of the named class.

  2. Have your anonymous class close over your "parameter". Be sure to mark it as final.

How to limit depth for recursive file list?

Checkout the -maxdepth flag of find

find . -maxdepth 1 -type d -exec ls -ld "{}" \;

Here I used 1 as max level depth, -type d means find only directories, which then ls -ld lists contents of, in long format.

Why doesn't catching Exception catch RuntimeException?

Catching Exception will catch a RuntimeException

how to change attribute "hidden" in jquery

A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true or false.

.attr("hidden", false) will remove the attribute the same as using .removeAttr("hidden").

.attr("hidden", "false") is incorrect and the tag remains hidden.

You should not be setting hidden, checked, selected, or several others to any string value to toggle it.

Disable Tensorflow debugging information

I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.

I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

How to sort an array in Bash

Original response:

array=(a c b "f f" 3 5)
readarray -t sorted < <(for a in "${array[@]}"; do echo "$a"; done | sort)

output:

$ for a in "${sorted[@]}"; do echo "$a"; done
3
5
a
b
c
f f

Note this version copes with values that contains special characters or whitespace (except newlines)

Note readarray is supported in bash 4+.


Edit Based on the suggestion by @Dimitre I had updated it to:

readarray -t sorted < <(printf '%s\0' "${array[@]}" | sort -z | xargs -0n1)

which has the benefit of even understanding sorting elements with newline characters embedded correctly. Unfortunately, as correctly signaled by @ruakh this didn't mean the the result of readarray would be correct, because readarray has no option to use NUL instead of regular newlines as line-separators.

d3 add text to circle

Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]

const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)

const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)

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

Postgres: INSERT if does not exist already

The approach with the most upvotes (from John Doe) does somehow work for me but in my case from expected 422 rows i get only 180. I couldn't find anything wrong and there are no errors at all, so i looked for a different simple approach.

Using IF NOT FOUND THEN after a SELECT just works perfectly for me.

(described in PostgreSQL Documentation)

Example from documentation:

SELECT * INTO myrec FROM emp WHERE empname = myname;
IF NOT FOUND THEN
  RAISE EXCEPTION 'employee % not found', myname;
END IF;

How to draw checkbox or tick mark in GitHub Markdown table?

I used &#9744; (☐) for [ ] and &#9745; (☑) for [x] and it works for marked.js which says it is compatible with Github markdown. I based my solution on answers for this question. See also this informative answer.

Update: I should have mentioned that when you do it this way, you do not need the <ul>, e.g:

| Unchecked | Checked |
| --------- | ------- |
| &#9744;   | &#9745; |

How do I increment a DOS variable in a FOR /F loop?

What about this simple code, works for me and on Windows 7

set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin

:end

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Vertical alignment of text and icon in button

There is one rule that is set by font-awesome.css, which you need to override.

You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline; by default and which I've corrected here:

<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:

enter image description here

I've downsized the font-size of the icon above in this instance to 30px, as it feels too big at 40px for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:

enter image description here

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

Choosing line type and color in Gnuplot 4.0

Here is the syntax:

  set terminal pdf {monochrome|color|colour}
                   {{no}enhanced}
                   {fname "<font>"} {fsize <fontsize>}
                   {font "<fontname>{,<fontsize>}"}
                   {linewidth <lw>} {rounded|butt}
                   {solid|dashed} {dl <dashlength>}}
                   {size <XX>{unit},<YY>{unit}}

and an example:

set terminal pdfcairo monochrome enhanced font "Times-New-Roman,12" dashed

Netbeans - Error: Could not find or load main class

Possible Fixes:

Fix 1

  1. Go to project properties (right click on the folder of your project in netbeans)
  2. On left tab where it shows the categories, click on the "Run" selection
  3. Then click on Browse to find the Main class you use on your project

Fix 2

  1. Go to C:\Users\name\AppData\Local\Netbeans
  2. delete the Cache folder.
  3. Rebuild and Run

Fix 3 Download most recent version of Netbeans

Fix 4 Download most recent version of JDK and configure Netbeans to use that

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

Run PHP Task Asynchronously

When you just want to execute one or several HTTP requests without having to wait for the response, there is a simple PHP solution, as well.

In the calling script:

$socketcon = fsockopen($host, 80, $errno, $errstr, 10);
if($socketcon) {   
   $socketdata = "GET $remote_house/script.php?parameters=... HTTP 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";      
   fwrite($socketcon, $socketdata); 
   fclose($socketcon);
}
// repeat this with different parameters as often as you like

On the called script.php, you can invoke these PHP functions in the first lines:

ignore_user_abort(true);
set_time_limit(0);

This causes the script to continue running without time limit when the HTTP connection is closed.

MVC controller : get JSON object from HTTP body?

It seems that if

  • Content-Type: application/json and
  • if POST body isn't tightly bound to controller's input object class

Then MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch it from the request stream yourself and process it.

[HttpPost]
public ActionResult Index(int? id)
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();

    InputClass input = null;
    try
    {
        // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
        input = JsonConvert.DeserializeObject<InputClass>(json)
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //do stuff

}

Update:

for Asp.Net Core, you have to add [FromBody] attrib beside your param name in your controller action for complex JSON data types:

[HttpPost]
public ActionResult JsonAction([FromBody]Customer c)

Also, if you want to access the request body as string to parse it yourself, you shall use Request.Body instead of Request.InputStream:

Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();

How do I configure the proxy settings so that Eclipse can download new plugins?

There is an eclipse.ini (sts.ini) parameter that can help:

-Djava.net.useSystemProxies=true

A lot of effort wasted on this trivial setting each time I change the work environment... See one of the related bugs on eclipse bugzilla.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:

ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog

jQuery - Detect value change on hidden input field

You can simply use the below function, You can also change the type element.

 $("input[type=hidden]").bind("change", function() {
       alert($(this).val()); 
 });

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

HTML

 <div id="message"></div>
<input type="hidden" id="testChange" value="0"  />    

JAVASCRIPT

var $message = $('#message');
var $testChange = $('#testChange');
var i = 1;

function updateChange() {
    $message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');
}

$testChange.on('change', updateChange);

setInterval(function() {
    $testChange.val(++i).trigger('change');; 
    console.log("value changed" +$testChange.val());
}, 3000);

updateChange();

should work as expected.

http://jsfiddle.net/7CM6k/3/

Check if file exists and whether it contains a specific string

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi

throwing an exception in objective-c/cocoa

I believe you should never use Exceptions to control normal program flow. But exceptions should be thrown whenever some value doesn't match a desired value.

For example if some function accepts a value, and that value is never allowed to be nil, then it's fine to trow an exception rather then trying to do something 'smart'...

Ries

How to differ sessions in browser-tabs?

you will need to do

1- store a cookie for accounts list

2- optional store a cookie for default one

3- store for each account with it's index like acc1, acc2

4- put in the url something represent the index of accounts and if not you will select the default one like google mail domain.com/0/some-url >> 0 here represent the index of account also you may need to know how to use urlwrite

5- when select a cookie, select it according to your urlpath represent the account index

Regards

Adding a directory to the PATH environment variable in Windows

This only modifies the registry. An existing process won't use these values. A new process will do so if it is started after this change and doesn't inherit the old environment from its parent.

You didn't specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IEventRepository, EventRepository>();           
}

You forgot to add "services.AddScoped" in startup ConfigureServices method.

Beautiful way to remove GET-variables with PHP?

Another solution... I find this function more elegant, it will also remove the trailing '?' if the key to remove is the only one in the query string.

/**
 * Remove a query string parameter from an URL.
 *
 * @param string $url
 * @param string $varname
 *
 * @return string
 */
function removeQueryStringParameter($url, $varname)
{
    $parsedUrl = parse_url($url);
    $query = array();

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $query);
        unset($query[$varname]);
    }

    $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
    $query = !empty($query) ? '?'. http_build_query($query) : '';

    return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}

Tests:

$urls = array(
    'http://www.example.com?test=test',
    'http://www.example.com?bar=foo&test=test2&foo2=dooh',
    'http://www.example.com',
    'http://www.example.com?foo=bar',
    'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
    'https://www.example.com/test/test.test?test=test6',
);

foreach ($urls as $url) {
    echo $url. '<br/>';
    echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}

Will output:

http://www.example.com?test=test
http://www.example.com

http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh

http://www.example.com
http://www.example.com

http://www.example.com?foo=bar
http://www.example.com?foo=bar

http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar

https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test

» Run these tests on 3v4l

General error: 1364 Field 'user_id' doesn't have a default value

Try using Auth::id(), like

Post::create([ 'body' => request('body'), 'title' => request('title'), 'user_id' => Auth::id()]);

also remember to include Auth facade at top of your controller which is App\Http\Controllers\Auth

Test if executable exists in Python?

On the basis that it is easier to ask forgiveness than permission (and, importantly, that the command is safe to run) I would just try to use it and catch the error (OSError in this case - I checked for file does not exist and file is not executable and they both give OSError).

It helps if the executable has something like a --version flag that is a quick no-op.

import subprocess
myexec = "python2.8"
try:
    subprocess.call([myexec, '--version']
except OSError:
    print "%s not found on path" % myexec

This is not a general solution, but will be the easiest way for a lot of use cases - those where the code needs to look for a single well known executable which is safe to run, or at least safe to run with a given flag.

Is there a pretty print for PHP?

Both print_r() and var_dump() will output visual representations of objects within PHP.

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);

Can I run CUDA on Intel's integrated graphics processor?

Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.

Link: http://www.pgroup.com/products/pgiworkstation.htm

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

How to write LDAP query to test if user is member of a group?

You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:

ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'

If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:

ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**

How can I update npm on Windows?

I was also facing similar issues. I followed below mentioned steps and it worked for me:

  • go to Windows > Start > Node.js

    • right click on Node.js command prompt
    • click on Run as administrator
  • ping registry.npmjs.org

  • npm view npm version

  • cd %ProgramFiles%\nodejs

  • npm install npm@latest

and npm updated successfully. Earlier I was trying for CMD and that was throwing error. may be some path issue that got resolved by running NodeJs Command Prompt. hope it'll work for you. try this.

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

How can I edit a .jar file?

This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.

http://classeditor.sourceforge.net/

Responsive Google Map?

My solution based on eugenemail response:

1. HTML - Google Maps API

Get API Key

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

2. HTML - Canvas

<div id="map_canvas"></div>

3. CSS - Map canvas

#map_canvas {
    height: 400px;
}

4. JavaScript

function initialize() {
    var lat = 40.759300;
    var lng = -73.985712;
    var map_center = new google.maps.LatLng(lat, lng);
    var mapOptions = {
        center: map_center,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var mapCanvas = document.getElementById("map_canvas");
    var map = new google.maps.Map(mapCanvas, mapOptions);
    new google.maps.Marker({
        map: map,
        draggable: false,
        position: new google.maps.LatLng(lat, lng)
    });
    google.maps.event.addDomListener(window, 'resize', function() {
        map.setCenter(map_center);
    });
}
initialize();

Adding ID's to google map markers

Marker already has unique id

marker.__gm_id

PHP - regex to allow letters and numbers only

You left off the / (pattern delimiter) and $ (match end string).

preg_match("/^[a-zA-Z0-9]+$/", $value)

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How to change language of app when user selects language?

all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)

public void setLocale(String lang) { 
Locale myLocale = new Locale(lang); 
Resources res = getResources(); 
DisplayMetrics dm = res.getDisplayMetrics(); 
Configuration conf = res.getConfiguration(); 
conf.locale = myLocale; 
res.updateConfiguration(conf, dm); 
Intent refresh = new Intent(this, AndroidLocalize.class); 
finish();
startActivity(refresh); 

}

Mine was not working just because the languages were not mentioned in the config file(build.gradle)

 defaultConfig {
    resConfigs "en", "hi", "kn"
}

after that, all languages started running

How to print Unicode character in C++?

This code works in Linux (C++11, geany, g++ 7.4.0):

#include <iostream>

using namespace std;


int utf8_to_unicode(string utf8_code);
string unicode_to_utf8(int unicode);


int main()
{
    cout << unicode_to_utf8(36) << '\t';
    cout << unicode_to_utf8(162) << '\t';
    cout << unicode_to_utf8(8364) << '\t';
    cout << unicode_to_utf8(128578) << endl;

    cout << unicode_to_utf8(0x24) << '\t';
    cout << unicode_to_utf8(0xa2) << '\t';
    cout << unicode_to_utf8(0x20ac) << '\t';
    cout << unicode_to_utf8(0x1f642) << endl;

    cout << utf8_to_unicode("$") << '\t';
    cout << utf8_to_unicode("¢") << '\t';
    cout << utf8_to_unicode("€") << '\t';
    cout << utf8_to_unicode("") << endl;

    cout << utf8_to_unicode("\x24") << '\t';
    cout << utf8_to_unicode("\xc2\xa2") << '\t';
    cout << utf8_to_unicode("\xe2\x82\xac") << '\t';
    cout << utf8_to_unicode("\xf0\x9f\x99\x82") << endl;

    return 0;
}


int utf8_to_unicode(string utf8_code)
{
    unsigned utf8_size = utf8_code.length();
    int unicode = 0;

    for (unsigned p=0; p<utf8_size; ++p)
    {
        int bit_count = (p? 6: 8 - utf8_size - (utf8_size == 1? 0: 1)),
            shift = (p < utf8_size - 1? (6*(utf8_size - p - 1)): 0);

        for (int k=0; k<bit_count; ++k)
            unicode += ((utf8_code[p] & (1 << k)) << shift);
    }

    return unicode;
}


string unicode_to_utf8(int unicode)
{
    string s;

    if (unicode>=0 and unicode <= 0x7f)  // 7F(16) = 127(10)
    {
        s = static_cast<char>(unicode);

        return s;
    }
    else if (unicode <= 0x7ff)  // 7FF(16) = 2047(10)
    {
        unsigned char c1 = 192, c2 = 128;

        for (int k=0; k<11; ++k)
        {
            if (k < 6)  c2 |= (unicode % 64) & (1 << k);
            else c1 |= (unicode >> 6) & (1 << (k - 6));
        }

        s = c1;    s += c2;

        return s;
    }
    else if (unicode <= 0xffff)  // FFFF(16) = 65535(10)
    {
        unsigned char c1 = 224, c2 = 128, c3 = 128;

        for (int k=0; k<16; ++k)
        {
            if (k < 6)  c3 |= (unicode % 64) & (1 << k);
            else if (k < 12) c2 |= (unicode >> 6) & (1 << (k - 6));
            else c1 |= (unicode >> 12) & (1 << (k - 12));
        }

        s = c1;    s += c2;    s += c3;

        return s;
    }
    else if (unicode <= 0x1fffff)  // 1FFFFF(16) = 2097151(10)
    {
        unsigned char c1 = 240, c2 = 128, c3 = 128, c4 = 128;

        for (int k=0; k<21; ++k)
        {
            if (k < 6)  c4 |= (unicode % 64) & (1 << k);
            else if (k < 12) c3 |= (unicode >> 6) & (1 << (k - 6));
            else if (k < 18) c2 |= (unicode >> 12) & (1 << (k - 12));
            else c1 |= (unicode >> 18) & (1 << (k - 18));
        }

        s = c1;    s += c2;    s += c3;    s += c4;

        return s;
    }
    else if (unicode <= 0x3ffffff)  // 3FFFFFF(16) = 67108863(10)
    {
        ;  // actually, there are no 5-bytes unicodes
    }
    else if (unicode <= 0x7fffffff)  // 7FFFFFFF(16) = 2147483647(10)
    {
        ;  // actually, there are no 6-bytes unicodes
    }
    else  ;  // incorrect unicode (< 0 or > 2147483647)

    return "";
}

More:

How to find index position of an element in a list when contains returns true

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

How do I change the IntelliJ IDEA default JDK?

The above responses were very useful, but after all settings, the project was running with the wrong version. Finally, I noticed that it can be also configured in the Dependencies window. Idea 2018.1.3 File -> Project Structure -> Modules -> Sources and Dependencies.

How to execute mongo commands through shell scripts?

As suggested by theTuxRacer, you can use the eval command, for those who are missing it like I was, you can also add in your db name if you are not trying to preform operation on the default db.

mongo <dbname> --eval "printjson(db.something.find())"

Open multiple Eclipse workspaces on the Mac

By far the best solution is the OSX Eclipse Launcher presented in http://torkild.resheim.no/2012/08/opening-multiple-eclipse-instances-on.html It can be downloaded in the Marketplace http://marketplace.eclipse.org/content/osx-eclipse-launcher#.UGWfRRjCaHk

I use it everyday and like it very much! To demonstrate the simplicity of usage just take a look at the following image:

Image demonstrating the plugin usage: Just go File / Open Workspace / select one

Storing Images in PostgreSQL

Quick update to mid 2015:

You can use the Postgres Foreign Data interface, to store the files in more suitable database. For example put the files in a GridFS which is part of MongoDB. Then use https://github.com/EnterpriseDB/mongo_fdw to access it in Postgres.

That has the advantages, that you can access/read/write/backup it in Postrgres and MongoDB, depending on what gives you more flexiblity.

There are also foreign data wrappers for file systems: https://wiki.postgresql.org/wiki/Foreign_data_wrappers#File_Wrappers

As an example you can use this one: https://multicorn.readthedocs.org/en/latest/foreign-data-wrappers/fsfdw.html (see here for brief usage example)

That gives you the advantage of the consistency (all linked files are definitely there) and all the other ACIDs, while there are still on the actual file system, which means you can use any file system you want and the webserver can serve them directly (OS caching applies too).

How to create a <style> tag with Javascript?

I'm assuming that you're wanting to insert a style tag versus a link tag (referencing an external CSS), so that's what the following example does:

<html>
 <head>
  <title>Example Page</title>
 </head>
 <body>
  <span>
   This is styled dynamically via JavaScript.
  </span>
 </body>
 <script type="text/javascript">
   var styleNode = document.createElement('style');
   styleNode.type = "text/css";
   // browser detection (based on prototype.js)
   if(!!(window.attachEvent && !window.opera)) {
        styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
   } else {
        var styleText = document.createTextNode('span { color: rgb(255, 0, 0); } ');
        styleNode.appendChild(styleText);
   }
   document.getElementsByTagName('head')[0].appendChild(styleNode);
 </script>
</html>

Also, I noticed in your question that you are using innerHTML. This is actually a non-standard way of inserting data into a page. The best practice is to create a text node and append it to another element node.

With respect to your final question, you're going to hear some people say that your work should work across all of the browsers. It all depends on your audience. If no one in your audience is using Chrome, then don't sweat it; however, if you're looking to reach the biggest audience possible, then it's best to support all major A-grade browsers

Playing mp3 song on python

If you're working in the Jupyter (formerly IPython) notebook, you can

import IPython.display as ipd
ipd.Audio(filename='path/to/file.mp3')

What is difference between mutable and immutable String in java

I modified the code of william with a output comments for better understandable

   static void changeStr(String in) { 
      in = in+" changed";
      System.out.println("fun:"+in); //value changed 
    }
    static void changeStrBuf(StringBuffer in) {
      in.append(" changed");   //value changed
    }

    public static void main(String[] args) {
       StringBuffer sb = new StringBuffer("value");
       String str = "value";
       changeStrBuf(sb);
       changeStr(str);
       System.out.println("StringBuffer: "+sb); //value changed
       System.out.println("String: "+str);       // value 
    }

In above code , look at the value of str in both main() and changeStr() , even though u r changing the value of str in changeStr() it is affecting only to that function but in the main function the value is not changed , but it not in the case of StringBuffer..

In StringBuffer changed value is affected as a global..

hence String is immutable and StringBuffer is mutable...

In Simple , whatever u changed to String Object will affecting only to that function By going to String Pool. but not Changed...

Split comma-separated values

You could use LINQBridge (MIT Licensed) to add support for lambda expressions to C# 2.0:

With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0.

find all subsets that sum to a particular value

This my dynamical programming implementation in JS. It will return an array of arrays, each holding the subsequences summing to the provided target value.

_x000D_
_x000D_
function getSummingItems(a,t){_x000D_
  return a.reduce((h,n) => Object.keys(h)_x000D_
                                 .reduceRight((m,k) => +k+n <= t ? (m[+k+n] = m[+k+n] ? m[+k+n].concat(m[k].map(sa => sa.concat(n)))_x000D_
                                                                                      : m[k].map(sa => sa.concat(n)),m)_x000D_
                                                                 :  m, h), {0:[[]]})[t];_x000D_
}_x000D_
var arr = Array(20).fill().map((_,i) => i+1), // [1,2,..,20]_x000D_
    tgt = 42,_x000D_
    res = [];_x000D_
_x000D_
console.time("test");_x000D_
res = getSummingItems(arr,tgt);_x000D_
console.timeEnd("test");_x000D_
console.log("found",res.length,"subsequences summing to",tgt);_x000D_
console.log(JSON.stringify(res));
_x000D_
_x000D_
_x000D_

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

Enable IIS7 gzip

Global Gzip in HttpModule

If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

Testing

Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).

annotation to make a private method public only for test classes

We recently released a library that helps a lot to access private fields, methods and inner classes through reflection : BoundBox

For a class like

public class Outer {
    private static class Inner {
        private int foo() {return 2;}
    }
}

It provides a syntax like :

Outer outer = new Outer();
Object inner = BoundBoxOfOuter.boundBox_new_Inner();
new BoundBoxOfOuter.BoundBoxOfInner(inner).foo();

The only thing you have to do to create the BoundBox class is to write @BoundBox(boundClass=Outer.class) and the BoundBoxOfOuter class will be instantly generated.

Simple pagination in javascript

Below is the pagination logic as a function


function Pagination(pageEleArr, numOfEleToDisplayPerPage) {
    this.pageEleArr = pageEleArr;
    this.numOfEleToDisplayPerPage = numOfEleToDisplayPerPage;
    this.elementCount = this.pageEleArr.length;
    this.numOfPages = Math.ceil(this.elementCount / this.numOfEleToDisplayPerPage);
    const pageElementsArr = function (arr, eleDispCount) {
        const arrLen = arr.length;
        const noOfPages = Math.ceil(arrLen / eleDispCount);
        let pageArr = [];
        let perPageArr = [];
        let index = 0;
        let condition = 0;
        let remainingEleInArr = 0;

        for (let i = 0; i < noOfPages; i++) {

            if (i === 0) {
                index = 0;
                condition = eleDispCount;
            }
            for (let j = index; j < condition; j++) {
                perPageArr.push(arr[j]);
            }
            pageArr.push(perPageArr);
            if (i === 0) {
                remainingEleInArr = arrLen - perPageArr.length;
            } else {
                remainingEleInArr = remainingEleInArr - perPageArr.length;
            }

            if (remainingEleInArr > 0) {
                if (remainingEleInArr > eleDispCount) {
                    index = index + eleDispCount;
                    condition = condition + eleDispCount;
                } else {
                    index = index + perPageArr.length;
                    condition = condition + remainingEleInArr;
                }
            }
            perPageArr = [];
        }
        return pageArr;
    }
    this.display = function (pageNo) {
        if (pageNo > this.numOfPages || pageNo <= 0) {
            return -1;
        } else {
            console.log('Inside else loop in display method');
            console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage));
            console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1]);
            return pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1];
        }
    }
}

const p1 = new Pagination(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
console.log(p1.elementCount);
console.log(p1.pageEleArr);
console.log(p1.numOfPages);
console.log(p1.numOfEleToDisplayPerPage);
console.log(p1.display(3));

setting JAVA_HOME & CLASSPATH in CentOS 6

Providing javac is set up through /etc/alternatives/javac, you can add to your .bash_profile:

JAVA_HOME=$(l=$(which javac) ; while : ; do nl=$(readlink ${l}) ; [ "$nl" ] || break ; l=$nl ; done ; echo $(cd $(dirname $l)/.. ; pwd) )
export JAVA_HOME

What does "dereferencing" a pointer mean?

Code and explanation from Pointer Basics:

The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.

void main() {   
    int*    x;  // Allocate the pointer x
    x = malloc(sizeof(int));    // Allocate an int pointee,
                            // and set x to point to it
    *x = 42;    // Dereference x to store 42 in its pointee   
}

Handling NULL values in Hive

Firstly — I don't think column1 is not NULL or column1 <> '' makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> '' (AND instead of OR)?

Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL when you read from them. So, for example, if table1.column1 is of type STRING and table2.column1 is of type INT, then I don't think that table1.column1 IS NOT NULL is enough to guarantee that table2.column1 IS NOT NULL. (I'm not sure about this, though.)

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

best practice font size for mobile

Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px. By declaring styles that lead to computed font-sizes of less than 12px, like so:

html {
  font-size: 8px;
}
p {
  font-size: 1.4rem;
}
// Computed p size: 11px.

You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px as 12px. So, the following is true:

h6 {
    font-size: 12px;
}
p {
   font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.   
// How unpleasant of a surprise.

I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.

I would instead, opt for something like this:

h1 {
    font-size: 2.5rem;
}

h2 {
    font-size: 2.25rem;
}

h3 {
    font-size: 2rem;
}

h4 {
    font-size: 1.75rem;
}

h5 {
    font-size: 1.5rem;
}

h6 {
    font-size: 1.25rem;
}

p {
    font-size: 1rem;
}

@media (max-width: 480px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 480px) {
    html {
        font-size: 13px;
    }
}

@media (min-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 992px) {
    html {
        font-size: 15px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}

You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p elements.

As a side note, setting margin-bottom equal to the font-size usually also tends to be attractive, i.e.:

h1 {
    font-size: 2.5rem;
    margin-bottom: 2.5rem;
}

Good luck.

How to change identity column values programmatically?

You need to

set identity_insert YourTable ON

Then delete your row and reinsert it with different identity.

Once you have done the insert don't forget to turn identity_insert off

set identity_insert YourTable OFF

Differences between Microsoft .NET 4.0 full Framework and Client Profile

You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.

Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.

PHP Constants Containing Arrays?

You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.

define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
var_dump($fruits);

Splitting string into multiple rows in Oracle

i had used the DBMS_UTILITY.comma_to _table function actually its working the code as follows

declare
l_tablen  BINARY_INTEGER;
l_tab     DBMS_UTILITY.uncl_array;
cursor cur is select * from qwer;
rec cur%rowtype;
begin
open cur;
loop
fetch cur into rec;
exit when cur%notfound;
DBMS_UTILITY.comma_to_table (
     list   => rec.val,
     tablen => l_tablen,
     tab    => l_tab);
FOR i IN 1 .. l_tablen LOOP
    DBMS_OUTPUT.put_line(i || ' : ' || l_tab(i));
END LOOP;
end loop;
close cur;
end; 

i had used my own table and column names

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

How to make image hover in css?

Make on class with this. And make 2 different images with the self width and height. Works in ie9.

See this link.

http://kyleschaeffer.com/development/pure-css-image-hover/

Also you can 2 differents images make and place in the self class name with in the hover the another images.

See example.

 .myButtonLink {
              margin-top: -5px;

    display: block;
    width: 45px;
    height: 39px;
    background: url('images/home1.png') bottom;
    text-indent: -99999px;
              margin-left:-17px;

              margin-right:-17px;

              margin-bottom: -5px;

              border-radius: 3px;
              -webkit-border-radius: 3px;           
}

.myButtonLink:hover {
    margin-top:  -5px;

    display: block;
    width: 45px;
    height: 39px;
              background: url('images/home2.png') bottom;
              text-indent: -99999px;
              margin-left:-17px;

              margin-right:-17px;

              margin-bottom: -20x;

              border-radius: 3px;
              -webkit-border-radius: 3px;
}

How can I restart a Java application?

Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.

You could do some tricks with custom classloaders to load, pack, and start the AWT components again but this will likely cause lots of headaches with regard to the GUI event loop.

Depending on how the application is launched, you could start the JVM in a wrapper script which contains a do/while loop, which continues while the JVM exits with a particular code, then the AWT app would have to call System.exit(RESTART_CODE). For example, in scripting pseudocode:

DO
  # Launch the awt program
  EXIT_CODE = # Get the exit code of the last process
WHILE (EXIT_CODE == RESTART_CODE)

The AWT app should exit the JVM with something other than the RESTART_CODE on "normal" termination which doesn't require restart.

DateDiff to output hours and minutes

Try this query

select
    *,
    Days          = datediff(dd,0,DateDif),
    Hours         = datepart(hour,DateDif),
    Minutes       = datepart(minute,DateDif),
    Seconds       = datepart(second,DateDif),
    MS            = datepart(ms,DateDif)
from
    (select
         DateDif = EndDate-StartDate,
         aa.*
     from
         (  -- Test Data
          Select
              StartDate = convert(datetime,'20090213 02:44:37.923'),
              EndDate   = convert(datetime,'20090715 13:24:45.837')) aa
    ) a

Output

DateDif                  StartDate                EndDate                 Days Hours Minutes Seconds MS
-----------------------  -----------------------  ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913  2009-02-13 02:44:37.923  2009-07-15 13:24:45.837 152  10    40      7       913

(1 row(s) affected)

What's the best way to get the current URL in Spring MVC?

Instead of using RequestContextHolder directly, you can also use ServletUriComponentsBuilder and its static methods:

  • ServletUriComponentsBuilder.fromCurrentContextPath()
  • ServletUriComponentsBuilder.fromCurrentServletMapping()
  • ServletUriComponentsBuilder.fromCurrentRequestUri()
  • ServletUriComponentsBuilder.fromCurrentRequest()

They use RequestContextHolder under the hood, but provide additional flexibility to build new URLs using the capabilities of UriComponentsBuilder.

Example:

ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
builder.replaceQueryParam("someBoolean", false);
URI newUri = builder.build().toUri();

Convert Array to Object

I would use underscore for this, but if that isn't available then I would drop down to using reduce with an initial value of empty object {}

>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}

reduce should be widely available in most browsers today, see MDN

Define constant variables in C++ header

C++17 inline variables

This awesome C++17 feature allow us to:

  • conveniently use just a single memory address for each constant
  • store it as a constexpr: How to declare constexpr extern?
  • do it in a single line from one header

main.cpp

#include <cassert>

#include "notmain.hpp"

int main() {
    // Both files see the same memory address.
    assert(&notmain_i == notmain_func());
    assert(notmain_i == 42);
}

notmain.hpp

#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP

inline constexpr int notmain_i = 42;

const int* notmain_func();

#endif

notmain.cpp

#include "notmain.hpp"

const int* notmain_func() {
    return &notmain_i;
}

Compile and run:

g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main

GitHub upstream.

See also: How do inline variables work?

C++ standard on inline variables

The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":

6 An inline function or variable with external linkage shall have the same address in all translation units.

cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static is not given, then it has external linkage.

Inline variable implementation

We can observe how it is implemented with:

nm main.o notmain.o

which contains:

main.o:
                 U _GLOBAL_OFFSET_TABLE_
                 U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
                 U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i

notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i

and man nm says about u:

"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.

so we see that there is a dedicated ELF extension for this.

C++17 standard draft on "global" const implies static

This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245

C++17 n4659 standard draft 6.5 "Program and linkage":

3 A name having namespace scope (6.3.6) has internal linkage if it is the name of

  • (3.1) — a variable, function or function template that is explicitly declared static; or,
  • (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
  • (3.3) — a data member of an anonymous union.

"namespace" scope is what we colloquially often refer to as "global".

Annex C (informative) Compatibility, C.1.2 Clause 6: "basic concepts" gives the rationale why this was changed from C:

6.5 [also 10.1.7]

Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage.

Rationale: Because const objects may be used as values during translation in C++, this feature urges programmers to provide an explicit initializer for each const object. This feature allows the user to put const objects in source files that are included in more than one translation unit.

Effect on original feature: Change to semantics of well-defined feature.

Difficulty of converting: Semantic transformation.

How widely used: Seldom.

See also: Why does const imply internal linkage in C++, when it doesn't in C?

Tested in GCC 7.4.0, Ubuntu 18.04.

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Bootstrap 3 Collapse show state with Chevron icon

Angular seems to cause issues with the JavaScript-based approaches here ( at least the ones I've tried ) . I found this solution here: http://www.codeproject.com/Articles/987311/Collapsible-Responsive-Master-Child-Grid-Using-Ang . The gist of it is to use data-ng-click on the toggle button and make the method to change the button in the controller using the $scope context .

I guess I could provide more detail... my buttons are set to the glyphicon of the initial state of the div they collapse ( glyphicon-chevron-right == collapsed div ) .

page.html:

<div class="title-1">
    <button data-toggle="collapse" data-target="#panel-{{ p_idx }}" class="dropdown-toggle title-btn glyphicon glyphicon-chevron-right" data-ng-click="collapse($event)"></button>
</div>
<div id="panel-{{ p_idx }}" class="collapse sect">
    ...
</div>

controllers.js:

.controller('PageController', function($scope, $rootScope) {
    $scope.collapse = function (event) {
        $(event.target).toggleClass("glyphicon-chevron-down glyphicon-chevron-right");
    };
)

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Ok why the complicated use of libraries and stuff? C++ String objects overload the [] operator, so you can just compare chars.. Like what I just did, because I want to list all files in a directory and ignore invisible files and the .. and . pseudofiles.

while ((ep = readdir(dp)))
{
    string s(ep->d_name);
    if (!(s[0] == '.')) // Omit invisible files and .. or .
        files.push_back(s);
}

It's that simple..

How do I set up cron to run a file just once at a specific time?

For those who is not able to access/install at in environment, can use custom script:

#!/bin/bash
if [ $# -lt 2 ]; then
echo ""
echo "Syntax Error!"
echo "Usage: $0 <shell script> <datetime>"
echo "<datetime> format: %Y%m%d%H%M"
echo "Example: $0 /home/user/scripts/server_backup.sh 202008142350"
echo ""
exit 1
fi

while true; do
  t=$(date +%Y%m%d%H%M);      
  if [ $t -eq $2 ]; then
    /bin/bash $1
    echo DONE $(date);
    break;
  fi;
  sleep 1;
done

Let's name the script as run1time.sh Example could be something like:

nohup bash run1time.sh /path/to/your/script.sh 202008150300 &

Adding to a vector of pair

Use std::make_pair:

revenue.push_back(std::make_pair("string",map[i].second));

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

The other answers in my case did not work. I had to restart windows before I could debug the application again.

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

How can I scroll a web page using selenium webdriver in python?

I was looking for a way of scrolling through a dynamic webpage, and automatically stopping once the end of the page is reached, and found this thread.

The post by @Cuong Tran, with one main modification, was the answer that I was looking for. I thought that others might find the modification helpful (it has a pronounced effect on how the code works), hence this post.

The modification is to move the statement that captures the last page height inside the loop (so that each check is comparing to the previous page height).

So, the code below:

Continuously scrolls down a dynamic webpage (.scrollTo()), only stopping when, for one iteration, the page height stays the same.

(There is another modification, where the break statement is inside another condition (in case the page 'sticks') which can be removed).

    SCROLL_PAUSE_TIME = 0.5


    while True:

        # Get scroll height
        ### This is the difference. Moving this *inside* the loop
        ### means that it checks if scrollTo is still scrolling 
        last_height = driver.execute_script("return document.body.scrollHeight")

        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:

            # try again (can be removed)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            # Wait to load page
            time.sleep(SCROLL_PAUSE_TIME)

            # Calculate new scroll height and compare with last scroll height
            new_height = driver.execute_script("return document.body.scrollHeight")

            # check if the page height has remained the same
            if new_height == last_height:
                # if so, you are done
                break
            # if not, move on to the next loop
            else:
                last_height = new_height
                continue

Should import statements always be at the top of a module?

This is a fascinating discussion. Like many others I had never even considered this topic. I got cornered into having to have the imports in the functions because of wanting to use the Django ORM in one of my libraries. I was having to call django.setup() before importing my model classes and because this was at the top of the file it was being dragged into completely non-Django library code because of the IoC injector construction.

I kind of hacked around a bit and ended up putting the django.setup() in the singleton constructor and the relevant import at the top of each class method. Now this worked fine but made me uneasy because the imports weren't at the top and also I started worrying about the extra time hit of the imports. Then I came here and read with great interest everybody's take on this.

I have a long C++ background and now use Python/Cython. My take on this is that why not put the imports in the function unless it causes you a profiled bottleneck. It's only like declaring space for variables just before you need them. The trouble is I have thousands of lines of code with all the imports at the top! So I think I will do it from now on and change the odd file here and there when I'm passing through and have the time.

Limit the height of a responsive image with css

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

Programmatically get the version number of a DLL

To get it for the assembly that was started (winform, console app, etc...)

using System.Reflection;
...
Assembly.GetEntryAssembly().GetName().Version

How to vertically center an image inside of a div element in HTML using CSS?

if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background

background-position: center center;

If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:

div{
    display: table-cell; vertical-align: middle 
}

Read more about this technique here. Reported to not work on IE6/7 (works on IE8).

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Java generics - get class?

I like the solution from

http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/

public class Dada<T> {

    private Class<T> typeOfT;

    @SuppressWarnings("unchecked")
    public Dada() {
        this.typeOfT = (Class<T>)
                ((ParameterizedType)getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
...

How can I create an executable JAR with dependencies using Maven?

The maven-assembly-plugin worked great for me. I spent hours with the maven-dependency-plugin and couldn't make it work. The main reason was that I had to define in the configuration section explicitly the artifact items which should be included as it is described in the documentation. There is an example there for the cases when you want to use it like: mvn dependency:copy, where there are not included any artifactItems but it doesn't work.

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

Find all stored procedures that reference a specific column in some table

You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.

SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
    ,objects.type_desc
FROM syscomments comments
    ,sys.objects objects
WHERE comments.id = objects.object_id
    AND TEXT LIKE '%CreatedDate%'
ORDER BY 1

Adding a line break in MySQL INSERT INTO text

INSERT INTO test VALUES('a line\nanother line');

\n just works fine here

How to create a stopwatch using JavaScript?

jsbin.com demo

You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.

This was a fun little project to work on. Here's how I'd approach it

var Stopwatch = function(elem, options) {

  var timer       = createTimer(),
      startButton = createButton("start", start),
      stopButton  = createButton("stop", stop),
      resetButton = createButton("reset", reset),
      offset,
      clock,
      interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements     
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset   = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render();
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    timer.innerHTML = clock/1000; 
  }

  function delta() {
    var now = Date.now(),
        d   = now - offset;

    offset = now;
    return d;
  }

  // public API
  this.start  = start;
  this.stop   = stop;
  this.reset  = reset;
};

Get some basic HTML wrappers for it

<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>

Usage is dead simple from there

var elems = document.getElementsByClassName("stopwatch");

for (var i=0, len=elems.length; i<len; i++) {
  new Stopwatch(elems[i]);
}

As a bonus, you get a programmable API for the timers as well. Here's a usage example

var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});

// start the timer
timer.start();

// stop the timer
timer.stop();

// reset the timer
timer.reset();

jQuery plugin

As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode

(function($) {

  var Stopwatch = function(elem, options) {
    // code from above...
  };

  $.fn.stopwatch = function(options) {
    return this.each(function(idx, elem) {
      new Stopwatch(elem, options);
    });
  };
})(jQuery);

jQuery plugin usage

// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();

// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});

replacing text in a file with Python

I might consider using a dict and re.sub for something like this:

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

This has a slight advantage to replace in that it is a bit more robust to overlapping matches.

How do you install GLUT and OpenGL in Visual Studio 2012?

Yes visual studio 2012 express has built in opengl library. the headers are in the folder C:\Program Files\Windows Kits\8.0\Include\um\gl and the lib files are in folder C:\Program Files\Windows Kits\8.0\Lib\win8\um\x86 & C:\Program Files\Windows Kits\8.0\Lib\win8\um\x64. but the problem is integrating the glut with the existing one.. i downloaded the library from http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip.. and deployed the files into .....\gl and ....\lib\win8\um\x32 and the dll to %system%/windows folders respectively.. Hope so this will solve the problem...

Oracle SQL, concatenate multiple columns + add text

Try this:

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake_Column FROM your_table_name;

It should concatenate all that data as a single column entry named "Cake_Column".

Group list by values

I don't know about elegant, but it's certainly doable:

oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
# change into: list = [["A", "C"], ["B"], ["D", "E"]]

order=[]
dic=dict()
for value,key in oldlist:
  try:
    dic[key].append(value)
  except KeyError:
    order.append(key)
    dic[key]=[value]
newlist=map(dic.get, order)

print newlist

This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.

Copy map values to vector in STL

If you are using the boost libraries, you can use boost::bind to access the second value of the pair as follows:

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

int main()
{
   typedef std::map<std::string, int> MapT;
   typedef std::vector<int> VecT;
   MapT map;
   VecT vec;

   map["one"] = 1;
   map["two"] = 2;
   map["three"] = 3;
   map["four"] = 4;
   map["five"] = 5;

   std::transform( map.begin(), map.end(),
                   std::back_inserter(vec),
                   boost::bind(&MapT::value_type::second,_1) );
}

This solution is based on a post from Michael Goldshteyn on the boost mailing list.

Count the number of occurrences of a character in a string in Javascript

And there is:

function character_count(string, char, ptr = 0, count = 0) {
    while (ptr = string.indexOf(char, ptr) + 1) {count ++}
    return count
}

Works with integers too!

How can I run an EXE program from a Windows Service using C#?

I think You are copying the .exe to different location. This might be the problem I guess. When you copy the exe, you are not copying its dependencies.

So, what you can do is, put all dependent dlls in GAC so that any .net exe can access it

Else, do not copy the exe to new location. Just create a environment variable and call the exe in your c#. Since the path is defined in environment variables, the exe is can be accessed by your c# program.

Update:

previously I had some kind of same issue in my c#.net 3.5 project in which I was trying to run a .exe file from c#.net code and that exe was nothing but the another project exe(where i added few supporting dlls for my functionality) and those dlls methods I was using in my exe application. At last I resolved this by creating that application as a separate project to the same solution and i added that project output to my deployment project. According to this scenario I answered, If its not what he wants then I am extremely sorry.

Removing address bar from browser (to view on Android)

The problem with most of these is that the user can still scroll up and see the addressbar. To make a permanent solution, you need to add this as well.

//WHENEVER the user scrolls
$(window).scroll(function(){
    //if you reach the top
    if ($(window).scrollTop() == 0)   
    //scroll back down  
    {window.scrollTo(1,1)}
})

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Git: How to find a deleted file in the project commit history?

Below is a simple command, where a dev or a git user can pass a deleted file name from the repository root directory and get the history:

git log --diff-filter=D --summary | grep filename | awk '{print $4; exit}' | xargs git log --all -- 

If anybody, can improve the command, please do.

fill an array in C#

int[] arr = Enumerable.Repeat(42, 10000).ToArray();

I believe that this does the job :)

image.onload event and browser cache

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

How to parse dates in multiple formats using SimpleDateFormat

I'm solved this problem more simple way using regex

fun parseTime(time: String?): Long {
    val longRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}.\\d{3}[Z]\$"
    val shortRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}Z\$"

    val longDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssXXX")
    val shortDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")

    return when {
        Pattern.matches(longRegex, time) -> longDateFormat.parse(time).time
        Pattern.matches(shortRegex, time) -> shortDateFormat.parse(time).time
        else -> throw InvalidParamsException(INVALID_TIME_MESSAGE, null)
    }
}

Submit form using <a> tag

<form  id="myform_id" action="/myMethode"  role="form"  method="post" > 
   <a  href="javascript:$('#myform_id').submit();" >submit</a>
</form>

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

How can I remove all my changes in my SVN working directory?

You can use the following command to revert all local changes:

svn st -q | awk '{print $2;}' | xargs svn revert

Sprintf equivalent in Java

You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:

PrintStream ps = new PrintStream(baos);
ps.printf("there is a %s from %d %s", "hello", 3, "friends");
System.out.println(baos.toString());
baos.reset(); //need reset to write new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");
System.out.println(baos.toString());
baos.reset();

The string stream can be created like this ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

File extensions for cryptographic certificates aren't really as standardized as you'd expect. Windows by default treats double-clicking a .crt file as a request to import the certificate into the Windows Root Certificate store, but treats a .cer file as a request just to view the certificate. So, they're different in the sense that Windows has some inherent different meaning for what happens when you double click each type of file.

But the way that Windows handles them when you double-click them is about the only difference between the two. Both extensions just represent that it contains a public certificate. You can rename a certificate file to use one extension in place of the other in any system or configuration file that I've seen. And on non-Windows platforms (and even on Windows), people aren't particularly careful about which extension they use, and treat them both interchangeably, as there's no difference between them as long as the contents of the file are correct.

Making things more confusing is that there are two standard ways of storing certificate data in a file: One is a "binary" X.509 encoding, and the other is a "text" base64 encoding that usually starts with "-----BEGIN CERTIFICATE-----". These encode the same data but in different ways. Most systems accept both formats, but, if you need to, you can convert one to the other via openssl or other tools. The encoding within a certificate file is really independent of which extension somebody gave the file.

How do I disable right click on my web page?

If you are a jquery fan,use this

    $(function() {
        $(this).bind("contextmenu", function(e) {
            e.preventDefault();
        });
    }); 

What is the difference between Cloud, Grid and Cluster?

my two cents worth ~

Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.

Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers

Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers

Python popen command. Wait until the command is finished

What you are looking for is the wait method.

How to print to stderr in Python?

I did the following using Python 3:

from sys import stderr

def print_err(*args, **kwargs):
    print(*args, file=stderr, **kwargs)

So now I'm able to add keyword arguments, for example, to avoid carriage return:

print_err("Error: end of the file reached. The word ", end='')
print_err(word, "was not found")

Save and load weights in keras

For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

Where is a log file with logs from a container?

To see how much space each container's log is taking up, use this:

docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl

(you might need a sudo before ls).

How to trigger jQuery change event in code

Use the trigger() method

$(selector).trigger("change");

What does "to stub" mean in programming?

"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."

From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones

Why does HTML think “chucknorris” is a color?

I now this this is not an image made by me, but this image can help a lot... enter image description here

So, here is an little app that I created so you can play with the values

_x000D_
_x000D_
function parseColor(input) {
  input = input.trim();
  if (input.length > 128) {
    input = input.slice(0, 128);
  }
  if (input.charAt(0) === "#") {
    input = input.slice(1);
  }
  input = input.replace(/[^0-9A-Fa-f]/g, "0");
  while (input.length === 0 || input.length % 3 > 0) {
    input += "0";
  }
  var r = input.slice(0, input.length / 3);
  var g = input.slice(input.length / 3, input.length * 2 / 3);
  var b = input.slice(input.length * 2 / 3);
  if (r.length > 8) {
    r = r.slice(-8);
    g = g.slice(-8);
    b = b.slice(-8);
  }
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {
    r = r.slice(1);
    g = g.slice(1);
    b = b.slice(1);
  }
  if (r.length > 2) {
    r = r.slice(0, 2);
    g = g.slice(0, 2);
    b = b.slice(0, 2);
  }
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");
}

$(function() {
  $("#input").on("change", function() {
    var input = $(this).val();
    var color = parseColor(input);
    var $cells = $("#result tbody td");
    $cells.eq(0).attr("bgcolor", input);
    $cells.eq(1).attr("bgcolor", color);

    var color1 = $cells.eq(0).css("background-color");
    var color2 = $cells.eq(1).css("background-color");
    $cells.eq(2).empty().append("background-color: " + input, "<br>", "getComputedStyle: " + color1);
    $cells.eq(3).empty().append("background-color: " + color, "<br>", "getComputedStyle: " + color2);
  });
});
_x000D_
* { font: monospace; }
input { width: 100hv; }
table { table-layout: fixed; width: 100%; }
input {border: 1px solid black;border-radius: 5px;outline:none;padding: 10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<p><input id="input" placeholder="Enter color e.g. demofothedayischur000! or ffffssssrrrddswww!"></p><details>
<summary>Color examples (drag-and-drop)</summary>
Try this colors:<br>
Batato<br>
Muatre!<br>
fsdyelow"<br>
000meandthis<br>
!!!!!<br>
entrcolor<br>
yellowofthe!<br>
!!!me!!!you!!!aregre!:;H<br>
!"#$%&/()=<br>
/()=??»»<br>
thsdem<br></details>
<details>
<summary>
Or.... Want a big example?
</summary>
Here it goes:<br>
Batato Muatre! dtexbtfe dodx42 f 1dzxwq lorem ip os dh4huryx nyxze eimqdmuezo fsdyelow" 000meandthis !!!!! entrcolor yellowofthe! !!!me!!!you!!!aregre!:;H !"#$%&/()= /()=??»» thsdem
</details>
<table id="result">
  <thead>
    <tr>
      <th>Left Color</th>
      <th>Right Color</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Find TODO tags in Eclipse

In adition to the other answers mentioning the Tasks view:

It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub.

To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:

enter image description here

This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).

How can I manually set an Angular form field as invalid?

Though its late but following solution worked form me.

    let control = this.registerForm.controls['controlName'];
    control.setErrors({backend: {someProp: "Invalid Data"}});
    let message = control.errors['backend'].someProp;

Drawing a dot on HTML5 canvas

The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:

I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm

Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.

At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)

Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..

What is the proper #include for the function 'sleep()'?

this is what I use for a cross-platform code:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

int main()
{
  pollingDelay = 100
  //do stuff

  //sleep:
  #ifdef _WIN32
  Sleep(pollingDelay);
  #else
  usleep(pollingDelay*1000);  /* sleep for 100 milliSeconds */
  #endif

  //do stuff again
  return 0;
}

Installing Homebrew on OS X

If you still get error after running,

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then try to download and install command line tool from https://developer.apple.com/download/more/ for your particular Mac os and Xcode version.

Then try to run,

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

and then

brew install node

Laravel Eloquent LEFT JOIN WHERE NULL

I would be using laravel whereDoesntHave to achieve this.

Customer::whereDoesntHave('orders')->get();

How do I get the MAX row with a GROUP BY in LINQ query?

        using (DataContext dc = new DataContext())
        {
            var q = from t in dc.TableTests
                    group t by t.SerialNumber
                        into g
                        select new
                        {
                            SerialNumber = g.Key,
                            uid = (from t2 in g select t2.uid).Max()
                        };
        }

Change image source with JavaScript

Your only real problem is you are passing a string, not an object with a .src property

Some suggestions:

  • Use a naturally clickable element trigger, such as <button>
  • Use data- prefixed attributes for event data on the element
  • Use late bound events when the DOM is ready.

Markup:

<div id="main_img">
  <img id="img" src="1772031_29_b.jpg">
</div>
<ul id="thumb_img">
  <li><button data-src='1772031_29_b.jpg'><img src='1772031_29_t.jpg' /></button></li>
  <li><button data-src='1772031_55_b.jpg'><img src='1772031_55_t.jpg' /></button></li>
  <li><button data-src='1772031_53_b.jpg'><img src='1772031_53_t.jpg' /></button></li>
</ul>

JavaScript:

If you need to support IE and other legacy browsers, Use a proper polyfill for Array.from

function clickedButton(btn, event) {
  document.getElementById('img').src = btn.getAttribute('data-src');
}

function bindClick(btn) {
  btn.addEventListener('click', clickedButton.bind(null,btn));
}

// Setup click handler(s) when content is loaded
document.addEventListener("DOMContentLoaded", function(){
  Array.from(document.querySelectorAll('#thumb_img > button'))
    .forEach(bindClick));
});

Edit: Vanilla JS for modern browsers.

How do you check if a variable is an array in JavaScript?

Something I just came up with:

if (item.length) //This is an array else //not an array

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

How to change a DIV padding without affecting the width/height ?

Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing and for Safari/Chrome, use -webkit-box-sizing.

IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.

Difference between natural join and inner join

mysql> SELECT  * FROM tb1 ;
+----+------+
| id | num  |
+----+------+
|  6 |   60 |
|  7 |   70 |
|  8 |   80 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

mysql> SELECT  * FROM tb2 ;
+----+------+
| id | num  |
+----+------+
|  4 |   40 |
|  5 |   50 |
|  9 |   90 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

INNER JOIN :

mysql> SELECT  * FROM tb1 JOIN tb2 ; 
+----+------+----+------+
| id | num  | id | num  |
+----+------+----+------+
|  6 |   60 |  4 |   40 |
|  7 |   70 |  4 |   40 |
|  8 |   80 |  4 |   40 |
|  1 |    1 |  4 |   40 |
|  2 |    2 |  4 |   40 |
|  3 |    3 |  4 |   40 |
|  6 |   60 |  5 |   50 |
|  7 |   70 |  5 |   50 |
|  8 |   80 |  5 |   50 |
.......more......
return 36 rows in set (0.01 sec) 
AND NATURAL JOIN :

    mysql> SELECT  * FROM tb1 NATURAL JOIN tb2 ;
    +----+------+
    | id | num  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    |  3 |    3 |
    +----+------+
    3 rows in set (0.01 sec)

jQuery Loop through each div

$('div.target').each(function() {
   /* Measure the width of each image. */
   var test = $(this).find('.scrolling img').width();

   /* Find out how many images there are. */
   var testimg = $(this).find('.scrolling img').length;

   /* Do the maths. */
   var final = (test* testimg)*1.2;

   /* Apply the maths to the CSS. */
   $(this).find('scrolling').width(final); 
});

Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

Drawing a line/path on Google Maps

Yes you need to use overlays.

You need to get the MapView's overlays and add your new overlay onto it.

Your class extends Overlay, which is a transparent canvas in which you can draw on it like any other canvas.

You can use mapView.getProjection() to get projection of map view.

...

More info found here: http://blogoscoped.com/archive/2008-12-15-n14.html

How to select an item from a dropdown list using Selenium WebDriver with java?

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

dropdown.selectByValue("prog");

Happy Coding :)

How to present a modal atop the current view in Swift

I am updating a simple solution. First add an id to your segue which presents modal. Than in properties change it's presentation style to "Over Current Context". Than add this code in presenting view controller (The controller which is presenting modal).

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let Device = UIDevice.currentDevice()

    let iosVersion = NSString(string: Device.systemVersion).doubleValue

    let iOS8 = iosVersion >= 8
    let iOS7 = iosVersion >= 7 && iosVersion < 8
    if((segue.identifier == "chatTable")){

    if (iOS8){


          }
        else {

            self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.CurrentContext


        }
    }
}

Make sure you change segue.identifier to your own id ;)

XPath with multiple conditions

Try:
//category[@name='Sport' and ./author/text()='James Small']

JUnit Testing Exceptions

If your constructor is similar to this one:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    }
    //do fun things with valid example here
}

Then, when you run this JUnit test you will get a green bar:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);
}

How do I separate an integer into separate digits in an array in JavaScript?

Suppose,

let a = 123456

First we will convert it into string and then apply split to convert it into array of characters and then map over it to convert the array to integer.

let b = a.toString().split('').map(val=>parseInt(val))
console.log(b)

Usage of MySQL's "IF EXISTS"

if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1 
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1 
end
else
begin
print 'the record does not exits'
end

Add an object to an Array of a custom class

If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:

List<Car> garage = new ArrayList<Car>();
garage.add(redCar);

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Add class to an element in Angular 4

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

What is the difference between Swing and AWT?

AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.

Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "pluggable look and feel" that can make it look more or less like how the native windows and widgets would look).

These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:

AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those toolkits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.

Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.

Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.

Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Update: as of the day of this writing, namedTuples are pickable (starting with python 2.7)

The issue here is the child processes aren't able to import the class of the object -in this case, the class P-, in the case of a multi-model project the Class P should be importable anywhere the child process get used

a quick workaround is to make it importable by affecting it to globals()

globals()["P"] = P

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

Just pressing F5 is not always working.

why?

Because your ISP is also caching web data for you.

Solution: Force Refresh.

Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5

You then can see 200 response instead of 304 in the browser F12 developer tools network tab.

Another trick is to add question mark ? at the end of the URL string of the requested page:

http://localhost:52199/Customers/Create?

The question mark will ensure that the browser refresh the request without caching any previous requests.

Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):

Go to browsers list Select browse with... Click Add... Point to the chrome.exe on your platform, add argument "Incognito" Choose the browser you just added and set as default, then click browse

Parsing JSON array into java.util.List with Gson

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

Validation of file extension before uploading file

None of the existing answers seemed quite compact enough for the simplicity of the request. Checking if a given file input field has an extension from a set can be accomplished as follows:

function hasExtension(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName);
}

So example usage might be (where upload is the id of a file input):

if (!hasExtension('upload', ['.jpg', '.gif', '.png'])) {
    // ... block upload
}

Or as a jQuery plugin:

$.fn.hasExtension = function(exts) {
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test($(this).val());
}

Example usage:

if (!$('#upload').hasExtension(['.jpg', '.png', '.gif'])) {
    // ... block upload
}

The .replace(/\./g, '\\.') is there to escape the dot for the regexp so that basic extensions can be passed in without the dots matching any character.

There's no error checking on these to keep them short, presumably if you use them you'll make sure the input exists first and the extensions array is valid!

SET NOCOUNT ON usage

I don't know how to test SET NOCOUNT ON between client and SQL, so I tested a similar behavior for other SET command "SET TRANSACTION ISOLATION LEVEL READ UNCIMMITTED"

I sent a command from my connection changing the default behavior of SQL (READ COMMITTED), and it was changed for the next commands. When I changed the ISOLATION level inside a stored procedure, it didn't change the connection behavior for the next command.

Current conclusion,

  1. Changing settings inside stored procedure doesn't change the connection default settings.
  2. Changing setting by sending commands using the ADOCOnnection changes the default behavior.

I think this is relevant to other SET command such like "SET NOCOUNT ON"

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

How to create a RelativeLayout programmatically with two buttons one on top of the other?

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

python exception message capturing

After python 3.6, you can use formatted string literal. It's neat! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)

try
 ...
except Exception as e:
    logger.error(f"Failed to upload to ftp: {e}")

Convert float64 column to int64 in Pandas

Solution for pandas 0.24+ for converting numeric with missing values:

df = pd.DataFrame({'column name':[7500000.0,7500000.0, np.nan]})
print (df['column name'])
0    7500000.0
1    7500000.0
2          NaN
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)

ValueError: Cannot convert non-finite values (NA or inf) to integer

#http://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html
df['column name'] = df['column name'].astype('Int64')
print (df['column name'])
0    7500000
1    7500000
2        NaN
Name: column name, dtype: Int64

I think you need cast to numpy.int64:

df['column name'].astype(np.int64)

Sample:

df = pd.DataFrame({'column name':[7500000.0,7500000.0]})
print (df['column name'])
0    7500000.0
1    7500000.0
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)
#same as
#df['column name'] = df['column name'].astype(pd.np.int64)
print (df['column name'])
0    7500000
1    7500000
Name: column name, dtype: int64

If some NaNs in columns need replace them to some int (e.g. 0) by fillna, because type of NaN is float:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].fillna(0).astype(np.int64)
print (df['column name'])
0    7500000
1          0
Name: column name, dtype: int64

Also check documentation - missing data casting rules

EDIT:

Convert values with NaNs is buggy:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].values.astype(np.int64)
print (df['column name'])
0                7500000
1   -9223372036854775808
Name: column name, dtype: int64

Order a List (C#) by many fields?

Make your object something like

public class MyObject : IComparable
{
    public string a;
    public string b;

    virtual public int CompareTo(object obj)
    {
        if (obj is MyObject)
        {
            var compareObj = (MyObject)obj;
            if (this.a.CompareTo(compareObj.a) == 0)
            {
                // compare second value
                return this.b.CompareTo(compareObj.b);
            }
            return this.a.CompareTo(compareObj.b);
        }
        else
        {
            throw new ArgumentException("Object is not a MyObject ");
        }
    }
}

also note that the returns for CompareTo :

http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx

Then, if you have a List of MyObject, call .Sort() ie

var objList = new List<MyObject>();
objList.Sort();

What is Dependency Injection?

The whole point of Dependency Injection (DI) is to keep application source code clean and stable:

  • clean of dependency initialization code
  • stable regardless of dependency used

Practically, every design pattern separates concerns to make future changes affect minimum files.

The specific domain of DI is delegation of dependency configuration and initialization.

Example: DI with shell script

If you occasionally work outside of Java, recall how source is often used in many scripting languages (Shell, Tcl, etc., or even import in Python misused for this purpose).

Consider simple dependent.sh script:

#!/bin/sh
# Dependent
touch         "one.txt" "two.txt"
archive_files "one.txt" "two.txt"

The script is dependent: it won't execute successfully on its own (archive_files is not defined).

You define archive_files in archive_files_zip.sh implementation script (using zip in this case):

#!/bin/sh
# Dependency
function archive_files {
    zip files.zip "$@"
}

Instead of source-ing implementation script directly in the dependent one, you use an injector.sh "container" which wraps both "components":

#!/bin/sh 
# Injector
source ./archive_files_zip.sh
source ./dependent.sh

The archive_files dependency has just been injected into dependent script.

You could have injected dependency which implements archive_files using tar or xz.

Example: removing DI

If dependent.sh script used dependencies directly, the approach would be called dependency lookup (which is opposite to dependency injection):

#!/bin/sh
# Dependent

# dependency look-up
source ./archive_files_zip.sh

touch         "one.txt" "two.txt"
archive_files "one.txt" "two.txt"

Now the problem is that dependent "component" has to perform initialization itself.

The "component"'s source code is neither clean nor stable because every changes in initialization of dependencies requires new release for "components"'s source code file as well.

Last words

DI is not as largely emphasized and popularized as in Java frameworks.

But it's a generic approach to split concerns of:

  • application development (single source code release lifecycle)
  • application deployment (multiple target environments with independent lifecycles)

Using configuration only with dependency lookup does not help as number of configuration parameters may change per dependency (e.g. new authentication type) as well as number of supported types of dependencies (e.g. new database type).

insert multiple rows into DB2 database

I disagree on the comment posted by Hogan. Those instructions will work for IBM DB2 Mini, but it's not the case of DB2 Z/OS.

Here is an example:

Exception data: org.apache.ibatis.exceptions.PersistenceException:
The error occurred while setting parameters

SQL: INSERT INTO TABLENAME(ID_, F1_, F2_, F3_, F4_, F5_) VALUES
 (?,          1,          ?,          ?,          ?,          ?),          
 (?,          1,          ?,          ?,          ?,          ?)


Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException: 
ILLEGAL SYMBOL ",". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: FOR <END-OF-STATEMENT> NOT ATOMIC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.25.17

So I can confirm that inline comma separated bulk inserts are not working on DB2 Z/OS (maybe you could feed it some props to get it working...)

Uppercase first letter of variable

You can try this simple code with the features of ucwords in PHP.

function ucWords(text) {
    return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');

It will keep the Upper Cases unchanged.

typescript - cloning object

function instantiateEmptyObject(obj: object): object {
    if (obj == null) { return {}; }

    const prototype = Object.getPrototypeOf(obj);
    if (!prototype) {
        return {};
    }

    return Object.create(prototype);
}

function quickCopy(src: object, dest: object): object {
    if (dest == null) { return dest; }

    return { ...src, ...dest };
}

quickCopy(src, instantiateEmptyObject(new Customer()));

SFTP Libraries for .NET

We use WinSCP. Its free. Its not a lib, but has a well documented and full featured command line interface that you can use with Process.Start.

Update: with v.5.0, WinSCP has a .NET wrapper library to the scripting layer of WinSCP.

Rollback to last git commit

git reset --hard will force the working directory back to the last commit and delete new/changed files.

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

What are Unwind segues for and how do you use them?

As far as how to use unwind segues in StoryBoard...

Step 1)

Go to the code for the view controller that you wish to unwind to and add this:

Objective-C

- (IBAction)unwindToViewControllerNameHere:(UIStoryboardSegue *)segue {
    //nothing goes here
}

Be sure to also declare this method in your .h file in Obj-C

Swift

@IBAction func unwindToViewControllerNameHere(segue: UIStoryboardSegue) {
    //nothing goes here
}

Step 2)

In storyboard, go to the view that you want to unwind from and simply drag a segue from your button or whatever up to the little orange "EXIT" icon at the top right of your source view.

enter image description here

There should now be an option to connect to "- unwindToViewControllerNameHere"

That's it, your segue will unwind when your button is tapped.

Declaring variables inside loops, good practice or bad practice?

This is excellent practice.

By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.

This way:

  • If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the -Wshadow warning instruction on GCC)

  • The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.

  • Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.

In short, you are right to do it.

Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time. You can also create a larger block, encompassing the loop, whose sole purpose is to declare variables which must retain their value from one loop to another. This typically includes the loop counter itself.

{
    int i, retainValue;
    for (i=0; i<N; i++)
    {
       int tmpValue;
       /* tmpValue is uninitialized */
       /* retainValue still has its previous value from previous loop */

       /* Do some stuff here */
    }
    /* Here, retainValue is still valid; tmpValue no longer */
}

For question #2: The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).

With restricted and more precise scope come more accurate optimizations. But more importantly, it makes your code safer, with less states (i.e. variables) to worry about when reading other parts of the code.

This is true even outside of an if(){...} block. Typically, instead of :

    int result;
    (...)
    result = f1();
    if (result) then { (...) }
    (...)
    result = f2();
    if (result) then { (...) }

it's safer to write :

    (...)
    {
        int const result = f1();
        if (result) then { (...) }
    }
    (...)
    {
        int const result = f2();
        if (result) then { (...) }
    }

The difference may seem minor, especially on such a small example. But on a larger code base, it will help : now there is no risk to transport some result value from f1() to f2() block. Each result is strictly limited to its own scope, making its role more accurate. From a reviewer perspective, it's much nicer, since he has less long range state variables to worry about and track.

Even the compiler will help better : assuming that, in the future, after some erroneous change of code, result is not properly initialized with f2(). The second version will simply refuse to work, stating a clear error message at compile time (way better than run time). The first version will not spot anything, the result of f1() will simply be tested a second time, being confused for the result of f2().

Complementary information

The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.

In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.

For standard types and structures, the size of variable is known at compilation time. There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.

However, for C++ classes, there is this constructor thing which I know much less about. I guess allocation is probably not going to be the issue, since the compiler shall be clever enough to reuse the same space, but the initialization is likely to take place at each loop iteration.

jQuery event handlers always execute in order they were bound - any way around this?

.data("events") has been removed in versions 1.9 and 2.0beta, so you cant any longer rely on those solutions.

http://jquery.com/upgrade-guide/1.9/#data-quot-events-quot-

minimum double value in C/C++

Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (DBL_MAX or numeric_limits<double>::max()), just prepend a minus sign.

And then is the cool way:

double f;
(*((long long*)&f))= ~(1LL<<52);

How to clean up R memory (without the need to restart my PC)?

Use ls() function to see what R objects are occupying space. use rm("objectName") to clear the objects from R memory that is no longer required. See this too.

How to play ringtone/alarm sound in Android

If a user has never set an alarm on their phone, the TYPE_ALARM can return null. You can account for this with:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

if(alert == null){
    // alert is null, using backup
    alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // I can't see this ever being null (as always have a default notification)
    // but just incase
    if(alert == null) {  
        // alert backup is null, using 2nd backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);                
    }
}

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

ElasticSearch - Return Unique Values

You can use the terms aggregation.

{
"size": 0,
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  "size" : 500 }
    }
}}

The size parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.

A search will return something like:

{
"took" : 16,
"timed_out" : false,
"_shards" : {
  "total" : 2,
  "successful" : 2,
  "failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
  "langs" : {
    "buckets" : [ {
      "key" : "10",
      "doc_count" : 244812
    }, {
      "key" : "11",
      "doc_count" : 136794
 
    }, {
      "key" : "12",
      "doc_count" : 32312
       } ]
    }
  }
}

Jquery Validate custom error message location

JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE

Demo & example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $("#registration").validate({_x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      firstname: "required",_x000D_
      lastname: "required",_x000D_
      email: {_x000D_
        required: true,_x000D_
        email: true_x000D_
      },      _x000D_
      phone: {_x000D_
        required: true,_x000D_
        digits: true,_x000D_
        minlength: 10,_x000D_
        maxlength: 10,_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5,_x000D_
      }_x000D_
    },_x000D_
    messages: {_x000D_
      firstname: {_x000D_
      required: "Please enter first name",_x000D_
     },      _x000D_
     lastname: {_x000D_
      required: "Please enter last name",_x000D_
     },     _x000D_
     phone: {_x000D_
      required: "Please enter phone number",_x000D_
      digits: "Please enter valid phone number",_x000D_
      minlength: "Phone number field accept only 10 digits",_x000D_
      maxlength: "Phone number field accept only 10 digits",_x000D_
     },     _x000D_
     email: {_x000D_
      required: "Please enter email address",_x000D_
      email: "Please enter a valid email address.",_x000D_
     },_x000D_
    },_x000D_
  _x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
  .error{_x000D_
    color: red;_x000D_
  }_x000D_
  label,_x000D_
  input,_x000D_
  button {_x000D_
    border: 0;_x000D_
    margin-bottom: 3px;_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
  }_x000D_
 .common_box_body {_x000D_
    padding: 15px;_x000D_
    border: 12px solid #28BAA2;_x000D_
    border-color: #28BAA2;_x000D_
    border-radius: 15px;_x000D_
    margin-top: 10px;_x000D_
    background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
  <h2>Registration</h2>_x000D_
  <form action="#" name="registration" id="registration">_x000D_
 _x000D_
    <label for="firstname">First Name</label>_x000D_
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
 _x000D_
    <label for="lastname">Last Name</label>_x000D_
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
 _x000D_
    <label for="phone">Phone</label>_x000D_
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  _x000D_
 _x000D_
    <label for="email">Email</label>_x000D_
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
 _x000D_
    <label for="password">Password</label>_x000D_
    <input type="password" name="password" id="password" placeholder=""><br>_x000D_
 _x000D_
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
  </form>_x000D_
</div>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to prevent a click on a '#' link from jumping to top of page?

Just use

<a href="javascript:;" class="someclass">Text</a>

JQUERY

$('.someclass').click(function(e) { alert("action here"); }

postgresql - replace all instances of a string within text field

Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -

select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;