# Programs & Examples On #Spline

A spline is a sufficiently smooth polynomial function that is piecewise-defined, and possesses a high degree of smoothness at the places where the polynomial pieces connect

### how to draw smooth curve through N points using javascript HTML5 canvas?

A bit late, but for the record.

You can achieve smooth lines by using cardinal splines (aka canonical spline) to draw smooth curves that goes through the points.

I made this function for canvas - it's split into three function to increase versatility. The main wrapper function looks like this:

``````function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {

showPoints  = showPoints ? showPoints : false;

ctx.beginPath();

drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));

if (showPoints) {
ctx.stroke();
ctx.beginPath();
for(var i=0;i<ptsa.length-1;i+=2)
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);
}
}
``````

To draw a curve have an array with x, y points in the order: `x1,y1, x2,y2, ...xn,yn`.

Use it like this:

``````var myPoints = [10,10, 40,30, 100,10]; //minimum two points
var tension = 1;

drawCurve(ctx, myPoints); //default tension=0.5
drawCurve(ctx, myPoints, tension);
``````

The function above calls two sub-functions, one to calculate the smoothed points. This returns an array with new points - this is the core function which calculates the smoothed points:

``````function getCurvePoints(pts, tension, isClosed, numOfSegments) {

// use input value if provided, or use a default value
tension = (typeof tension != 'undefined') ? tension : 0.5;
isClosed = isClosed ? isClosed : false;
numOfSegments = numOfSegments ? numOfSegments : 16;

var _pts = [], res = [],    // clone array
x, y,           // our x,y coords
t1x, t2x, t1y, t2y, // tension vectors
c1, c2, c3, c4,     // cardinal points
st, t, i;       // steps based on num. of segments

// clone array so we don't change the original
//
_pts = pts.slice(0);

// The algorithm require a previous and next point to the actual point array.
// Check if we will draw closed or open curve.
// If closed, copy end points to beginning and first points to end
// If open, duplicate first points to befinning, end points to end
if (isClosed) {
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.push(pts[0]);
_pts.push(pts[1]);
}
else {
_pts.unshift(pts[1]);   //copy 1. point and insert at beginning
_pts.unshift(pts[0]);
_pts.push(pts[pts.length - 2]); //copy last point and append
_pts.push(pts[pts.length - 1]);
}

// ok, lets start..

// 1. loop goes through point array
// 2. loop goes through each segment between the 2 pts + 1e point before and after
for (i=2; i < (_pts.length - 4); i+=2) {
for (t=0; t <= numOfSegments; t++) {

// calc tension vectors
t1x = (_pts[i+2] - _pts[i-2]) * tension;
t2x = (_pts[i+4] - _pts[i]) * tension;

t1y = (_pts[i+3] - _pts[i-1]) * tension;
t2y = (_pts[i+5] - _pts[i+1]) * tension;

// calc step
st = t / numOfSegments;

// calc cardinals
c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1;
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2);
c3 =       Math.pow(st, 3)  - 2 * Math.pow(st, 2) + st;
c4 =       Math.pow(st, 3)  -     Math.pow(st, 2);

// calc x and y cords with common control vectors
x = c1 * _pts[i]    + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;
y = c1 * _pts[i+1]  + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;

//store points in array
res.push(x);
res.push(y);

}
}

return res;
}
``````

And to actually draw the points as a smoothed curve (or any other segmented lines as long as you have an x,y array):

``````function drawLines(ctx, pts) {
ctx.moveTo(pts[0], pts[1]);
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);
}
``````

_x000D_
_x000D_
``````var ctx = document.getElementById("c").getContext("2d");_x000D_
_x000D_
_x000D_
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {_x000D_
_x000D_
ctx.beginPath();_x000D_
_x000D_
drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));_x000D_
_x000D_
if (showPoints) {_x000D_
ctx.beginPath();_x000D_
for(var i=0;i<ptsa.length-1;i+=2) _x000D_
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);_x000D_
}_x000D_
_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
_x000D_
var myPoints = [10,10, 40,30, 100,10, 200, 100, 200, 50, 250, 120]; //minimum two points_x000D_
var tension = 1;_x000D_
_x000D_
drawCurve(ctx, myPoints); //default tension=0.5_x000D_
drawCurve(ctx, myPoints, tension);_x000D_
_x000D_
_x000D_
function getCurvePoints(pts, tension, isClosed, numOfSegments) {_x000D_
_x000D_
// use input value if provided, or use a default value  _x000D_
tension = (typeof tension != 'undefined') ? tension : 0.5;_x000D_
isClosed = isClosed ? isClosed : false;_x000D_
numOfSegments = numOfSegments ? numOfSegments : 16;_x000D_
_x000D_
var _pts = [], res = [], // clone array_x000D_
x, y,   // our x,y coords_x000D_
t1x, t2x, t1y, t2y, // tension vectors_x000D_
c1, c2, c3, c4,  // cardinal points_x000D_
st, t, i;  // steps based on num. of segments_x000D_
_x000D_
// clone array so we don't change the original_x000D_
//_x000D_
_pts = pts.slice(0);_x000D_
_x000D_
// The algorithm require a previous and next point to the actual point array._x000D_
// Check if we will draw closed or open curve._x000D_
// If closed, copy end points to beginning and first points to end_x000D_
// If open, duplicate first points to befinning, end points to end_x000D_
if (isClosed) {_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.push(pts[0]);_x000D_
_pts.push(pts[1]);_x000D_
}_x000D_
else {_x000D_
_pts.unshift(pts[1]); //copy 1. point and insert at beginning_x000D_
_pts.unshift(pts[0]);_x000D_
_pts.push(pts[pts.length - 2]); //copy last point and append_x000D_
_pts.push(pts[pts.length - 1]);_x000D_
}_x000D_
_x000D_
// ok, lets start.._x000D_
_x000D_
// 1. loop goes through point array_x000D_
// 2. loop goes through each segment between the 2 pts + 1e point before and after_x000D_
for (i=2; i < (_pts.length - 4); i+=2) {_x000D_
for (t=0; t <= numOfSegments; t++) {_x000D_
_x000D_
// calc tension vectors_x000D_
t1x = (_pts[i+2] - _pts[i-2]) * tension;_x000D_
t2x = (_pts[i+4] - _pts[i]) * tension;_x000D_
_x000D_
t1y = (_pts[i+3] - _pts[i-1]) * tension;_x000D_
t2y = (_pts[i+5] - _pts[i+1]) * tension;_x000D_
_x000D_
// calc step_x000D_
st = t / numOfSegments;_x000D_
_x000D_
// calc cardinals_x000D_
c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1; _x000D_
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); _x000D_
c3 =     Math.pow(st, 3) - 2 * Math.pow(st, 2) + st; _x000D_
c4 =     Math.pow(st, 3) -    Math.pow(st, 2);_x000D_
_x000D_
// calc x and y cords with common control vectors_x000D_
x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;_x000D_
y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;_x000D_
_x000D_
//store points in array_x000D_
res.push(x);_x000D_
res.push(y);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
return res;_x000D_
}_x000D_
_x000D_
function drawLines(ctx, pts) {_x000D_
ctx.moveTo(pts[0], pts[1]);_x000D_
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);_x000D_
}``````
_x000D_
``canvas { border: 1px solid red; }``
_x000D_
``<canvas id="c"><canvas>``
_x000D_
_x000D_
_x000D_

This results in this:

You can easily extend the canvas so you can call it like this instead:

``````ctx.drawCurve(myPoints);
``````

Add the following to the javascript:

``````if (CanvasRenderingContext2D != 'undefined') {
CanvasRenderingContext2D.prototype.drawCurve =
function(pts, tension, isClosed, numOfSegments, showPoints) {
drawCurve(this, pts, tension, isClosed, numOfSegments, showPoints)}
}
``````

You can find a more optimized version of this on NPM (`npm i cardinal-spline-js`) or on GitLab.

### ldap query for group members

The query should be:

``````(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))
``````

You missed & and ()

### How to draw circle by canvas in Android?

``````import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity
{

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}

public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}

@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
``````

Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using

``````canvas.translate(getWidth()/2f,getHeight()/2f);
``````

http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o

http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html

### rails bundle clean

If you're using RVM you may use `rvm gemset empty` for the current gemset - this command will remove all gems installed to the current gemset (gemset itself will stay in place). Then run `bundle install` in order to install actual versions of gems. Also be sure that you do not delete such general gems as rake, bundler and so on during `rvm gemset empty` (if it is the case then install them manually via `gem install` prior to `bundle install`).

### Converting a value to 2 decimal places within jQuery

you can use just javascript for it

``````var total =10.8
(total).toFixed(2); 10.80

``````

### How to Disable landscape mode in Android?

`````` android:screenOrientation="portrait"
``````

### Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

``````#container {
height:100%;
width:100%;
overflow:hidden;
/* for IE */
zoom:1;
}
``````

### Inserting image into IPython notebook markdown

I am using ipython 2.0, so just two line.

``````from IPython.display import Image
Image(filename='output1.png')
``````

### What is the difference between WCF and WPF?

• WPF is your FrontEnd (presentation: .htm, .xaml & .css, ..)
• WCF is your BackEnd app (services that involve server connections to acquire data for you to deliver to the FrontEnd to present). You can write WCF for RESTful model.
• WebAPI is for building services of RESTful model for 4.+ frameworks.

### What is the difference between Sublime text and Github's Atom

One major difference is the support of "Indic Fonts" aka South Asian Scripts (including Southeast Asian languages such as Khmer, Lao, Myanmar and Thai). Also, there is much better support for East Asian languages (Chinese, Japanese, Korean). These are known bugs (actually the most highly rated bugs) that have been going on for years (thought it appears East Asian language support used to work better but have now become difficult to use):

### Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.

# Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

``````torch.save(the_model.state_dict(), PATH)
``````

Then later:

``````the_model = TheModelClass(*args, **kwargs)
``````

The second saves and loads the entire model:

``````torch.save(the_model, PATH)
``````

Then later:

``````the_model = torch.load(PATH)
``````

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

# Drag-And-Drop

Easiest way for a lazy Mac user like me: Drag-and-drop the `startup.sh` file from the Finder to the Terminal window and press Return.

To shutdown Tomcat, do the same with `shutdown.sh`.

You can delete all the `.bat` files as they are only for a Windows PC, of no use on a Mac to other Unix computer. I delete them as it makes it easier to read that folder's listing.

# File Permissions

I find that a fresh Tomcat download will not run on my Mac because of file permission restrictions throwing errors during startup. I use the `BatChmod` app which wraps a GUI around the equivelant Unix commands to reset file permissions.

# Port-Forwarding

Unix systems protect access to ports numbered under 1024. So if you want to use port 80 with Tomcat you will need to learn how to do "port-forwarding" to forward incoming requests to port 8080 where Tomcat listens by default. To do port-forwarding, you issue commands to the packet-filtering (firewall) app built into Mac OS X (and BSD). In the old days we used `ipfw`. In Mac OS X 10.7 (Lion) and later Apple is moving to a newer tool, `pf`.

### .NET Console Application Exit Event

The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.

Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)

Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...

``````
Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean

Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean

Public Enum CtrlTypes
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT
CTRL_CLOSE_EVENT
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT
End Enum

Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function

Public Sub Main()
.
.
.
.
.
End Sub
``````

This setup seems to work out perfectly. Here is a link to some C# code for the same thing.

I created my own Gem, but I did it in a directory that is not in my load path:

``````\$ pwd
/Users/myuser/projects
\$ gem build my_gem/my_gem.gemspec
``````

Then I ran `irb` and tried to load the Gem:

``````> require 'my_gem'
``````

I used the global variable \$: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path `\$:`. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

``````\$: << "/Users/myuser/projects/my_gem/lib"
``````

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

``````> require 'my_gem'
=> true
``````

Now if you want to install the gem in RVM path, then you would need to run:

``````\$ gem install my_gem
``````

But it will need to be in a repository like rubygems.org.

``````\$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem
``````

### How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

``````    public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this,  mDrawerLayout, mToolbar,
);
mDrawerLayout.setDrawerListener(mDrawerToggle);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
``````

and all the other things will remain same...

For those who are having problem `Drawerlayout` overlaying toolbar

add `android:layout_marginTop="?attr/actionBarSize"` to root layout of drawer content

### How do I import .sql files into SQLite 3?

Alternatively, you can do this from a Windows commandline prompt/batch file:

``````sqlite3.exe DB.db ".read db.sql"
``````

Where DB.db is the database file, and db.sql is the SQL file to run/import.

### @HostBinding and @HostListener: what do they do and what are they for?

One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...

``````@HostBinding('attr.something')
get something() {
return this.somethingElse;
}
``````

It works, because it is a `get` accessor. You couldn't use a function equivalent:

``````@HostBinding('attr.something')
something() {
return this.somethingElse;
}
``````

Otherwise, the benefit of using `@HostBinding` is it assures change detection is run when the bound value changes.

### How to disable an Android button?

Did you try this?

``````myButton.setEnabled(false);
``````

Update: Thanks to Gwen. Almost forgot that `android:clickable` can be set in your XML layout to determine whether a button can be clickable or not.

### How can I list ALL DNS records?

What you want is called a zone transfer. You can request a zone transfer using `dig -t axfr`.

A zone is a domain and all of the domains below it that are not delegated to another server.

Note that zone transfers are not always supported. They're not used in normal lookup, only in replicating DNS data between servers; but there are other protocols that can be used for that (such as rsync over ssh), there may be a security risk from exposing names, and zone transfer responses cost more to generate and send than usual DNS lookups.

### Iterate two Lists or Arrays with one ForEach statement in C#

You could also simply use a local integer variable if the lists have the same length:

``````List<classA> listA = fillListA();
List<classB> listB = fillListB();

var i = 0;
foreach(var itemA in listA)
{
Console.WriteLine(itemA  + listB[i++]);
}
``````

# whithout librairies: using Array.prototype.reduce()

``````const args = process.argv.slice(2).reduce((acc, arg) => {

let [k, v = true] = arg.split('=')
acc[k] = v
return acc

}, {})
``````

for this command `node index.js count=2 print debug=false msg=hi`

``````console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }
``````

#### also,

we can change

``````    let [k, v = true] = arg.split('=')
acc[k] = v
``````

by (much longer)

``````    let [k, v] = arg.split('=')
acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
``````

to auto parse Boolean & Number

``````console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
``````

### design a stack such that getMinimum( ) should be O(1)

``````class FastStack {

private static class StackNode {
private Integer data;
private StackNode nextMin;

public StackNode(Integer data) {
this.data = data;
}

public Integer getData() {
return data;
}

public void setData(Integer data) {
this.data = data;
}

public StackNode getNextMin() {
return nextMin;
}

public void setNextMin(StackNode nextMin) {
this.nextMin = nextMin;
}

}

private StackNode currentMin = null;

public void push(Integer item) {
StackNode node = new StackNode(item);
if (currentMin == null) {
currentMin = node;
node.setNextMin(null);
} else if (item < currentMin.getData()) {
StackNode oldMinNode = currentMin;
node.setNextMin(oldMinNode);
currentMin = node;
}

}

public Integer pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
StackNode node = stack.peek();
if (currentMin == node) {
currentMin = node.getNextMin();
}
stack.removeFirst();
return node.getData();
}

public Integer getMinimum() {
if (stack.isEmpty()) {
throw new NoSuchElementException("Stack is empty");
}
return currentMin.getData();
}
}
``````

### Using a bitmask in C#

Easy Way:

``````[Flags]
public enum MyFlags {
None = 0,
Susan = 1,
Alice = 2,
Bob = 4,
Eve = 8
}
``````

To set the flags use logical "or" operator `|`:

``````MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;
``````

And to check if a flag is included use `HasFlag`:

``````if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}
``````

### C# Convert List<string> to Dictionary<string, string>

EDIT

another way to deal with duplicate is you can do like this

``````var dic = slist.Select((element, index)=> new{element,index} )
.ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);
``````

or

easy way to do is

``````var res = list.ToDictionary(str => str, str=> str);
``````

but make sure that there is no string is repeating...again otherewise above code will not work for you

if there is string is repeating than its better to do like this

``````Dictionary<string,string> dic= new Dictionary<string,string> ();

foreach(string s in Stringlist)
{
if(!dic.ContainsKey(s))
{
}
}
``````

### jQuery: find element by text

You can use the `:contains` selector to get elements based on their content.

Demo here

_x000D_
_x000D_
``\$('div:contains("test")').css('background-color', 'red');``
_x000D_
``````<div>This is a test</div>_x000D_
<div>Another Div</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>``````
_x000D_
_x000D_
_x000D_

### Setting the User-Agent header for a WebClient request

You can also use that:

``````client.Headers.Add(HttpRequestHeader.UserAgent, "My app.");
``````

### How to make an Asynchronous Method return a value?

Perhaps you can try to BeginInvoke a delegate pointing to your method like so:

``````

delegate string SynchOperation(string value);

class Program
{
static void Main(string[] args)
{
BeginTheSynchronousOperation(CallbackOperation, "my value");
}

static void BeginTheSynchronousOperation(AsyncCallback callback, string value)
{
SynchOperation op = new SynchOperation(SynchronousOperation);
op.BeginInvoke(value, callback, op);
}

static string SynchronousOperation(string value)
{
return value;
}

static void CallbackOperation(IAsyncResult result)
{
var ar = result.AsyncState as SynchOperation;
// end invoke and get value
var returned = ar.EndInvoke(result);

Console.WriteLine(returned);
}
}
```
```

Then use the value in the method you sent as AsyncCallback to continue..

### VBScript How can I Format Date?

'for unique file names I use

``````Dim ts, logfile, thisScript

thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension

ts = timeStamp
logfile = thisScript & "_" & ts

' ======
Function timeStamp()
timeStamp = Year(Now) & "-" & _
Right("0" & Month(Now),2)  & "-" & _
Right("0" & Day(Now),2)  & "_" & _
Right("0" & Hour(Now),2) & _
Right("0" & Minute(Now),2) '    '& _    Right("0" & Second(Now),2)
End Function
' ======
``````

### Valid characters in a Java class name

Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:

http://www.oracle.com/technetwork/java/codeconventions-135099.html

### Delete all documents from index/type without deleting type

Elasticsearch 2.3 the option

``````    action.destructive_requires_name: true
``````

in elasticsearch.yml do the trip

``````    curl -XDELETE http://localhost:9200/twitter/tweet
``````

### What's the advantage of a Java enum versus a class with public static final fields?

The first benefit of enums, as you have already noticed, is syntax simplicity. But the main point of enums is to provide a well-known set of constants which, by default, form a range and help to perform more comprehensive code analysis through type & value safety checks.

Those attributes of enums help both a programmer and a compiler. For example, let's say you see a function that accepts an integer. What that integer could mean? What kind of values can you pass in? You don't really know right away. But if you see a function that accepts enum, you know very well all possible values you can pass in.

For the compiler, enums help to determine a range of values and unless you assign special values to enum members, they are well ranges from 0 and up. This helps to automatically track down errors in the code through type safety checks and more. For example, compiler may warn you that you don't handle all possible enum values in your switch statement (i.e. when you don't have `default` case and handle only one out of N enum values). It also warns you when you convert an arbitrary integer into enum because enum's range of values is less than integer's and that in turn may trigger errors in the function that doesn't really accept an integer. Also, generating a jump table for the switch becomes easier when values are from 0 and up.

This is not only true for Java, but for other languages with a strict type-checking as well. C, C++, D, C# are good examples.

### android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

@nmr also check the ownership and groups on the sqlite file itself... I'd copied my database in from /sdcard as root so had to change the permissions..

``````-rw-rw---- root     root       180224 2014-05-05 11:06 test.sqlite
``````

should be..

``````-rw-rw---- u0_a80   u0_a80     180224 2014-05-05 11:06 test.sqlite
``````

Used the following commands to set the correct ownership and group. The `u0_a80` I got from `ls -al` on other files in the directory

``````chown u0_a80 test.sqlite
chgrp u0_a80 test.sqlite
``````

### How can I initialize base class member variables in derived class constructor?

Aggregate classes, like A in your example(*), must have their members public, and have no user-defined constructors. They are intialized with initializer list, e.g. `A a {0,0};` or in your case `B() : A({0,0}){}`. The members of base aggregate class cannot be individually initialized in the constructor of the derived class.

(*) To be precise, as it was correctly mentioned, original `class A` is not an aggregate due to private non-static members

### What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

### Communication between multiple docker-compose projects

You just need to make sure that the containers you want to talk to each other are on the same network. Networks are a first-class docker construct, and not specific to compose.

``````# front/docker-compose.yml
version: '2'
services:
front:
...
networks:
- some-net
networks:
some-net:
driver: bridge
``````

...

``````# api/docker-compose.yml
version: '2'
services:
api:
...
networks:
- front_some-net
networks:
front_some-net:
external: true
``````

Note: Your app’s network is given a name based on the “project name”, which is based on the name of the directory it lives in, in this case a prefix `front_` was added

They can then talk to each other using the service name. From `front` you can do `ping api` and vice versa.

### Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

``````RepeatingOperation = function(op, yieldEveryIteration) {

//keeps count of how many times we have run heavytask()
//before we need to temporally check back with the browser.
var count = 0;

this.step = function() {

//Each time we run heavytask(), increment the count. When count
//is bigger than the yieldEveryIteration limit, pass control back
//to browser and instruct the browser to immediately call op() so
//we can pick up where we left off.  Repeat until we are done.
if (++count >= yieldEveryIteration) {
count = 0;

//pass control back to the browser, and in 1 millisecond,
//have the browser call the op() function.
setTimeout(function() { op(); }, 1, [])

//The following return statement halts this thread, it gives
//the browser a sigh of relief, your long-running javascript
//loop has ended (even though technically we havn't yet).
//The browser decides there is no need to alarm the user of
//an unresponsive javascript process.
return;
}
op();
};
};
``````

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

``````process10000HeavyTasks = function() {
var len = 10000;
for (var i = len - 1; i >= 0; i--) {
//an 'unresponsive script' dialog appears.
//If heavytask() is run more than 20 times in one
//javascript thread, the browser informs the user that
//an unresponsive script needs to be dealt with.

//This is where we need to terminate this long running
//thread, instruct the browser not to panic on an unresponsive
//script, and tell it to call us right back to pick up
//where we left off.
}
}
``````

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

``````process10000HeavyTasks = function() {

var global_i = 10000; //initialize your 'for loop stepper' (i) here.

var repeater = new this.RepeatingOperation(function() {

if (--global_i >= 0){     //Your for loop conditional goes here.
repeater.step();        //while we still have items to process,
//run the next iteration of the loop.
}
else {
alert("we are done");  //when this line runs, the for loop is complete.
}
}, 10);                   //10 means process 10 heavytask(), then
//yield back to the browser, and have the
//browser call us right back.

repeater.step();          //this command kicks off the recursive closure.

};
``````

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

### Check if page gets reloaded or refreshed in JavaScript

First step is to check `sessionStorage` for some pre-defined value and if it exists alert user:

``````if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
``````

Second step is to set `sessionStorage` to some value (for example `true`):

``````sessionStorage.setItem("is_reloaded", true);
``````

Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.

Send the following headers before outputting the file:

``````header("Content-Disposition: attachment; filename=\"" . basename(\$File) . "\"");
``````

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

### How to pass a value from one jsp to another jsp page?

Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'

``````<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
``````

// Code to be written in 'display.jsp'

`````` <% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
``````

If you want to use these variables of servlets in javascript then simply write

``````<script type="text/javascript">
var a=<%=u1%>;
</script>
``````

Hope it helps :)

### How to use Greek symbols in ggplot2?

Here is a link to an excellent wiki that explains how to put greek symbols in ggplot2. In summary, here is what you do to obtain greek symbols

1. Text Labels: Use `parse = T` inside `geom_text` or `annotate`.
2. Axis Labels: Use `expression(alpha)` to get greek alpha.
3. Facet Labels: Use `labeller = label_parsed` inside `facet`.
4. Legend Labels: Use `bquote(alpha == .(value))` in legend label.

You can see detailed usage of these options in the link

EDIT. The objective of using greek symbols along the tick marks can be achieved as follows

``````require(ggplot2);
data(tips);
p0 = qplot(sex, data = tips, geom = 'bar');
p1 = p0 + scale_x_discrete(labels = c('Female' = expression(alpha),
'Male'   = expression(beta)));
print(p1);
``````

For complete documentation on the various symbols that are available when doing this and how to use them, see `?plotmath`.

### Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

``````Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
``````

If you want to include the activecell in the range that gets copied, you don't need the offset:

``````Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
``````

Note that you don't need to select before copying.

### Stop an input field in a form from being submitted

``````<form action="YOUR_URL" method="post" accept-charset="utf-8" onsubmit="return validateRegisterForm();">
``````

And the script will be like this:

``````        function validateRegisterForm(){
if(SOMETHING IS WRONG)
{
event.preventDefault();
return false;

}else{
return true;
}
}
``````

This works for me everytime :)

### How to change UINavigationBar background color from the AppDelegate

The colour code is the issue here. Instead of using 195/255, use 0.7647 or 195.f/255.f The problem is converting the float is not working properly. Try using exact float value.

### Dynamically create checkbox with JQuery from text input

``````<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
\$('#btnSave').click(function() {
});
});

var container = \$('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;

\$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
\$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
``````

### How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

``````window.onload = function() {
yourFunction(param1, param2);
};
``````

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

### how to get the cookies from a php curl into a variable

The accepted answer seems like it will search through the entire response message. This could give you false matches for cookie headers if the word "Set-Cookie" is at the beginning of a line. While it should be fine in most cases. The safer way might be to read through the message from the beginning until the first empty line which indicates the end of the message headers. This is just an alternate solution that should look for the first blank line and then use preg_grep on those lines only to find "Set-Cookie".

``````    curl_setopt(\$ch, CURLOPT_HEADER, 1);
//Return everything
\$res = curl_exec(\$ch);
//Split into lines
\$lines = explode("\n", \$res);
\$body = "";
foreach(\$lines as \$num => \$line){
\$l = str_replace("\r", "", \$line);
//Empty line indicates the start of the message body and end of headers
if(trim(\$l) == ""){
\$body = \$lines[\$num + 1];
break;
}
}
``````

Here is how I got this working

_x000D_
_x000D_
``````\$.ajax({
url: '<URL_TO_FILE>',
success: function(data) {
var blob=new Blob([data]);
}
});``````
_x000D_
``<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>``
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
``````\$.ajax({
url: '<URL_TO_FILE>',
});``````
_x000D_
_x000D_
_x000D_

### Configure Log4net to write to multiple files

``````<log4net>
<appender name="File1Appender" type="log4net.Appender.FileAppender">
<file value="log-file-1.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<appender name="File2Appender" type="log4net.Appender.FileAppender">
<file value="log-file-2.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>

<root>
<level value="DEBUG" />
<appender-ref ref="File1Appender" />
<appender-ref ref="File2Appender" />
</root>
</log4net>
``````

### Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

1. Like you installed older version of PHP do the same with Apache. I picked version 2.0.63 and then I was able to run WAMP Server with PHP 5.2.9 with no problems.

2. I also read that it's problem with 64-bit version of WAMP.

### What is a software framework?

The summary at Wikipedia (Software Framework) (first google hit btw) explains it quite well:

A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.

Software frameworks have these distinguishing features that separate them from libraries or normal user applications:

1. inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
2. default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
3. extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
4. non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.

You may "need" it because it may provide you with a great shortcut when developing applications, since it contains lots of already written and tested functionality. The reason is quite similar to the reason we use software libraries.

### Streaming via RTSP or RTP in HTML5

With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)

The first to have a doc on this should notify us ;)

### How to submit a form using Enter key in react.js?

Change `<button type="button"` to `<button type="submit"`. Remove the `onClick`. Instead do `<form className="commentForm" onSubmit={this.onFormSubmit}>`. This should catch clicking the button and pressing the return key.

``````onFormSubmit = e => {
e.preventDefault();
const { name, email } = this.state;
// send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
...
<button type="submit">Submit</button>
</form>
``````

### How to completely DISABLE any MOUSE CLICK

To disable all mouse click

``````var event = \$(document).click(function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});

// disable right click
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
``````

to enable it again:

``````\$(document).unbind('click');
``````

### A hex viewer / editor plugin for Notepad++?

Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.

I used to use the Notepad++ plugin, but not anymore.

### How do I grep recursively?

I now always use (even on Windows with GoW -- Gnu on Windows):

``````grep --include="*.xxx" -nRHI "my Text to grep" *
``````

That includes the following options:

``````--include=PATTERN
``````

Recurse in directories only searching file matching `PATTERN`.

``````-n, --line-number
``````

Prefix each line of output with the line number within its input file.

(Note: phuclv adds in the comments that `-n` decreases performance a lot so, so you might want to skip that option)

``````-R, -r, --recursive
``````

Read all files under each directory, recursively; this is equivalent to the `-d recurse` option.

``````-H, --with-filename
``````

Print the filename for each match.

``````-I
``````

Process a binary file as if it did not contain matching data;
this is equivalent to the `--binary-files=without-match` option.

And I can add '`i`' (`-nRHIi`), if I want case-insensitive results.

I can get:

``````/home/vonc/gitpoc/passenger/gitlist/github #grep --include="*.php" -nRHI "hidden" *
src/GitList/Application.php:43:            'git.hidden'      => \$config->get('git', 'hidden') ? \$config->get('git', 'hidden') : array(),
src/GitList/Provider/GitServiceProvider.php:21:            \$options['hidden'] = \$app['git.hidden'];
tests/InterfaceTest.php:32:        \$options['hidden'] = array(self::\$tmpdir . '/hiddenrepo');
vendor/klaussilveira/gitter/lib/Gitter/Client.php:20:    protected \$hidden;
vendor/klaussilveira/gitter/lib/Gitter/Client.php:170:     * Get hidden repository list
vendor/klaussilveira/gitter/lib/Gitter/Client.php:176:        return \$this->hidden;
...
``````

### How do I initialize an empty array in C#?

Try this:

``````string[] a = new string[] { };
``````

### Load a HTML page within another HTML page

You can use jQuery

``````<html>
<script src="jquery.js"></script>
<script>
\$(function(){
});
</script>

<body>
<div id="divId" style="display:none;"></div>
</body>
</html>
``````

on click event you can make it display block .

### How to get current route in Symfony 2?

if you want to get route name in your controller than you have to inject the request (instead of getting from container due to Symfony UPGRADE and than call get('_route').

``````public function indexAction(Request \$request)
{
\$routeName = \$request->get('_route');
}
``````

if you want to get route name in twig than you have to get it like

``````{{ app.request.attributes.get('_route') }}
``````

### Round float to x decimals?

I coded a function (used in Django project for DecimalField) but it can be used in Python project :

This code :

• Manage integers digits to avoid too high number
• Manage decimals digits to avoid too low number
• Manage signed and unsigned numbers

Code with tests :

``````def convert_decimal_to_right(value, max_digits, decimal_places, signed=True):

integer_digits = max_digits - decimal_places
max_value = float((10**integer_digits)-float(float(1)/float((10**decimal_places))))

if signed:
min_value = max_value*-1
else:
min_value = 0

if value > max_value:
value = max_value

if value < min_value:
value = min_value

return round(value, decimal_places)

value = 12.12345
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.12

value = 12.126
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.13

value = 1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : 99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : -99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2, signed = False)
# nb : 0

value = 12.123
nb = convert_decimal_to_right(value, 8, 4)
# nb : 12.123
``````

### Return list from async/await method

In addition to @takemyoxygen's answer the convention of having a function name that ends in `Async` is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call `Task.Run`. If that is all the code that is in your function, it will be better to remove it completely and simply have:

``````List<Item> list = await Task.Run(() => manager.GetList());
``````

### Spring RestTemplate GET with parameters

If your url is `http://localhost:8080/context path?msisdn={msisdn}&email={email}`

then

``````Map<String,Object> queryParams=new HashMap<>();
``````

works for resttemplate exchange method as described by you

### How to run VBScript from command line without Cscript/Wscript

I am wondering why you cannot put this in a batch file. Example:

``````cd D:\VBS\
WSCript Converter.vbs
``````

Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.

### How to enable php7 module in apache?

First, disable the `php5` module:

``````a2dismod php5
``````

then, enable the `php7` module:

``````a2enmod php7.0
``````

``````service apache2 restart
``````

#### Update 2018-09-04

wrt the comment, you need to specify exact installed version.

### Import CSV to SQLite

before .import command, type ".mode csv"

### How to create virtual column using MySQL SELECT?

Something like:

``````SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
``````

This allows you to make operations and show it as columns.

EDIT:

you can also use joins and show operations as columns:

``````SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id
``````

### jQuery - Trigger event when an element is removed from the DOM

I like mtkopone's answer using jQuery special events, but note that it doesn't work a) when elements are detached instead of removed or b) when some old non-jquery libraries use innerHTML to destroy your elements

### Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

This work for me :

``````sudo service redis-server start
``````

### Trying to Validate URL Using JavaScript

If you're looking for a more reliable regex, check out RegexLib. Here's the page you'd probably be interested in:

http://regexlib.com/Search.aspx?k=url

As for the error messages showing while the person is still typing, change the event from `keydown` to `blur` and then it will only check once the person moves to the next element.

### WPF checkbox binding

Should be easier than that. Just use:

``````<Checkbox IsChecked="{Binding Path=myVar, UpdateSourceTrigger=PropertyChanged}" />
``````

### javascript: get a function's variable's value within another function

you need a return statement in your first function.

``````function first(){
var nameContent = document.getElementById('full_name').value;
return nameContent;
}
``````

and then in your second function can be:

``````function second(){
}
``````

### Launch programs whose path contains spaces

``````Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("firefox")
Set objShell = Nothing
``````

### Find a class somewhere inside dozens of JAR files?

A bit late to the party, but nevertheless...

I've been using JarBrowser to find in which jar a particular class is present. It's got an easy to use GUI which allows you to browse through the contents of all the jars in the selected path.

### Processing \$http response in service

Because it is asynchronous, the `\$scope` is getting the data before the ajax call is complete.

You could use `\$q` in your service to create `promise` and give it back to controller, and controller obtain the result within `then()` call against `promise`.

``````app.factory('myService', function(\$http, \$q) {
var deffered = \$q.defer();
var data = [];
var myService = {};

myService.async = function() {
\$http.get('test.json')
.success(function (d) {
data = d;
console.log(d);
deffered.resolve();
});
return deffered.promise;
};
myService.data = function() { return data; };

return myService;
});
``````

``````app.controller('MainCtrl', function( myService,\$scope) {
myService.async().then(function() {
\$scope.data = myService.data();
});
});
``````

### How to dynamically load a Python class

``````def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
``````

### Relative imports in Python 3

I was getting this ImportError: attempted relative import with no known parent package

In my program I was using the file from current path for importing its function.

``````from .filename import function
``````

Then I modified the current path (Dot) with package name. Which resolved my issue.

``````from package_name.filename import function
``````

I hope the above answer helps you.

### T-SQL Cast versus Convert

Something no one seems to have noted yet is readability. Having…

``````CONVERT(SomeType,
SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
)
``````

…may be easier to understand than…

``````CAST(SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
AS SomeType
)
``````

### How to get a path to a resource in a Java JAR file

Inside your ressources folder (java/main/resources) of your jar add your file (we assume that you have added an xml file named imports.xml), after that you inject `ResourceLoader` if you use spring like bellow

``````@Autowired
``````

inside tour function write the bellow code in order to load file:

``````    Resource resource = resourceLoader.getResource("classpath:imports.xml");
try{
File file;
file = resource.getFile();//will load the file
...
}catch(IOException e){e.printStackTrace();}
``````

### Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

`````` <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>
``````

checkit out

Angular 2 - Setting selected value on dropdown list

### Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

Sample Code: To set Footer text programatically

``````    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
``````

UPDATED CODE:

``````  decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}

if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}

}
``````

In .aspx Page

`````` <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />

</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
``````

My Blog - Asp.net Gridview Article

### Validating IPv4 addresses with regexp

My [extended] approach ? regexp for space-separated IP addresses:

`((((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\\.(?=\\d)|(?!\\d))){4})( (?!\$)|\$))+`

### chrome : how to turn off user agent stylesheet settings?

1. Open Chrome dev tools
2. Click gear icon on bottom right
3. In General section, check or uncheck "Show user agent styles".

### CSS horizontal scroll

check this link here i change display:inline-block http://cssdesk.com/gUGBH

### CSS image resize percentage of itself?

Although it does not answer the question directly, one way to scale images is relative to the size (especially width) of the viewport, which is mostly the use case for responsive design. No wrapper elements needed.

_x000D_
_x000D_
``````img {
width: 50vw;
}``````
_x000D_
``<img src="" />``
_x000D_
_x000D_
_x000D_

### How to insert a file in MySQL database?

The BLOB datatype is best for storing files.

### How to use jQuery to get the current value of a file input field

I think it should be

`````` \$('#fileinput').val();
``````

### What techniques can be used to speed up C++ compilation times?

Use

``````#pragma once
``````

at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.

### How to detect orientation change?

In Objective C

``````-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
``````

In swift

``````func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
``````

Override this method to detect the orientation change.

### What are Maven goals and phases and what is their difference?

The chosen answer is great, but still I would like to add something small to the topic. An illustration.

It clearly demonstrates how the different phases binded to different plugins and the goals that those plugins expose.

So, let's examine a case of running something like `mvn compile`:

• It's a phase which execute the compiler plugin with compile goal
• Compiler plugin got different goals. For `mvn compile` it's mapped to a specific goal, the compile goal.
• It's the same as running `mvn compiler:compile`

Therefore, phase is made up of plugin goals.

### How to get the selected item of a combo box to a string variable in c#

Try this:

``````string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
``````

I'm going to give you an example of how I read REST headers for my controllers. My controllers only accept application/json as a request type if I have data that needs to be read. I suspect that your problem is that you have an application/octet-stream that Spring doesn't know how to handle.

Normally my controllers look like this:

``````@Controller
public class FooController {
@Autowired
private DataService dataService;

@RequestMapping(value="/foo/", method = RequestMethod.GET)
@ResponseBody
return ResponseEntity.newInstance(dataService.getData(dataId);
}
``````

Now there is a lot of code doing stuff in the background here so I will break it down for you.

ResponseEntity is a custom object that every controller returns. It contains a static factory allowing the creation of new instances. My Data Service is a standard service class.

The magic happens behind the scenes, because you are working with JSON, you need to tell Spring to use Jackson to map HttpRequest objects so that it knows what you are dealing with.

You do this by specifying this inside your `<mvc:annotation-driven>` block of your config

``````<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
``````

ObjectMapper is simply an extension of `com.fasterxml.jackson.databind.ObjectMapper` and is what Jackson uses to actually map your request from JSON into an object.

I suspect you are getting your exception because you haven't specified a mapper that can read an Octet-Stream into an object, or something that Spring can handle. If you are trying to do a file upload, that is something else entirely.

So my request that gets sent to my controller looks something like this simply has an extra header called `dataId`.

If you wanted to change that to a request parameter and use `@RequestParam String dataId` to read the ID out of the request your request would look similar to this:

``````contactId : {"fooId"}
``````

This request parameter can be as complex as you like. You can serialize an entire object into JSON, send it as a request parameter and Spring will serialize it (using Jackson) back into a Java Object ready for you to use.

Example In Controller:

``````@RequestMapping(value = "/penguin Details/", method = RequestMethod.GET)
@ResponseBody
public DataProcessingResponseDTO<Pengin> getPenguinDetailsFromList(
@RequestParam DataProcessingRequestDTO jsonPenguinRequestDTO)
``````

Request Sent:

``````jsonPengiunRequestDTO: {
"draw": 1,
"columns": [
{
"data": {
},
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
},
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "customerCampaignId",
},
"name": "customerCampaignId",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "penguinId",
},
"name": "penguinId",
"searchable": false,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "validpenguin",
},
"name": "validpenguin",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "",
},
"name": "",
"searchable": false,
"orderable": false,
"search": {
"value": "",
"regex": false
}
}
],
"order": [
{
"column": 0,
"dir": "asc"
}
],
"start": 0,
"length": 10,
"search": {
"value": "",
"regex": false
},
"objectId": "30"
}
``````

which gets automatically serialized back into an DataProcessingRequestDTO object before being given to the controller ready for me to use.

As you can see, this is quite powerful allowing you to serialize your data from JSON to an object without having to write a single line of code. You can do this for `@RequestParam` and `@RequestBody` which allows you to access JSON inside your parameters or request body respectively.

Now that you have a concrete example to go off, you shouldn't have any problems once you change your request type to `application/json`.

### ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

### SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

``````select Subject,
CONVERT(varchar,DeliveryDate,101) as DeliveryDate
where MerchantId =@MerchantID
``````

### Black transparent overlay on image hover with only CSS?

You were close. This will work:

``````.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
``````

You needed to put the `:hover` on image, and make the `.overlay` cover the whole image by adding `right:0;` and `bottom:0`.

jsfiddle: http://jsfiddle.net/Zf5am/569/

### How can I disable a button in a jQuery dialog from a function?

Here is my enableOk function for a jQuery dialog:

``````function enableOk(enable)
{
var dlgFirstButton = \$('.ui-dialog-buttonpane').find('button:first');

if (enable) {
dlgFirstButton.attr('disabled', '');
dlgFirstButton.removeClass('ui-state-disabled');
} else {
dlgFirstButton.attr('disabled', 'disabled');
}
}
``````

The "first" button is the one furthest to the right. You both disable the button and set the dialog's disabled class, for the proper visual effect.

### How to create a multiline UITextfield?

Use `textView` instead then conform with its delegate, call the `textViewDidChange` method inside of that method call `tableView.beginUpdates()` and `tableView.endUpdates()` and don't forget to set `rowHeight` and `estimatedRowHeight` to `UITableView.automaticDimension`.

### Calling a php function by onclick event

probably the `onclick` handler should read `onclick='hello();'` instead of `onclick=hello();`

### Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

#### 9.32 alpha 2013-12-01

• Improved support for file pathnames longer than 260 characters.

#### 4.44 beta 2007-01-20

• 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

# How to make a simple Android popup window

This is a fuller example. It is a supplemental answer that deals with creating a popup window in general and not necessarily the specific details of the OP's problem. (The OP asks for a cancel button, but this is not necessary because the user can click anywhere on the screen to cancel it.) It will look like the following image.

#### Make a layout for the popup window

Add a layout file to `res/layout` that defines what the popup window will look like.

popup_window.xml

``````<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#62def8">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:textSize="22sp"
android:text="This is a popup window."/>

</RelativeLayout>
``````

#### Inflate and show the popup window

Here is the code for the main activity of our example. Whenever the button is clicked, the popup window is inflated and shown over the activity. Touching anywhere on the screen dismisses the popup window.

MainActivity.java

``````public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void onButtonShowPopupWindowClick(View view) {

// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);

// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

// show the popup window
// which view you pass in doesn't matter, it is only used for the window tolken
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
}
``````

That's it. You're finished.

# Going on

Check out how gravity values effect PopupWindow.

#### Further study

These were also helpful in learning how to make a popup window:

### Copy tables from one database to another in SQL Server

If it’s one table only then all you need to do is

• Script table definition
• Create new table in another database
• Update rules, indexes, permissions and such
• Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

### Unit Testing: DateTime.Now

Moles:

``````[Test]
public void TestOfDateTime()
{
var firstValue = DateTime.Now;
MDateTime.NowGet = () => new DateTime(2000,1,1);
var secondValue = DateTime.Now;
Assert(firstValue > secondValue); // would be false if 'moleing' failed
}
``````

Disclaimer - I work on Moles

### Laravel Request::all() Should Not Be Called Statically

use the `request()` helper instead. You don't have to worry about `use` statements and thus this sort of problem wont happen again.

``````\$input = request()->all();
``````

simple

### Simulator or Emulator? What is the difference?

If a flight-simulator could transport you from A to B then it would be a flight-emulator.

An emulator can replace the original for real use.
A Virtual PC emulates a PC.

A simulator is a model for study and analysis.

An emulator will always have to operate close to real-time. For a simulator that is not always the case. A geological simulation could do 1000 years/second or more.

### Can two or more people edit an Excel document at the same time?

Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.

### Set background color in PHP?

just insert the following line and use any color you like

``````    echo "<body style='background-color:pink'>";
``````

### Mipmap drawables for icons

``````res/
mipmap-mdpi/ic_launcher.png (48x48 pixels)
mipmap-hdpi/ic_launcher.png (72x72)
mipmap-xhdpi/ic_launcher.png (96x96)
mipmap-xxhdpi/ic_launcher.png (144x144)
mipmap-xxxhdpi/ic_launcher.png (192x192)
``````

MipMap for app icon for launcher

https://androidbycode.wordpress.com/2015/02/14/goodbye-launcher-drawables-hello-mipmaps/

### how do I check in bash whether a file was created more than x time ago?

I always liked using `date -r /the/file +%s` to find its age.

You can also do `touch --date '2015-10-10 9:55' /tmp/file` to get extremely fine-grained time on an arbitrary date/time.

### Difference between DOM parentNode and parentElement

`parentElement` is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as `parentNode`. The only difference comes when a node's `parentNode` is not an element. If so, `parentElement` is `null`.

As an example:

``````document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false
``````

Since the `<html>` element (`document.documentElement`) doesn't have a parent that is an element, `parentElement` is `null`. (There are other, more unlikely, cases where `parentElement` could be `null`, but you'll probably never come across them.)

### Could not find any resources appropriate for the specified culture or the neutral culture

One approach would be to put the shared classes/resources in a separate class library project and refer them in both the web sites.

### Preventing HTML and Script injections in Javascript

``````myDiv.textContent = arbitraryHtmlString
``````

as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.

### Multi-line strings in PHP

Maybe try ".=" indead of "="?

``````\$xml="l";
\$xml.="vv";
``````

will give you "lvv";

### Select values of checkbox group with jQuery

I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:

``````("input[@name='user_group[]']").each( function() {
});
``````

Of course a better selector is available:

``````\$(':checkbox')
``````

### jQuery text() and newlines

I would suggest to work with the `someElem` element directly, as replacements with `.html()` would replace other HTML tags within the string as well.

Here is my function:

``````function nl2br(el) {
var lines = \$(el).text().split(/\n/);
\$(el).empty();
for (var i = 0 ; i < lines.length ; i++) {
if (i > 0) \$(el).append('<br>');
\$(el).append(document.createTextNode(lines[i]));
}
return el;
}
``````

Call it by:

``````someElem = nl2br(someElem);
``````

### How to convert a String to a Date using SimpleDateFormat?

This piece of code helps to convert back and forth

``````    System.out.println("Date: "+ String.valueOf(new Date()));
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stringdate = dt.format(new Date());
System.out.println("String.valueOf(date): "+stringdate);

try {
Date date = dt.parse(stringdate);
System.out.println("parse date: "+ String.valueOf(date));
} catch (ParseException e) {
e.printStackTrace();
}
``````

### Capitalize only first character of string and leave others alone? (Rails)

This should do it:

``````title = "test test"
title[0] = title[0].capitalize
puts title # "Test test"
``````

### What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.

Tried explaining it as simply as possible

### Static nested class in Java, why?

Simple example :

``````package test;

public class UpperClass {
public static class StaticInnerClass {}

public class InnerClass {}

public static void main(String[] args) {
// works
StaticInnerClass stat = new StaticInnerClass();
// doesn't compile
InnerClass inner = new InnerClass();
}
}
``````

If non-static the class cannot be instantiated exept in an instance of the upper class (so not in the example where main is a static function)

### Convert DateTime to a specified Format

Easy peasy:

``````var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
``````

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

``````string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
``````

### 'sudo gem install' or 'gem install' and gem locations

You can install gems into a specific folder (example vendor/) in your Rails app using :

``````bundle install --path vendor
``````

### How can I convert spaces to tabs in Vim or Linux?

``````:%s/\(^\s*\)\@<=    /\t/g
``````

Translation: Search for every instance of 4 consecutive spaces (after the = character), but only if the entire line up to that point is whitespace (this uses the zero-width look-behind assertion, `\@<=`). Replace each found instance with a tab character.

### How can I check if a checkbox is checked?

Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/

_x000D_
_x000D_
``````<input type="checkbox" id="check">_x000D_
<a href="#" onclick="check()">click</a>_x000D_
<button onclick="check()">_x000D_
button_x000D_
</button>_x000D_
<script>_x000D_
function check() {_x000D_
if (document.getElementById('check').checked) {_x000D_
} else {_x000D_
alert("You didn't check it! Let me check it for you.");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
</script>``````
_x000D_
_x000D_
_x000D_

### WAMP shows error 'MSVCR100.dll' is missing when install

To solve this issue you have to install all Microsoft redistribution packages 2010,2012(x86 and x64) than uninstall wampserver from control panel and reinstall new copy of wamp server this error will be get fixed

### sprintf like functionality in Python

This is probably the closest translation from your C code to Python code.

``````A = 1
B = "hello"
buf = "A = %d\n , B= %s\n" % (A, B)

c = 2
buf += "C=%d\n" % c

f = open('output.txt', 'w')
print >> f, c
f.close()
``````

The `%` operator in Python does almost exactly the same thing as C's `sprintf`. You can also print the string to a file directly. If there are lots of these string formatted stringlets involved, it might be wise to use a `StringIO` object to speed up processing time.

So instead of doing `+=`, do this:

``````import cStringIO
buf = cStringIO.StringIO()

...

print >> buf, "A = %d\n , B= %s\n" % (A, B)

...

print >> buf, "C=%d\n" % c

...

print >> f, buf.getvalue()
``````

### ng-repeat finish event

Maybe a bit simpler approach with `ngInit` and Lodash's `debounce` method without the need of custom directive:

Controller:

``````\$scope.items = [1, 2, 3, 4];

\$scope.refresh = _.debounce(function() {
// Debounce has timeout and prevents multiple calls, so this will be called
// once the iteration finishes
console.log('we are done');
}, 0);
``````

Template:

``````<ul>
<li ng-repeat="item in items" ng-init="refresh()">{{item}}</li>
</ul>
``````

#### Update

There is even simpler pure AngularJS solution using ternary operator:

Template:

``````<ul>
<li ng-repeat="item in items" ng-init="\$last ? doSomething() : null">{{item}}</li>
</ul>
``````

Be aware that ngInit uses pre-link compilation phase - i.e. the expression is invoked before child directives are processed. This means that still an asynchronous processing might be required.

### jquery drop down menu closing by clicking outside

Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/

_x000D_
_x000D_
``````\$('.moderate .button').on('click', (event) => {_x000D_
\$(event.target).siblings('.dropdown')_x000D_
.toggleClass('is-open');_x000D_
});_x000D_
_x000D_
\$(document).click(function(e) {_x000D_
\$('.moderate')_x000D_
.not(\$('.moderate').has(\$(e.target)))_x000D_
.children('.dropdown')_x000D_
.removeClass('is-open');_x000D_
});``````
_x000D_
``````<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />_x000D_
_x000D_
<script_x000D_
src="https://code.jquery.com/jquery-3.2.1.min.js"_x000D_
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="_x000D_
crossorigin="anonymous"></script>_x000D_
_x000D_
<style>_x000D_
.dropdown {_x000D_
display: none;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
z-index: 10;_x000D_
}_x000D_
_x000D_
.dropdown a {_x000D_
font-size: 12px;_x000D_
}_x000D_
_x000D_
.dropdown.is-open {_x000D_
display: block;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a>   </li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### Deep copy an array in Angular 2 + TypeScript

Simple:

``````let objCopy  = JSON.parse(JSON.stringify(obj));
``````

This Also Works (Only for Arrays)

``````let objCopy2 = obj.slice()
``````

### Background color of text in SVG

Instead of using a `<text>` tag, the `<foreignObject>` tag can be used, which allows for XHTML content with CSS.

When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerName account, where ComputerName is the name of the server on which IIS is running. By default, the IUSER_ComputerName account is a member of the Guests group. This group has security restrictions. Try to grand access to IUSER_ComputerName to that folder

Hope this helps

### Unity 2d jumping script

Usually for jumping people use `Rigidbody2D.AddForce` with `Forcemode.Impulse`. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

``````rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
``````

# Language features:

#### Cleaner multi-return and flow control

• Structured bindings

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

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

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

• Much requested feature to simplify almost-generic code.

#### New algorithms

• `for_each_n`

• `reduce`

• `transform_reduce`

• `exclusive_scan`

• `inclusive_scan`

• `transform_exclusive_scan`

• `transform_inclusive_scan`

#### Deprecated

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

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

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

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

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

these slides had some features missing elsewhere.

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

# Removed:

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

# Papers not yet integrated into above:

• P0505R0 (constexpr chrono)

• P0418R2 (atomic tweaks)

• P0512R0 (template argument deduction tweaks)

• P0490R0 (structured binding tweaks)

• P0513R0 (changes to `std::hash`)

• P0502R0 (parallel exceptions)

• P0509R1 (updating restrictions on exception handling)

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

• P0510R0 (restrictions on variants)

• P0504R0 (tags for optional/variant/any)

• P0497R0 (shared ptr tweaks)

• P0508R0 (structured bindings node handles)

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

# Further reference:

### Java null check why use == instead of .equals()

If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.

### Google Maps API 3 - Custom marker color for default (dot) marker

change it to chart.googleapis.com for the path, otherwise SSL won't work

### numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply `answer1.sum()==0`, and you can't perform a division by zero.

This happens because `answer1` is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

`nan` is returned in this case because of the division by zero.

Now to solve your problem you could:

• go for a library for high-precision mathematics, like mpmath. But that's less fun.
• as an alternative to a bigger weapon, do some math manipulation, as detailed below.
• go for a tailored `scipy/numpy` function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

``````exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
``````

where above `x=3* 1089` and `y=3* 1093`. Now, the argument of this exponential is

`-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06`

For the denominator you could proceed similarly but obtain that `log(1+exp(-z+k))` is already rounded to `0`, so that the argument of the exponential function at the denominator is simply rounded to `-z=-3000`. You then have that your result is

``````exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
``````

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number `1089` in the numerator and the first number `1000` at the denominator):

``````exp(3*(1089-1000))=exp(-267)
``````

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

``````Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
``````

The difference between this number and the exponent above is `+1.7053025658242404e-13`, so the approximation we made at the denominator was fine.

The final result is

``````'exp(-266.99999385580668) = 1.1050349147204485e-116
``````

``````1.105034914720621496.. × 10^-116 # Wolfram alpha.
``````

and again, it is safe to use numpy here too.

### How to subtract 30 days from the current date using SQL Server

``````SELECT DATEADD(day,-30,date) AS before30d
FROM...
``````

But it is strongly recommended to keep date in datetime column, not varchar.

### jQuery if statement, syntax

It depends on what you mean by stop. If it's in a function that can return void then:

``````if(a && b) {
// do something
}else{
// "stop"
return;
}
``````

### HTML input field hint

I think for your situation, the easy and simple for your html input , you can probably add the attribute title

``````<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">
``````

### Removing X-Powered-By

If you have an access to php.ini, set `expose_php = Off`.

### Post form data using HttpWebRequest

Use this code:

``````internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();

string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += \$"{pair.Key}={pair.Value}&";
}

// delete last "&"
body = body.Substring(0, body.Length - 1);

return body;
}
``````

### DNS problem, nslookup works, ping doesn't

Do you have an entry for weddinglist in your hosts file? You can find this in:

``````C:\WINDOWS\system32\drivers\etc
``````

`nslookup` always uses DNS whereas ping uses other methods for finding hostnames as well.

### Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

``````import { trigger, state, style, transition,
animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
})),
state('out', style({
'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
})),
transition('in => out', [group([
animate('400ms ease-in-out', style({
'opacity': '0'
})),
animate('600ms ease-in-out', style({
'max-height': '0px'
})),
animate('700ms ease-in-out', style({
'visibility': 'hidden'
}))
]
)]),
transition('out => in', [group([
animate('1ms ease-in-out', style({
'visibility': 'visible'
})),
animate('600ms ease-in-out', style({
'max-height': '500px'
})),
animate('800ms ease-in-out', style({
'opacity': '1'
}))
]
)])
]),
]
``````

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

``````import { SlideInOutAnimation } from './animations';

@Component({
...
animations: [SlideInOutAnimation]
})
export class AppComponent  {
animationState = 'in';

...

toggleShowDiv(divName: string) {
if (divName === 'divA') {
console.log(this.animationState);
this.animationState = this.animationState === 'out' ? 'in' : 'out';
console.log(this.animationState);
}
}
}
``````

And here is how your app.component.html would look like :

``````<div class="wrapper">
<button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
<div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
THIS DIV IS ANIMATED</div>
<div class="content">THIS IS CONTENT DIV</div>
</div>
``````

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

``````import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
imports: [ ..., BrowserAnimationsModule ],
...
})
``````

### Android sqlite how to check if a record exists

SELECT EXISTS with LIMIT 1 is much faster.

Query Ex: `SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);`

Code Ex:

``````public boolean columnExists(String value) {
String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();

// cursor.getInt(0) is 1 if column with value exists
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
``````

### localhost refused to connect Error in visual studio

I solved a similar problem by listing bound IP addresses in a cmd window running as admin:

``````netsh http show iplisten
``````

Then, one by one, blowing them all away:

``````netsh http delete iplisten ipaddress=127.0.0.200
...
``````

### Could not autowire field in spring. why?

I was getting this same error and searching for it led me here. My fix appeared to be simply to add @Component annotation to the implementation of the abstract service.

In this case, that would look like:

``````import org.springframework.stereotype.Component;

...

@Component
public class ContactServiceImpl implements ContactService {
``````

### How to create a list of objects?

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

``````class myClass():
myInstances = []
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
``````

A hack way to get this done:

``````import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
thisStep += 1
if "myClass object at" in thisLocalsLine:
print(thisLocalsLine)
print(myLocals[(thisStep - 2)])
#myInstances.append(myLocals[(thisStep - 2)])
print(myInstances)
myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
``````

Another more 'clever' hack:

``````import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02

myInstances = []
myClasses = {
"myObj01": ["Foo", "Bar"],
"myObj02": ["FooBar",  "Baz"]
}

for thisClass in myClasses.keys():
exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
``````

### Change value of input placeholder via model?

You can bind with a variable in the controller:

``````<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />
``````

In the controller:

``````\$scope.somePlaceholder = 'abc';
``````

### Regex remove all special characters except numbers?

to remove symbol use tag [ ]

step:1

``````[]
``````

step 2:place what symbol u want to remove eg:@ like [@]

``````[@]
``````

step 3:

``````var name = name.replace(/[@]/g, "");
``````

thats it

_x000D_
_x000D_
``````var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)``````
_x000D_
_x000D_
_x000D_

Extra Tips

To remove space (give one space into square bracket like []=>[ ])

``````[@ ]
``````

It Remove Everything (using except)

``````[^place u dont want to remove]
``````

eg:i remove everyting except alphabet (small and caps)

``````[^a-zA-Z ]
``````

_x000D_
_x000D_
``````var name="ggggg33333@#\$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)``````
_x000D_
_x000D_
_x000D_

### Delete a row from a table by id

to Vilx-:

``````var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
table = table.parentNode;
``````

and what if `row.parentNode` is `TBODY`?

You should check it out first, and after that do `while` by `.tBodies`, probably

### How do I print out the contents of a vector?

Just copy the container to the console.

``````std::vector<int> v{1,2,3,4};
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " " ));
``````

Should output :

``````1 2 3 4
``````

### How can I get the order ID in WooCommerce?

As of woocommerce 3.0

``````\$order->id;
``````

will not work, it will generate notice, use getter function:

``````\$order->get_id();
``````

The same applies for other woocommerce objects like procut.

### Delete specific line from a text file?

What? Use file open, seek position then stream erase line using null.

Gotch it? Simple,stream,no array that eat memory,fast.

This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en

``````Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
line = lineinput(1)
dim namevalue() as string = split(line, "=")
if namevalue(0) = "line name value that i want to edit" then
currentpos = seek(1)
fileclose()
dim fs as filestream("test.ini", filemode.open)
dim sw as streamwriter(fs)
fs.seek(currentpos, seekorigin.begin)
sw.write(null)
sw.write(namevalue + "=" + newvalue)
sw.close()
fs.close()
exit while
end if
msgbox("org ternate jua bisa, no line found")
end while
``````

that's all..use #d

### Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

``````Color maroon = new Color (128, 0, 0);
``````

Once you've done that, you then put:

``````Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string
``````

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

### How to show full column content in a Spark Dataframe?

The other solutions are good. If these are your goals:

1. No truncation of columns,
2. No loss of rows,
3. Fast and
4. Efficient

These two lines are useful ...

``````    df.persist
df.show(df.count, false) // in Scala or 'False' in Python
``````

By persisting, the 2 executor actions, count and show, are faster & more efficient when using `persist` or `cache` to maintain the interim underlying dataframe structure within the executors. See more about persist and cache.

### Find integer index of rows with NaN in pandas dataframe

Here is a simpler solution:

`inds = pd.isnull(df).any(1).nonzero()[0]`

``````In [9]: df
Out[9]:
0         1
0  0.450319  0.062595
1 -0.673058  0.156073
2 -0.871179 -0.118575
3  0.594188       NaN
4 -1.017903 -0.484744
5  0.860375  0.239265
6 -0.640070       NaN
7 -0.535802  1.632932
8  0.876523 -0.153634
9 -0.686914  0.131185

In [10]: pd.isnull(df).any(1).nonzero()[0]
Out[10]: array([3, 6])
``````

### What determines the monitor my app runs on?

I'm fairly sure the primary monitor is the default. If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.

EDIT: The way I usually do it is to have the location stored in the app's settings. On load, if there is no value for them, it defaults to the center of the screen. On closing of the form, it records its position. That way, whenever it opens, it's where it was last. I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.

-- Kevin Fairchild

### How to get the first day of the current week and month?

To get the first day of the month, simply get a `Date` and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.

``````private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
``````

First day of the week is the same thing, but using `Calendar.DAY_OF_WEEK` instead

``````private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
``````

### Extract first item of each sublist

Using list comprehension:

``````>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']
``````

### How to check visibility of software keyboard in Android?

``````if (keyopen())
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
}
``````

The above function is what I use to check if a Keyboard is visible. If it is, then I close it.

Below shows the two methods required.

First, define the workable Window height in onCreate.

``````protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
sheight= rectgle.bottom;
//

}
``````

Then, add a boolean method that gets the Window height at that instance. If it does not match the original (assuming you are not changing it along the way...) then, the keyboard is open.

``````public boolean keyopen()
{
Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int curheight= rectgle.bottom;

if (curheight!=sheight)
{
return true;
}
else
{
return false;
}
}
``````

Frotz!

### Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

``````\$string = iconv('ASCII', 'UTF-8//IGNORE', \$string);
``````

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

### extract digits in a simple way from a python string

If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).

``````def unit_value(str):
m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
if m:
g = m.groups()
return ' '.join((g[0], g[2])).strip(), float(g[1])
else:
return int(str)
``````

### MySQL ORDER BY rand(), name ASC

Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.

``````SELECT COUNT(id) FROM users; #id is the primary key
``````

Then, get a random twenty rows.

``````\$start_row = mt_rand(0, \$total_rows - 20);
``````

The final query:

``````SELECT * FROM users ORDER BY name ASC LIMIT \$start_row, 20;
``````

### How to get Latitude and Longitude of the mobile device in android?

With `google` things changes very often: non of the previous answers worked for me.

based on this google training here is how you do it using

fused location provider

this requires Set Up Google Play Services

Activity class

``````public class GPSTrackerActivity extends AppCompatActivity implements

Location mLastLocation;

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

.build();
}

}

protected void onStart() {
super.onStart();
}

protected void onStop() {
super.onStop();
}

@Override
public void onConnected(Bundle bundle) {
try {

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();

}
} catch (SecurityException e) {

}

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
}
``````

usage

in you activity

`````` Intent intent = new Intent(context, GPSTrackerActivity.class);
startActivityForResult(intent,1);
``````

And this method

`````` protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
Double longitude = extras.getDouble("Longitude");
Double latitude = extras.getDouble("Latitude");
}
}
``````

### HTTP Error 500.19 and error code : 0x80070021

I got this error while trying to host a WCF service in an empty ASP.NET application. The whole solution was using .NET 4.5 platform, on IIS 8.5 running on Windows 8.1. The gotcha was to

1. Open up "Turn Windows Features on or off"

2. Go to WCF section under ASP.NET 4.5 advanced services

3. Check HTTP Activation.

4. You'll be asked to restart the system.

This should Fix the HTTP 500.19!

EDIT 11-FEB-2016 Just got an issue on Windows 10 Pro, IIS 10, This time, it was an HTTP 404.0. The fix is still the same, turn on "HTTP Activation" under Windows Features -> .NET Framework 4.6 Advanced Services -> WCF Services -> HTTP Activation

### Find if value in column A contains value from column B?

You can try this. :) simple solution!

``````=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")
``````

### How can I increase the JVM memory?

When starting the JVM, two parameters can be adjusted to suit your memory needs :

``````-Xms<size>
``````

specifies the initial Java heap size and

``````-Xmx<size>
``````

the maximum Java heap size.

### What is time(NULL) in C?

The `time` function returns the current time (as a `time_t` value) in seconds since some point (on Unix systems, since midnight UTC January 1, 1970), and it takes one argument, a `time_t` pointer in which the time is stored. Passing `NULL` as the argument causes `time` to return the time as a normal return value but not store it anywhere else.

### Circular (or cyclic) imports in Python

As other answers describe this pattern is acceptable in python:

``````def dostuff(self):
from foo import bar
...
``````

Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.

Most Circular Imports are not actually logical circular imports but rather raise `ImportError` errors, because of the way `import()` evaluates top level statements of the entire file when called.

These `ImportErrors` can almost always be avoided if you positively want your imports on top:

Consider this circular import:

#### App A

``````# profiles/serializers.py

from images.serializers import SimplifiedImageSerializer

class SimplifiedProfileSerializer(serializers.Serializer):
name = serializers.CharField()

class ProfileSerializer(SimplifiedProfileSerializer):
recent_images = SimplifiedImageSerializer(many=True)
``````

#### App B

``````# images/serializers.py

from profiles.serializers import SimplifiedProfileSerializer

class SimplifiedImageSerializer(serializers.Serializer):
title = serializers.CharField()

class ImageSerializer(SimplifiedImageSerializer):
profile = SimplifiedProfileSerializer()
``````

From David Beazleys excellent talk Modules and Packages: Live and Let Die! - PyCon 2015, `1:54:00`, here is a way to deal with circular imports in python:

``````try:
from images.serializers import SimplifiedImageSerializer
except ImportError:
import sys
SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']
``````

This tries to import `SimplifiedImageSerializer` and if `ImportError` is raised, because it already is imported, it will pull it from the importcache.

PS: You have to read this entire post in David Beazley's voice.

### How to change users in TortoiseSVN

When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing `--username` and `--password` does not work, and the SVN client does not cache your credentials on disk, too.

When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.

Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:

1. Start Control Panel | Credential Manager on the client computer.
2. Click Add a Windows Credential.
3. As Internet or network address enter the FQDN of the server machine (e.g., `svn.example.com`).
4. As Username enter your domain account's username in the `DOMAIN\Username` format.
5. Complete the password field and click OK.

Now when you will contact `https://svn.example.com/svn/MyRepo` or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.

### python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

### iPhone Debugging: How to resolve 'failed to get the task for process'?

Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe

### MySQL Like multiple values

Don't forget to use parenthesis if you use this function after an `AND` parameter

Like this:

``````WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%')
``````

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
``````<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="index.php">Home</a></li>_x000D_
<li><a href="#portfolio">Portfolio</a></li>_x000D_
<li><a href="#">Blog</a></li>_x000D_
<li><a href="contact.php">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>``````
_x000D_
_x000D_
_x000D_

### heroku - how to see all the logs

`heroku logs -t` shows us the live logs. `heroku logs -n 1500` for specific number of logs

But still I would recommend to use paper trail add-on which have certain benefits and has free basic plan.

### How to make a div with a circular shape?

Use a border-radius property of 50%.

So for example:

``````.example-div {

}
``````

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

``````git rev-parse --show-toplevel
``````

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

``````--show-toplevel
``````

Show the absolute path of the top-level directory.

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

``````git rev-parse --git-dir
``````

That would give the path of the `.git` directory.

The OP mentions:

``````git rev-parse --show-prefix
``````

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

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

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

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

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

### Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Installtion Steps

2. Copy in the respective folder. Example - C:\apache-maven-3.3.9
3. Add Variable (either user or system) M2_HOME = C:\apache-maven-3.3.9
4. Add Variable (either user or system) MAVEN_HOME = C:\apache-maven-3.3.9
5. Update Variable PATH with C:\apache-maven-3.3.9\bin
6. Open CMD and Type mvn -v or mvn --version it should give the below response

C:\Users\XXXXXXX>mvn --version Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:4 7+05:30) Maven home: C:\apache-maven-3.3.9 Java version: 1.8.0_40, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.8.0_40\jre Default locale: en_US, platform encoding: Cp1252 OS name: "windows 8", version: "6.2", arch: "amd64", family: "dos"

**Make sure all variables have correct values using echo %M2_HOME% on CMD

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

You must use the column names and then set the values to insert (both ? marks):

``````//insert 1st row
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();
``````

### How to fill in proxy information in cntlm config file?

For me just using `cntlm -H` wasn't generating the right hash, but it does with the command below providing the user name.

If you need to generate a new password hash for cntlm, because you have change it or you've been forced to update it, you can just type the below command and update your cntlm.conf configuration file with the output:

``````\$ cntlm -u test -H
PassLM          D2AABAF8828482D5552C4BCA4AEBFB11
PassNT          83AC305A1582F064C469755F04AE5C0A
PassNTLMv2      4B80D9370D353EE006D714E39715A5CB    # Only for user 'test', domain ''
``````

There are 2 ways for using Gradle behind a proxy :

#### Add arguments in command line

(From Guillaume Berche's post)

``````-Dhttp.proxyHost=your_proxy_http_host -Dhttp.proxyPort=your_proxy_http_port
``````

or these arguments if you are using https :

``````-Dhttps.proxyHost=your_proxy_https_host -Dhttps.proxyPort=your_proxy_https_port
``````

in `gradle.properties` add the following lines :

``````systemProp.http.proxyHost=your_proxy_http_host
systemProp.http.proxyPort=your_proxy_http_port
systemProp.https.proxyHost=your_proxy_https_host
systemProp.https.proxyPort=your_proxy_https_port
``````

(for `gradle.properties` file location, please refer to official documentation https://docs.gradle.org/current/userguide/build_environment.html

EDIT : as said by @Joost : A small but important detail that I initially overlooked: notice that the actual host name does NOT contain `http://` protocol part of the URL...

### Spring MVC @PathVariable with dot (.) is getting truncated

`/somepath/{variable:.+}` works in Java `requestMapping` tag.

### Parsing CSV files in C#, with header

CsvHelper (a library I maintain) will read a CSV file into custom objects.

``````var csv = new CsvReader( File.OpenText( "file.csv" ) );
var myCustomObjects = csv.GetRecords<MyCustomObject>();
``````

Sometimes you don't own the objects you're trying to read into. In this case, you can use fluent mapping because you can't put attributes on the class.

``````public sealed class MyCustomObjectMap : CsvClassMap<MyCustomObject>
{
public MyCustomObjectMap()
{
Map( m => m.Property1 ).Name( "Column Name" );
Map( m => m.Property2 ).Index( 4 );
Map( m => m.Property3 ).Ignore();
Map( m => m.Property4 ).TypeConverter<MySpecialTypeConverter>();
}
}
``````

EDIT:

CsvReader now requires CultureInfo to be passed into the constuctor (https://github.com/JoshClose/CsvHelper/issues/1441).

Example:

``````var csv = new CsvReader(File.OpenText("file.csv"), System.Globalization.CultureInfo.CurrentCulture);
``````

### Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

``````public IActionResult AddURLTest()
{
}
``````

``````\$(document).ready (function(){
});
});
``````

### MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

MYSQL PROCEDURE steps:

1. change delimiter from default ' ; ' to ' // '

DELIMITER //

1. create PROCEDURE, you can refer syntax

NOTE: Don't forget to end statement with ' ; '

``````create procedure ProG()
begin
SELECT * FROM hs_hr_employee_leave_quota;
end;//
``````
1. Change delimiter back to ' ; '

delimiter ;

1. Now to execute:

call ProG();

### AngularJS - get element attributes values

_x000D_
_x000D_
``````function onContentLoad() {_x000D_
var item = document.getElementById("id1");_x000D_
var x = item.dataset.x;_x000D_
var data = item.dataset.myData;_x000D_
_x000D_
var resX = document.getElementById("resX");_x000D_
var resData = document.getElementById("resData");_x000D_
_x000D_
resX.innerText = x;_x000D_
resData.innerText = data;_x000D_
_x000D_
console.log(x);_x000D_
console.log(data);_x000D_
}``````
_x000D_
``````<body onload="onContentLoad()">_x000D_
<div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
<label id="resX"></label>_x000D_
<label id="resData"></label>_x000D_
</body>``````
_x000D_
_x000D_
_x000D_

### Python Matplotlib figure title overlaps axes label when using twiny

I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:

``````plt.title(figure_title, y=1.08)
``````

This also works for `plt.suptitle()`, but not (yet) for `plt.xlabel()`, etc.

### Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set `raw_input` to 0. Do not do this, at it modifies the built-in `raw_input()` function. Therefore, whenever you call `raw_input()`, it is essentially calling `0()`, which raises the error. To remove the error, remove the first line of your code:

``````M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54

def intro():
print("Welcome! This program will convert measures for you.")
main()

def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")

choice = input("Enter your choice by number: ")

if choice == '1':
convertMK()

elif choice == '2':
converCF()

elif choice == '3':
convertGL()

elif choice == '4':
convertPK()

elif choice == '5':
convertPK()

else:
print("Error")

def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()

def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()

def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()

def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()

def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()

def end():
print("This program will close.")
exit()

intro()
``````

### Clear the entire history stack and start a new activity on Android

I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.

What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.

Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.

Here's my logout function; the View parameter is the button to which the function's attached.

``````public void onLogoutClick(final View view) {
Intent i = new Intent(this, Splash.class);
startActivity(i);
finish();
}
``````

### str.startswith with a list of strings to test for

`str.startswith` allows you to supply a tuple of strings to test for:

``````if link.lower().startswith(("js", "catalog", "script", "katalog")):
``````

From the docs:

`str.startswith(prefix[, start[, end]])`

Return `True` if string starts with the `prefix`, otherwise return `False`. `prefix` can also be a tuple of prefixes to look for.

Below is a demonstration:

``````>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
``````

### Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it `\$place_older` say. And then when you want to eliminate the text, you call `quotemeta`, and you use that value to substitute:

``````my \$subs = quotemeta \$place_holder;
s/\$subs//g;
``````

### changing the owner of folder in linux

Use `chown` to change ownership and `chmod` to change rights.

use the `-R` option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The `-R` option makes them also change the permissions for all files and directories inside of the directory.

For example

``````sudo chown -R username:group directory
``````

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

``````sudo chown username:group directory
``````

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use `chown user: file` (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

``````chgrp group_name file/directory_name
``````

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

``````# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file
``````

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

### MySQL Trigger - Storing a SELECT in a variable

Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)

### How to detect shake event with android?

There are a lot of solutions to this question already, but I wanted to post one that:

• Doesn't use a library depricated in API 3
• Calculates the magnitude of the acceleration correctly
• Correctly applies a timeout between shake events

Here is such a solution:

``````// variables for shake detection
private static final float SHAKE_THRESHOLD = 3.25f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private SensorManager mSensorMgr;
``````

To initialize the timer:

``````// Get a sensor manager to listen for shakes
mSensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

// Listen for shakes
Sensor accelerometer = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
mSensorMgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
``````

`SensorEventListener` methods to override:

``````@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {

float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
Log.d(APP_NAME, "Acceleration is " + acceleration + "m/s^2");

if (acceleration > SHAKE_THRESHOLD) {
mLastShakeTime = curTime;
Log.d(APP_NAME, "Shake, Rattle, and Roll");
}
}
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Ignore
}
``````

When you are all done

``````// Stop listening for shakes
mSensorMgr.unregisterListener(this);
``````

### What is the difference between map and flatMap and a good use case for each?

Use `test.md` as a example:

``````?  spark-1.6.1 cat test.md
This is the first line;
This is the second line;
This is the last line.

scala> val textFile = sc.textFile("test.md")
scala> textFile.map(line => line.split(" ")).count()
res2: Long = 3

scala> textFile.flatMap(line => line.split(" ")).count()
res3: Long = 15

scala> textFile.map(line => line.split(" ")).collect()
res0: Array[Array[String]] = Array(Array(This, is, the, first, line;), Array(This, is, the, second, line;), Array(This, is, the, last, line.))

scala> textFile.flatMap(line => line.split(" ")).collect()
res1: Array[String] = Array(This, is, the, first, line;, This, is, the, second, line;, This, is, the, last, line.)
``````

If you use `map` method, you will get the lines of `test.md`, for `flatMap` method, you will get the number of words.

The `map` method is similar to `flatMap`, they are all return a new RDD. `map` method often to use return a new RDD, `flatMap` method often to use split words.

### Convert to absolute value in Objective-C

Depending on the type of your variable, one of `abs(int)`, `labs(long)`, `llabs(long long)`, `imaxabs(intmax_t)`, `fabsf(float)`, `fabs(double)`, or `fabsl(long double)`.

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no `habs(short)` function. Or `scabs(signed char)` for that matter...)

Apple's and GNU's Objective-C headers also include an `ABS()` macro which is type-agnostic. I don't recommend using `ABS()` however as it is not guaranteed to be side-effect-safe. For instance, `ABS(a++)` will have an undefined result.

If you're using C++ or Objective-C++, you can bring in the `<cmath>` header and use `std::abs()`, which is templated for all the standard integer and floating-point types.

### SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

``````    SELECT COUNT(*) FROM your_table;
``````

### How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

``````<?php

\$filename = 'test.html';
?>
``````

you can create any .html , .php file just change extention in file name

### How to toggle boolean state of react component?

Depending on your context; this will allow you to update state given the mouseEnter function. Either way, by setting a state value to either true:false you can update that state value given any function by setting it to the opposing value with `!this.state.variable`

``````state = {
hover: false
}

onMouseEnter = () => {
this.setState({
hover: !this.state.hover
});
};
``````

### Moving average or running mean

Another approach to find moving average without using numpy, panda

``````import itertools
sample = [2, 6, 10, 8, 11, 10]
list(itertools.starmap(lambda a,b: b/a,
enumerate(itertools.accumulate(sample), 1)))
``````

will print [2.0, 4.0, 6.0, 6.5, 7.4, 7.833333333333333]

### How to replace four spaces with a tab in Sublime Text 2?

If you want to recursively apply this change to all files in a directoy, you can use the Find > Find in Files... modal:

Edit I didn't highlight it in the image, but you have to click the .* button on the left to have Sublime interpret the Find field as a regex /Edit

Edit 2 I neglected to add a start of string anchor to the regex. I'm correcting that below, and will update the image when I get a chance /Edit

The regex in the Find field `^[^\S\t\n\r]{4}` will match white space characters in groups of 4 (excluding tabs and newline characters). The replace field `\t` indicates you would like to replace them with tabs.

If you click the button to the right of the Where field, you'll see options that will help you target your search, replace. `Add Folder` option will let you select the folder you'd like to recursively search from. The `Add Include Filter` option will let you restrict the search to files of a certain extension.