Programs & Examples On #Geometry

Geometry is a branch of mathematics concerned with questions of shape, size, relative position of figures, and the properties of space.

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

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

Interesting question! While there are plenty of guides on horizontally and vertically centering a div, an authoritative treatment of the subject where the centered div is of an unpredetermined width is conspicuously absent.

Let's apply some basic constraints:

  • No Javascript
  • No mangling of the display property to table-cell, which is of questionable support status

Given this, my entry into the fray is the use of the inline-block display property to horizontally center the span within an absolutely positioned div of predetermined height, vertically centered within the parent container in the traditional top: 50%; margin-top: -123px fashion.

Markup: div > div > span

CSS:

body > div { position: relative; height: XYZ; width: XYZ; }
div > div { 
  position: absolute;
  top: 50%;
  height: 30px;
  margin-top: -15px; 
  text-align: center;}
div > span { display: inline-block; }

Source: http://jsfiddle.net/38EFb/


An alternate solution that doesn't require extraneous markups but that very likely produces more problems than it solves is to use the line-height property. Don't do this. But it is included here as an academic note: http://jsfiddle.net/gucwW/

Circle line-segment collision detection algorithm?

You can find a point on a infinite line that is nearest to circle center by projecting vector AC onto vector AB. Calculate the distance between that point and circle center. If it is greater that R, there is no intersection. If the distance is equal to R, line is a tangent of the circle and the point nearest to circle center is actually the intersection point. If distance less that R, then there are 2 intersection points. They lie at the same distance from the point nearest to circle center. That distance can easily be calculated using Pythagorean theorem. Here's algorithm in pseudocode:

{
dX = bX - aX;
dY = bY - aY;
if ((dX == 0) && (dY == 0))
  {
  // A and B are the same points, no way to calculate intersection
  return;
  }

dl = (dX * dX + dY * dY);
t = ((cX - aX) * dX + (cY - aY) * dY) / dl;

// point on a line nearest to circle center
nearestX = aX + t * dX;
nearestY = aY + t * dY;

dist = point_dist(nearestX, nearestY, cX, cY);

if (dist == R)
  {
  // line segment touches circle; one intersection point
  iX = nearestX;
  iY = nearestY;

  if (t < 0 || t > 1)
    {
    // intersection point is not actually within line segment
    }
  }
else if (dist < R)
  {
  // two possible intersection points

  dt = sqrt(R * R - dist * dist) / sqrt(dl);

  // intersection point nearest to A
  t1 = t - dt;
  i1X = aX + t1 * dX;
  i1Y = aY + t1 * dY;
  if (t1 < 0 || t1 > 1)
    {
    // intersection point is not actually within line segment
    }

  // intersection point farthest from A
  t2 = t + dt;
  i2X = aX + t2 * dX;
  i2Y = aY + t2 * dY;
  if (t2 < 0 || t2 > 1)
    {
    // intersection point is not actually within line segment
    }
  }
else
  {
  // no intersection
  }
}

EDIT: added code to check whether found intersection points actually are within line segment.

How to tell whether a point is to the right or left side of a line

Try this code which makes use of a cross product:

public bool isLeft(Point a, Point b, Point c){
     return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0;
}

Where a = line point 1; b = line point 2; c = point to check against.

If the formula is equal to 0, the points are colinear.

If the line is horizontal, then this returns true if the point is above the line.

Shortest distance between a point and a line segment

Eli, the code you've settled on is incorrect. A point near the line on which the segment lies but far off one end of the segment would be incorrectly judged near the segment. Update: The incorrect answer mentioned is no longer the accepted one.

Here's some correct code, in C++. It presumes a class 2D-vector class vec2 {float x,y;}, essentially, with operators to add, subract, scale, etc, and a distance and dot product function (i.e. x1 x2 + y1 y2).

float minimum_distance(vec2 v, vec2 w, vec2 p) {
  // Return minimum distance between line segment vw and point p
  const float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
  if (l2 == 0.0) return distance(p, v);   // v == w case
  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line. 
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  // We clamp t from [0,1] to handle points outside the segment vw.
  const float t = max(0, min(1, dot(p - v, w - v) / l2));
  const vec2 projection = v + t * (w - v);  // Projection falls on the segment
  return distance(p, projection);
}

EDIT: I needed a Javascript implementation, so here it is, with no dependencies (or comments, but it's a direct port of the above). Points are represented as objects with x and y attributes.

function sqr(x) { return x * x }
function dist2(v, w) { return sqr(v.x - w.x) + sqr(v.y - w.y) }
function distToSegmentSquared(p, v, w) {
  var l2 = dist2(v, w);
  if (l2 == 0) return dist2(p, v);
  var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
  t = Math.max(0, Math.min(1, t));
  return dist2(p, { x: v.x + t * (w.x - v.x),
                    y: v.y + t * (w.y - v.y) });
}
function distToSegment(p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w)); }

EDIT 2: I needed a Java version, but more important, I needed it in 3d instead of 2d.

float dist_to_segment_squared(float px, float py, float pz, float lx1, float ly1, float lz1, float lx2, float ly2, float lz2) {
  float line_dist = dist_sq(lx1, ly1, lz1, lx2, ly2, lz2);
  if (line_dist == 0) return dist_sq(px, py, pz, lx1, ly1, lz1);
  float t = ((px - lx1) * (lx2 - lx1) + (py - ly1) * (ly2 - ly1) + (pz - lz1) * (lz2 - lz1)) / line_dist;
  t = constrain(t, 0, 1);
  return dist_sq(px, py, pz, lx1 + t * (lx2 - lx1), ly1 + t * (ly2 - ly1), lz1 + t * (lz2 - lz1));
}

Creating a triangle with for loops

Try this one in Java

for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}

How can you determine a point is between two other points on a line segment?

c# From http://www.faqs.org/faqs/graphics/algorithms-faq/ -> Subject 1.02: How do I find the distance from a point to a line?

Boolean Contains(PointF from, PointF to, PointF pt, double epsilon)
        {

            double segmentLengthSqr = (to.X - from.X) * (to.X - from.X) + (to.Y - from.Y) * (to.Y - from.Y);
            double r = ((pt.X - from.X) * (to.X - from.X) + (pt.Y - from.Y) * (to.Y - from.Y)) / segmentLengthSqr;
            if(r<0 || r>1) return false;
            double sl = ((from.Y - pt.Y) * (to.X - from.X) - (from.X - pt.X) * (to.Y - from.Y)) / System.Math.Sqrt(segmentLengthSqr);
            return -epsilon <= sl && sl <= epsilon;
        }

How do CSS triangles work?

Others have already explained this well. Let me give you an animation which will explain this quickly: http://codepen.io/chriscoyier/pen/lotjh

Here is some code for you to play with and learn the concepts.

HTML:

<html>
  <body>
    <div id="border-demo">
    </div>
  </body>
</html>

CSS:

/*border-width is border thickness*/
#border-demo {
    background: gray;
    border-color: yellow blue red green;/*top right bottom left*/
    border-style: solid;
    border-width: 25px 25px 25px 25px;/*top right bottom left*/
    height: 50px;
    width: 50px;
}

Play with this and see what happens. Set height and width to zero. Then remove top border and make left and right transparent, or just look at the code below to make a css triangle:

#border-demo {
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 100px solid blue;
}

How to draw circle in html page?

There are a few unicode circles you could use:

_x000D_
_x000D_
* { font-size: 50px; }
_x000D_
&#x25CB;_x000D_
&#x25CC;_x000D_
&#x25CD;_x000D_
&#x25CE;_x000D_
&#x25CF;
_x000D_
_x000D_
_x000D_

More shapes here.

You can overlay text on the circles if you want to:

_x000D_
_x000D_
#container {_x000D_
    position: relative;_x000D_
}_x000D_
#circle {_x000D_
  font-size: 50px;_x000D_
  color: #58f;_x000D_
}_x000D_
#text {_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 21px;_x000D_
    left: 11px;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="circle">&#x25CF;</div>_x000D_
    <div id="text">a</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You could also use a custom font (like this one) if you want to have a higher chance of it looking the same on different systems since not all computers/browsers have the same fonts installed.

How to calculate an angle from three points?

      Atan2        output in degrees
       PI/2              +90
         |                | 
         |                |    
   PI ---.--- 0   +180 ---.--- 0       
         |                |
         |                |
       -PI/2             +270

public static double CalculateAngleFromHorizontal(double startX, double startY, double endX, double endY)
{
    var atan = Math.Atan2(endY - startY, endX - startX); // Angle in radians
    var angleDegrees = atan * (180 / Math.PI);  // Angle in degrees (can be +/-)
    if (angleDegrees < 0.0)
    {
        angleDegrees = 360.0 + angleDegrees;
    }
    return angleDegrees;
}

// Angle from point2 to point 3 counter clockwise
public static double CalculateAngle0To360(double centerX, double centerY, double x2, double y2, double x3, double y3)
{
    var angle2 = CalculateAngleFromHorizontal(centerX, centerY, x2, y2);
    var angle3 = CalculateAngleFromHorizontal(centerX, centerY, x3, y3);
    return (360.0 + angle3 - angle2)%360;
}

// Smaller angle from point2 to point 3
public static double CalculateAngle0To180(double centerX, double centerY, double x2, double y2, double x3, double y3)
{
    var angle = CalculateAngle0To360(centerX, centerY, x2, y2, x3, y3);
    if (angle > 180.0)
    {
        angle = 360 - angle;
    }
    return angle;
}

}

A simple algorithm for polygon intersection

This can be a huge approximation depending on your polygons, but here's one :

  • Compute the center of mass for each polygon.
  • Compute the min or max or average distance from each point of the polygon to the center of mass.
  • If C1C2 (where C1/2 is the center of the first/second polygon) >= D1 + D2 (where D1/2 is the distance you computed for first/second polygon) then the two polygons "intersect".

Though, this should be very efficient as any transformation to the polygon applies in the very same way to the center of mass and the center-node distances can be computed only once.

Evenly distributing n points on a sphere

# create uniform spiral grid
numOfPoints = varargin[0]
vxyz = zeros((numOfPoints,3),dtype=float)
sq0 = 0.00033333333**2
sq2 = 0.9999998**2
sumsq = 2*sq0 + sq2
vxyz[numOfPoints -1] = array([(sqrt(sq0/sumsq)), 
                              (sqrt(sq0/sumsq)), 
                              (-sqrt(sq2/sumsq))])
vxyz[0] = -vxyz[numOfPoints -1] 
phi2 = sqrt(5)*0.5 + 2.5
rootCnt = sqrt(numOfPoints)
prevLongitude = 0
for index in arange(1, (numOfPoints -1), 1, dtype=float):
  zInc = (2*index)/(numOfPoints) -1
  radius = sqrt(1-zInc**2)

  longitude = phi2/(rootCnt*radius)
  longitude = longitude + prevLongitude
  while (longitude > 2*pi): 
    longitude = longitude - 2*pi

  prevLongitude = longitude
  if (longitude > pi):
    longitude = longitude - 2*pi

  latitude = arccos(zInc) - pi/2
  vxyz[index] = array([ (cos(latitude) * cos(longitude)) ,
                        (cos(latitude) * sin(longitude)), 
                        sin(latitude)])

Using the "animated circle" in an ImageView while loading stuff

This is generally referred to as an Indeterminate Progress Bar or Indeterminate Progress Dialog.

Combine this with a Thread and a Handler to get exactly what you want. There are a number of examples on how to do this via Google or right here on SO. I would highly recommend spending the time to learn how to use this combination of classes to perform a task like this. It is incredibly useful across many types of applications and will give you a great insight into how Threads and Handlers can work together.

I'll get you started on how this works:

The loading event starts the dialog:

//maybe in onCreate
showDialog(MY_LOADING_DIALOG);
fooThread = new FooThread(handler);
fooThread.start();

Now the thread does the work:

private class FooThread extends Thread {
    Handler mHandler;

    FooThread(Handler h) {
        mHandler = h;
    }

    public void run() { 
        //Do all my work here....you might need a loop for this

        Message msg = mHandler.obtainMessage();
        Bundle b = new Bundle();                
        b.putInt("state", 1);   
        msg.setData(b);
        mHandler.sendMessage(msg);
    }
}

Finally get the state back from the thread when it is complete:

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        int state = msg.getData().getInt("state");
        if (state == 1){
            dismissDialog(MY_LOADING_DIALOG);
            removeDialog(MY_LOADING_DIALOG);
        }
    }
};

Using atan2 to find angle between two vectors

angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))

+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))

+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))

-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))

xb,yb and xa,ya are the coordinates of the two vectors

How to determine if a point is in a 2D triangle?

C# version of the barycentric method posted by andreasdr and Perro Azul. I added a check to abandon the area calculation when s and t have opposite signs, since potentially avoiding one-third of the multiplication cost seems justified.

Also, even though the math here is firmly-established by now, I ran a thorough unit-test harness on this specific code for good measure anyway.

public static bool PointInTriangle(Point p, Point p0, Point p1, Point p2)
{
    var s = p0.Y * p2.X - p0.X * p2.Y + (p2.Y - p0.Y) * p.X + (p0.X - p2.X) * p.Y;
    var t = p0.X * p1.Y - p0.Y * p1.X + (p0.Y - p1.Y) * p.X + (p1.X - p0.X) * p.Y;

    if ((s < 0) != (t < 0))
        return false;

    var A = -p1.Y * p2.X + p0.Y * (p2.X - p1.X) + p0.X * (p1.Y - p2.Y) + p1.X * p2.Y;

    return A < 0 ?
            (s <= 0 && s + t >= A) :
            (s >= 0 && s + t <= A);
}

Circle button css

For div tag there is already default property display:block given by browser. For anchor tag there is not display property given by browser. You need to add display property to it. That's why use display:block or display:inline-block. It will work.

_x000D_
_x000D_
.btn {_x000D_
  display:block;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  border-radius: 50%;_x000D_
  border: 1px solid red;_x000D_
  _x000D_
}
_x000D_
<a class="btn" href="#"><i class="ion-ios-arrow-down"></i></a>
_x000D_
_x000D_
_x000D_

Finding whether a point lies inside a rectangle or not

# Pseudo code
# Corners in ax,ay,bx,by,dx,dy
# Point in x, y

bax = bx - ax
bay = by - ay
dax = dx - ax
day = dy - ay

if ((x - ax) * bax + (y - ay) * bay < 0.0) return false
if ((x - bx) * bax + (y - by) * bay > 0.0) return false
if ((x - ax) * dax + (y - ay) * day < 0.0) return false
if ((x - dx) * dax + (y - dy) * day > 0.0) return false

return true

How can I check if two segments intersect?

One of the solutions above worked so well I decided to write a complete demonstration program using wxPython. You should be able to run this program like this: python "your file name"

# Click on the window to draw a line.
# The program will tell you if this and the other line intersect.

import wx

class Point:
    def __init__(self, newX, newY):
        self.x = newX
        self.y = newY

app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, "Main")
p1 = Point(90,200)
p2 = Point(150,80)
mp = Point(0,0) # mouse point
highestX = 0


def ccw(A,B,C):
    return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)

# Return true if line segments AB and CD intersect
def intersect(A,B,C,D):
    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

def is_intersection(p1, p2, p3, p4):
    return intersect(p1, p2, p3, p4)

def drawIntersection(pc):
    mp2 = Point(highestX, mp.y)
    if is_intersection(p1, p2, mp, mp2):
        pc.DrawText("intersection", 10, 10)
    else:
        pc.DrawText("no intersection", 10, 10)

def do_paint(evt):
    pc = wx.PaintDC(frame)
    pc.DrawLine(p1.x, p1.y, p2.x, p2.y)
    pc.DrawLine(mp.x, mp.y, highestX, mp.y)
    drawIntersection(pc)

def do_left_mouse(evt):
    global mp, highestX
    point = evt.GetPosition()
    mp = Point(point[0], point[1])
    highestX = frame.Size[0]
    frame.Refresh()

frame.Bind(wx.EVT_PAINT, do_paint)
frame.Bind(wx.EVT_LEFT_DOWN, do_left_mouse)
frame.Show()
app.MainLoop()

How to determine if a list of polygon points are in clockwise order?

find the center of mass of these points.

suppose there are lines from this point to your points.

find the angle between two lines for line0 line1

than do it for line1 and line2

...

...

if this angle is monotonically increasing than it is counterclockwise ,

else if monotonically decreasing it is clockwise

else (it is not monotonical)

you cant decide, so it is not wise

Draw radius around a point in Google map

In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.

Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.

Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.

In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).

Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.

How do I compute the intersection point of two lines?

Unlike other suggestions, this is short and doesn't use external libraries like numpy. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.)

def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

print line_intersection((A, B), (C, D))

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y)

EDIT: Initially there was a typo. That was fixed Sept 2014 thanks to @zidik.

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

Calculating the position of points in a circle

The angle between each of your points is going to be 2Pi/x so you can say that for points n= 0 to x-1 the angle from a defined 0 point is 2nPi/x.

Assuming your first point is at (r,0) (where r is the distance from the centre point) then the positions relative to the central point will be:

rCos(2nPi/x),rSin(2nPi/x)

Easier way to create circle div than using an image?

I have 4 solution to finish this task:

  1. border-radius
  2. clip-path
  3. pseudo elements
  4. radial-gradient

_x000D_
_x000D_
#circle1 {
  background-color: #B90136;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
}

#circle2 {
  background-color: #B90136;
  width: 100px;/* specify the radius */
  height: 100px;/* specify the radius */
  clip-path: circle();
}

#circle3::before {
  content: "";
  display: block;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
  background-color: #B90136;
}

#circle4 {
  background-image: radial-gradient(#B90136 70%, transparent 30%);
  height: 100px;/* specify the radius */
  width: 100px;/* specify the radius */
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 pseudo element</h3>
<div id="circle3"></div>
<hr/>
<h3>4 radial-gradient</h3>
<div id="circle4"></div>
_x000D_
_x000D_
_x000D_

Generate a random point within a circle (uniformly)

Note the point density in proportional to inverse square of the radius, hence instead of picking r from [0, r_max], pick from [0, r_max^2], then compute your coordinates as:

x = sqrt(r) * cos(angle)
y = sqrt(r) * sin(angle)

This will give you uniform point distribution on a disk.

http://mathworld.wolfram.com/DiskPointPicking.html

How do you detect where two line segments intersect?

I have tried to implement the algorithm so elegantly described by Jason above; unfortunately while working though the mathematics in the debugging I found many cases for which it doesn't work.

For example consider the points A(10,10) B(20,20) C(10,1) D(1,10) gives h=.5 and yet it is clear by examination that these segments are no-where near each other.

Graphing this makes it clear that 0 < h < 1 criteria only indicates that the intercept point would lie on CD if it existed but tells one nothing of whether that point lies on AB. To ensure that there is a cross point you must do the symmetrical calculation for the variable g and the requirement for interception is: 0 < g < 1 AND 0 < h < 1

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

Calculate distance between 2 GPS coordinates

This Lua code is adapted from stuff found on Wikipedia and in Robert Lipe's GPSbabel tool:

local EARTH_RAD = 6378137.0 
  -- earth's radius in meters (official geoid datum, not 20,000km / pi)

local radmiles = EARTH_RAD*100.0/2.54/12.0/5280.0;
  -- earth's radius in miles

local multipliers = {
  radians = 1, miles = radmiles, mi = radmiles, feet = radmiles * 5280,
  meters = EARTH_RAD, m = EARTH_RAD, km = EARTH_RAD / 1000, 
  degrees = 360 / (2 * math.pi), min = 60 * 360 / (2 * math.pi)
}

function gcdist(pt1, pt2, units) -- return distance in radians or given units
  --- this formula works best for points close together or antipodal
  --- rounding error strikes when distance is one-quarter Earth's circumference
  --- (ref: wikipedia Great-circle distance)
  if not pt1.radians then pt1 = rad(pt1) end
  if not pt2.radians then pt2 = rad(pt2) end
  local sdlat = sin((pt1.lat - pt2.lat) / 2.0);
  local sdlon = sin((pt1.lon - pt2.lon) / 2.0);
  local res = sqrt(sdlat * sdlat + cos(pt1.lat) * cos(pt2.lat) * sdlon * sdlon);
  res = res > 1 and 1 or res < -1 and -1 or res
  res = 2 * asin(res);
  if units then return res * assert(multipliers[units])
  else return res
  end
end

How to draw a filled circle in Java?

public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;
   // Assume x, y, and diameter are instance variables.
   Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
   g2d.fill(circle);
   ...
}

Here are some docs about paintComponent (link).

You should override that method in your JPanel and do something similar to the code snippet above.

In your ActionListener you should specify x, y, diameter and call repaint().

Circle-Rectangle collision detection (intersection)

I developed this algorithm while making this game: https://mshwf.github.io/mates/

If the circle touches the square, then the distance between the centerline of the circle and the centerline of the square should equal (diameter+side)/2. So, let's have a variable named touching that holds that distance. The problem was: which centerline should I consider: the horizontal or the vertical? Consider this frame:

enter image description here

Each centerline gives different distances, and only one is a correct indication to a no-collision, but using our human intuition is a start to understand how the natural algorithm works.

They are not touching, which means that the distance between the two centerlines should be greater than touching, which means that the natural algorithm picks the horizontal centerlines (the vertical centerlines says there's a collision!). By noticing multiple circles, you can tell: if the circle intersects with the vertical extension of the square, then we pick the vertical distance (between the horizontal centerlines), and if the circle intersects with the horizontal extension, we pick the horizontal distance:

enter image description here

Another example, circle number 4: it intersects with the horizontal extension of the square, then we consider the horizontal distance which is equal to touching.

Ok, the tough part is demystified, now we know how the algorithm will work, but how we know with which extension the circle intersects? It's easy actually: we calculate the distance between the most right x and the most left x (of both the circle and the square), and the same for the y-axis, the one with greater value is the axis with the extension that intersects with the circle (if it's greater than diameter+side then the circle is outside the two square extensions, like circle #7). The code looks like:

right = Math.max(square.x+square.side, circle.x+circle.rad);
left = Math.min(square.x, circle.x-circle.rad);

bottom = Math.max(square.y+square.side, circle.y+circle.rad);
top = Math.min(square.y, circle.y-circle.rad);

if (right - left > down - top) {
 //compare with horizontal distance
}
else {
 //compare with vertical distance
}

/*These equations assume that the reference point of the square is at its top left corner, and the reference point of the circle is at its center*/

How do I create a circle or square with just CSS - with a hollow center?

Circle Time! :) Easy way of making a circle with a hollow center : use border-radius, give the element a border and no background so you can see through it :

_x000D_
_x000D_
div {_x000D_
    display: inline-block;_x000D_
    margin-left: 5px;_x000D_
    height: 100px;_x000D_
    border-radius: 100%;_x000D_
    width:100px;_x000D_
    border:solid black 2px;_x000D_
}_x000D_
_x000D_
body{_x000D_
    background:url('http://lorempixel.com/output/people-q-c-640-480-1.jpg');_x000D_
    background-size:cover;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

How to find the Center Coordinate of Rectangle?

The center of rectangle is the midpoint of the diagonal end points of rectangle.

Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 ).

That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2

Let me know your code.

The smallest difference between 2 Angles

For UnityEngine users, the easy way is just to use Mathf.DeltaAngle.

How do I calculate the normal vector of a line segment?

m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1

then

m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line.. 

b is something if you want to pass it from a point you defined

Equation for testing if a point is inside a circle

As said above -- use Euclidean distance.

from math import hypot

def in_radius(c_x, c_y, r, x, y):
    return math.hypot(c_x-x, c_y-y) <= r

Determine if two rectangles overlap each other?

In the question, you link to the maths for when rectangles are at arbitrary angles of rotation. If I understand the bit about angles in the question however, I interpret that all rectangles are perpendicular to one another.

A general knowing the area of overlap formula is:

Using the example:

   1   2   3   4   5   6

1  +---+---+
   |       |   
2  +   A   +---+---+
   |       | B     |
3  +       +   +---+---+
   |       |   |   |   |
4  +---+---+---+---+   +
               |       |
5              +   C   +
               |       |
6              +---+---+

1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates

1 3 4 5 6

2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates

1 2 3 4 6

3) create a 2D array by number of gaps between the unique x coordinates * number of gaps between the unique y coordinates.

4 * 4

4) paint all the rectangles into this grid, incrementing the count of each cell it occurs over:

   1   3   4   5   6

1  +---+
   | 1 | 0   0   0
2  +---+---+---+
   | 1 | 1 | 1 | 0
3  +---+---+---+---+
   | 1 | 1 | 2 | 1 |
4  +---+---+---+---+
     0   0 | 1 | 1 |
6          +---+---+

5) As you paint the rectangles, its easy to intercept the overlaps.

Circle drawing with SVG's arc path

A totally different approach:

Instead of fiddling with paths to specify an arc in svg, you can also take a circle element and specify a stroke-dasharray, in pseudo code:

with $score between 0..1, and pi = 3.141592653589793238

$length = $score * 2 * pi * $r
$max = 7 * $r  (i.e. well above 2*pi*r)

<circle r="$r" stroke-dasharray="$length $max" />

Its simplicity is the main advantage over the multiple-arc-path method (e.g. when scripting you only plug in one value and you're done for any arc length)

The arc starts at the rightmost point, and can be shifted around using a rotate transform.

Note: Firefox has an odd bug where rotations over 90 degrees or more are ignored. So to start the arc from the top, use:

<circle r="$r" transform="rotate(-89.9)" stroke-dasharray="$length $max" />

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

What is deserialize and serialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.

Say, you have an object:

{foo: [1, 4, 7, 10], bar: "baz"}

serializing into JSON will convert it into a string:

'{"foo":[1,4,7,10],"bar":"baz"}'

which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}.

Disable / Check for Mock Location (prevent gps spoofing)

This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }

Match exact string

Use the start and end delimiters: ^abc$

How to open a web page from my application?

The old school way ;)

public static void openit(string x) {
   System.Diagnostics.Process.Start("cmd", "/C start" + " " + x); 
}

Use: openit("www.google.com");

Clearing content of text file using C#

 using (FileStream fs = File.Create(path))
 {

 }

Will create or overwrite a file.

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

Android Color Picker

We have just uploaded AmbilWarna color picker to Maven:

https://github.com/yukuku/ambilwarna

It can be used either as a dialog or as a Preference entry.

enter image description here

Logging in Scala

Using slf4j and a wrapper is nice but the use of it's built in interpolation breaks down when you have more than two values to interpolate, since then you need to create an Array of values to interpolate.

A more Scala like solution is to use a thunk or cluster to delay the concatenation of the error message. A good example of this is Lift's logger

Log.scala Slf4jLog.scala

Which looks like this:

class Log4JLogger(val logger: Logger) extends LiftLogger {
  override def trace(msg: => AnyRef) = if (isTraceEnabled) logger.trace(msg)
}

Note that msg is a call-by-name and won't be evaluated unless isTraceEnabled is true so there's no cost in generating a nice message string. This works around the slf4j's interpolation mechanism which requires parsing the error message. With this model, you can interpolate any number of values into the error message.

If you have a separate trait that mixes this Log4JLogger into your class, then you can do

trace("The foobar from " + a + " doesn't match the foobar from " +
      b + " and you should reset the baz from " + c")

instead of

info("The foobar from {0} doesn't match the foobar from {1} and you should reset the baz from {c},
     Array(a, b, c))

Create Windows service from executable

Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.

Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable to the system.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Postman: sending nested JSON object

This is a combination of the above, because I had to read several posts to understand.

  1. In the Headers, add the following key-values:
    1. Content-Type to application/json
    2. and Accept to application/json

enter image description here

  1. In the Body:
    1. change the type to "raw"
    2. confirm "JSON (application/json)" is the text type
    3. put the nested property there: { "Obj1" : { "key1" : "val1" } }

enter image description here

Hope this helps!

How do I get first element rather than using [0] in jQuery?

You can try like this:
yourArray.shift()

Float a div above page content

Use

position: absolute;
top: ...px;
left: ...px;

To position the div. Make sure it doesn't have a parent tag with position: relative;

HTML button to NOT submit form

Another option that worked for me was to add onsubmit="return false;" to the form tag.

<form onsubmit="return false;">

Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element the won't submit.

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Grep and Python

You can use python-textops3 :

from textops import *

print('\n'.join(cat(f) | grep(search_term)))

with python-textops3 you can use unix-like commands with pipes

How to get current page URL in MVC 3

Add this extension method to your code:

public static Uri UrlOriginal(this HttpRequestBase request)
{
  string hostHeader = request.Headers["host"];

  return new Uri(string.Format("{0}://{1}{2}",
     request.Url.Scheme, 
     hostHeader, 
     request.RawUrl));
}

And then you can execute it off the RequestContext.HttpContext.Request property.

There is a bug (can be side-stepped, see below) in Asp.Net that arises on machines that use ports other than port 80 for the local website (a big issue if internal web sites are published via load-balancing on virtual IP and ports are used internally for publishing rules) whereby Asp.Net will always add the port on the AbsoluteUri property - even if the original request does not use it.

This code ensures that the returned url is always equal to the Url the browser originally requested (including the port - as it would be included in the host header) before any load-balancing etc takes place.

At least, it does in our (rather convoluted!) environment :)

If there are any funky proxies in between that rewrite the host header, then this won't work either.

Update 30th July 2013

As mentioned by @KevinJones in comments below - the setting I mention in the next section has been documented here: http://msdn.microsoft.com/en-us/library/hh975440.aspx

Although I have to say I couldn't get it work when I tried it - but that could just be me making a typo or something.

Update 9th July 2012

I came across this a little while ago, and meant to update this answer, but never did. When an upvote just came in on this answer I thought I should do it now.

The 'bug' I mention in Asp.Net can be be controlled with an apparently undocumented appSettings value - called 'aspnet:UseHostHeaderForRequest' - i.e:

<appSettings>
  <add key="aspnet:UseHostHeaderForRequest" value="true" />
</appSettings>

I came across this while looking at HttpRequest.Url in ILSpy - indicated by the ---> on the left of the following copy/paste from that ILSpy view:

public Uri Url
{
  get
  {
    if (this._url == null && this._wr != null)
    {
      string text = this.QueryStringText;
      if (!string.IsNullOrEmpty(text))
      {
        text = "?" + HttpEncoder.CollapsePercentUFromStringInternal(text, 
          this.QueryStringEncoding);
      }
 ---> if (AppSettings.UseHostHeaderForRequestUrl)
      {
        string knownRequestHeader = this._wr.GetKnownRequestHeader(28);
        try
        {
          if (!string.IsNullOrEmpty(knownRequestHeader))
          {
            this._url = new Uri(string.Concat(new string[]
            {
              this._wr.GetProtocol(),
              "://",
              knownRequestHeader,
              this.Path,
              text 
            }));
          }
        }
        catch (UriFormatException)
        { }
     }
     if (this._url == null) { /* build from server name and port */
       ...

I personally haven't used it - it's undocumented and so therefore not guaranteed to stick around - however it might do the same thing that I mention above. To increase relevancy in search results - and to acknowledge somebody else who seeems to have discovered this - the 'aspnet:UseHostHeaderForRequest' setting has also been mentioned by Nick Aceves on Twitter

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Eventually, add the http.sslverify to your .git/config.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = https://server/user/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[http]
        sslVerify = false

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

Unable to establish SSL connection, how do I fix my SSL cert?

For me a DNS name of my server was added to /etc/hosts and it was mapped to 127.0.0.1 which resulted in

SL23_GET_SERVER_HELLO:unknown protocol

Removing mapping of my real DNS name to 127.0.0.1 resolved the problem.

Learning to write a compiler

If you're willing to use LLVM, check this out: http://llvm.org/docs/tutorial/. It teaches you how to write a compiler from scratch using LLVM's framework, and doesn't assume you have any knowledge about the subject.

The tutorial suggest you write your own parser and lexer etc, but I advise you to look into bison and flex once you get the idea. They make life so much easier.

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

Show a message box from a class in c#?

using System.Windows.Forms;
...
MessageBox.Show("Hello World!");

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

Set formula to a range of cells

Use this

            Sub calc()


            Range("C1:C10").FormulaR1C1 = "=(R10C1+R10C2)"


            End Sub

How can I open a Shell inside a Vim Window?

I guess this is a fairly old question, but now in 2017. We have neovim, which is a fork of vim which adds terminal support.

So invoking :term would open a terminal window. The beauty of this solution as opposed to using tmux (a terminal multiplexer) is that you'll have the same window bindings as your vim setup. neovim is compatible with vim, so you can basically copy and paste your .vimrc and it will just work.

More advantages are you can switch to normal mode on the opened terminal and you can do basic copy and editing. It is also pretty useful for git commits too I guess, since everything in your buffer you can use in auto-complete.

I'll update this answer since vim is also planning to release terminal support, probably in vim 8.1. You can follow the progress here: https://groups.google.com/forum/#!topic/vim_dev/Q9gUWGCeTXM

Once it's released, I do believe this is a more superior setup than using tmux.

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

Share variables between files in Node.js?

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

How to change environment's font size?

enter image description here

I have mine set to "editor.fontSize": 12,

Save the file, you will see the effect right the way.

enter image description here

Enjoy !

How to prompt for user input and read command-line arguments

The best way to process command line arguments is the argparse module.

Use raw_input() to get user input. If you import the readline module your users will have line editing and history.

How do you uninstall a python package that was installed using distutils?

Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.

If you want to make it work again, simply re-install.

By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.

AngularJS toggle class using ng-class

Add more than one class based on the condition:

<div ng-click="AbrirPopUp(s)" 
ng-class="{'class1 class2 class3':!isNew, 
           'class1 class4': isNew}">{{ isNew }}</div>

Apply: class1 + class2 + class3 when isNew=false,

Apply: class1+ class4 when isNew=true

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

powershell is missing the terminator: "

This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:

"c:\users\abc\"

instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.

"c:\users\abc\\"

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

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

await is only valid in async function

To use await, its executing context needs to be async in nature

As it said, you need to define the nature of your executing context where you are willing to await a task before anything.

Just put async before the fn declaration in which your async task will execute.

var start = async function(a, b) { 
  // Your async task will execute with await
  await foo()
  console.log('I will execute after foo get either resolved/rejected')
}

Explanation:

In your question, you are importing a method which is asynchronous in nature and will execute in parallel. But where you are trying to execute that async method is inside a different execution context which you need to define async to use await.

 var helper = require('./helper.js');   
 var start = async function(a,b){
     ....
     const result = await helper.myfunction('test','test');
 }
 exports.start = start;

Wondering what's going under the hood

await consumes promise/future / task-returning methods/functions and async marks a method/function as capable of using await.

Also if you are familiar with promises, await is actually doing the same process of promise/resolve. Creating a chain of promise and executes you next task in resolve callback.

For more info you can refer to MDN DOCS.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:

string.Empty.PadRight(totalLength, (char)32);

An alternative approach: Create all spaces manually within a custom method and call it:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

And call it in your code to create white spaces: GetSpaces(14);

Windows 7 environment variable not working in path

Things like having %PATH% or spaces between items in your path will break it. Be warned.

Yes, windows paths that include spaces will cause errors. For example an application added this to the front of the system %PATH% variable definition:

C:\Program Files (x86)\WebEx\Productivity Tools;C:\Sybase\IQ-16_0\Bin64;

which caused all of the paths in %PATH% to not be set in the cmd window.

My solution is to demarcate the extended path variable in double quotes where needed:

"C:\Program Files (x86)\WebEx\Productivity Tools";C:\Sybase\IQ-16_0\Bin64;

The spaces are therefore ignored and the full path variable is parsed properly.

Most efficient way to check for DBNull and then assign to a variable?

This is how I handle reading from DataRows

///<summary>
/// Handles operations for Enumerations
///</summary>
public static class DataRowUserExtensions
{
    /// <summary>
    /// Gets the specified data row.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static T Get<T>(this DataRow dataRow, string key)
    {
        return (T) ChangeTypeTo<T>(dataRow[key]);
    }

    private static object ChangeTypeTo<T>(this object value)
    {
        Type underlyingType = typeof (T);
        if (underlyingType == null)
            throw new ArgumentNullException("value");

        if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
        {
            if (value == null)
                return null;
            var converter = new NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }

        // Try changing to Guid  
        if (underlyingType == typeof (Guid))
        {
            try
            {
                return new Guid(value.ToString());
            }
            catch

            {
                return null;
            }
        }
        return Convert.ChangeType(value, underlyingType);
    }
}

Usage example:

if (dbRow.Get<int>("Type") == 1)
{
    newNode = new TreeViewNode
                  {
                      ToolTip = dbRow.Get<string>("Name"),
                      Text = (dbRow.Get<string>("Name").Length > 25 ? dbRow.Get<string>("Name").Substring(0, 25) + "..." : dbRow.Get<string>("Name")),
                      ImageUrl = "file.gif",
                      ID = dbRow.Get<string>("ReportPath"),
                      Value = dbRow.Get<string>("ReportDescription").Replace("'", "\'"),
                      NavigateUrl = ("?ReportType=" + dbRow.Get<string>("ReportPath"))
                  };
}

Props to Monsters Got My .Net for ChageTypeTo code.

Get underlined text with Markdown

Markdown doesn't have a defined syntax to underline text.

I guess this is because underlined text is hard to read, and that it's usually used for hyperlinks.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

How to POST a JSON object to a JAX-RS service

Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml

@Path("/customer")
public class CustomerService {

    private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();

    @POST
    @Path("save")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public SaveResult save(Customer c) {

        customers.put(c.getId(), c);

        SaveResult sr = new SaveResult();
        sr.sucess = true;
        return sr;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{id}")
    public Customer getCustomer(@PathParam("id") int id) {
        Customer c = customers.get(id);
        if (c == null) {
            c = new Customer();
            c.setId(id * 3);
            c.setName("unknow " + id);
        }
        return c;
    }
}

And in the pom.xml

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.7</version>
</dependency>

Installed Java 7 on Mac OS X but Terminal is still using version 6

Update

brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk/openjdk/adoptopenjdk8

https://stackoverflow.com/a/28635465

Old version For me the easiest and cleanest way to go is to install Java using homebrew like described here:

https://stackoverflow.com/a/28635465

brew update
brew cask install java

List of standard lengths for database fields

I just queried my database with millions of customers in the USA.

  • The maximum first name length was 46. I go with 50. (Of course, only 500 of those were over 25, and they were all cases where data imports resulted in extra junk winding up in that field.)

  • Last name was similar to first name.

  • Email addresses maxed out at 62 characters. Most of the longer ones were actually lists of email addresses separated by semicolons.

  • Street address maxes out at 95 characters. The long ones were all valid.

  • Max city length was 35.

This should be a decent statistical spread for people in the US. If you have localization to consider, the numbers could vary significantly.

How to solve WAMP and Skype conflict on Windows 7?

  1. open skype
  2. click tools and go to options
  3. click advanced option from left side
  4. click connection
  5. unchecked (Use port 80 and 443 as alternatives for incoming connection)

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How to securely save username/password (local)?

If you are just going to verify/validate the entered user name and password, use the Rfc2898DerivedBytes class (also known as Password Based Key Derivation Function 2 or PBKDF2). This is more secure than using encryption like Triple DES or AES because there is no practical way to go from the result of RFC2898DerivedBytes back to the password. You can only go from a password to the result. See Is it ok to use SHA1 hash of password as a salt when deriving encryption key and IV from password string? for an example and discussion for .Net or String encrypt / decrypt with password c# Metro Style for WinRT/Metro.

If you are storing the password for reuse, such as supplying it to a third party, use the Windows Data Protection API (DPAPI). This uses operating system generated and protected keys and the Triple DES encryption algorithm to encrypt and decrypt information. This means your application does not have to worry about generating and protecting the encryption keys, a major concern when using cryptography.

In C#, use the System.Security.Cryptography.ProtectedData class. For example, to encrypt a piece of data, use ProtectedData.Protect():

// Data to protect. Convert a string to a byte[] using Encoding.UTF8.GetBytes().
byte[] plaintext; 

// Generate additional entropy (will be used as the Initialization vector)
byte[] entropy = new byte[20];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
    rng.GetBytes(entropy);
}

byte[] ciphertext = ProtectedData.Protect(plaintext, entropy,
    DataProtectionScope.CurrentUser);

Store the entropy and ciphertext securely, such as in a file or registry key with permissions set so only the current user can read it. To get access to the original data, use ProtectedData.Unprotect():

byte[] plaintext= ProtectedData.Unprotect(ciphertext, entropy,
    DataProtectionScope.CurrentUser);

Note that there are additional security considerations. For example, avoid storing secrets like passwords as a string. Strings are immutable, being they cannot be notified in memory so someone looking at the application's memory or a memory dump may see the password. Use SecureString or a byte[] instead and remember to dispose or zero them as soon as the password is no longer needed.

Accessing Websites through a Different Port?

Perhaps this is obvious, but FWIW this will only work if the web server is serving requests for that website on the alternate port. It's not at all uncommon for a webserver to only serve a site on port 80.

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

Generating an array of letters in the alphabet

You could do something like this, based on the ascii values of the characters:

char[26] alphabet;

for(int i = 0; i <26; i++)
{
     alphabet[i] = (char)(i+65); //65 is the offset for capital A in the ascaii table
}

(See the table here.) You are just casting from the int value of the character to the character value - but, that only works for ascii characters not different languages etc.

EDIT: As suggested by Mehrdad in the comment to a similar solution, it's better to do this:

alphabet[i] = (char)(i+(int)('A'));

This casts the A character to it's int value and then increments based on this, so it's not hardcoded.

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

How do I check if an element is hidden in jQuery?

.is(":not(':hidden')") /*if shown*/

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Get DateTime.Now with milliseconds precision

This should work:

DateTime.Now.ToString("hh.mm.ss.ffffff");

If you don't need it to be displayed and just need to know the time difference, well don't convert it to a String. Just leave it as, DateTime.Now();

And use TimeSpan to know the difference between time intervals:

Example

DateTime start;
TimeSpan time;

start = DateTime.Now;

//Do something here

time = DateTime.Now - start;
label1.Text = String.Format("{0}.{1}", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));

"Keep Me Logged In" - the best approach

I think you could just do this:

$cookieString = password_hash($username, PASSWORD_DEFAULT);

Store $cookiestring in the DB and and set it as a cookie. Also set the username of the person as a cookie. The whole point of a hash is that it can't be reverse-engineered.

When a user turns up, get the username from one cookie, than $cookieString from another. If $cookieString matches the one stored in the DB, then the user is authenticated. As password_hash uses a different salt each time, it is irrelevant as to what the clear text is.

How to uninstall Ruby from /usr/local?

do this way :

sudo apt purge ruby

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

How to check type of variable in Java?

You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.

reference - Here is the Oracle docs link

jQuery val is undefined?

You should call the events after the document is ready, like this:

$(document).ready(function () {
  // Your code
});

This is because you are trying to manipulate elements before they are rendered by the browser.

So, in the case you posted it should look something like this

$(document).ready(function () {
  var editorTitle = $('#editorTitle').val();
  var editorText = $('#editorText').html();
});

Hope it helps.

Tips: always save your jQuery object in a variable for later use and only code that really need to run after the document have loaded should go inside the ready() function.

Dark color scheme for Eclipse

These are the pleasing colors for my eyes during coding. Jazz music not included in theme.

Screenshot of LukinaJama3

Eclipse Color Themes Plugin file: LukinaJama3.xml on depositfiles

build-impl.xml:1031: The module has not been deployed

One of the main reason for this error is due to permission not granted to all users. so remove this error, follow the following steps :
1) Go to the C:/Programme Files/Apache Software Foundation/Tomcat 7.0
2) Right click on the Tomcat 7.0 folder and click on properties.
3) go to Security Tab.
4) Select the User and click on Edit... button
5) Grant all the permission to the user and click on apply and ok.
Refresh the system and now try. I hope it will work

Exists Angularjs code/naming conventions?

I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171

Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower

And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec

Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub

Convert integer to hex and hex to integer

Given:

declare @hexStr varchar(16), @intVal int

IntToHexStr:

select @hexStr = convert(varbinary, @intVal, 1)

HexStrToInt:

declare
    @query varchar(100),
    @parameters varchar(50)

select
    @query = 'select @result = convert(int,' + @hb + ')',
    @parameters = '@result int output'

exec master.dbo.Sp_executesql @query, @parameters, @intVal output

Adding an external directory to Tomcat classpath

In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see

set CLASSPATH=%JAVA_HOME%\lib\tools.jar

then in catalina.bat, it's used like so

%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% 
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" 
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" 
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat

set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

Angularjs - Pass argument to directive

You can pass arguments to your custom directive as you do with the builtin Angular-directives - by specifying an attribute on the directive-element:

angular.element(document.getElementById('wrapper'))
       .append('<directive-name title="title2"></directive-name>');

What you need to do is define the scope (including the argument(s)/parameter(s)) in the factory function of your directive. In below example the directive takes a title-parameter. You can then use it, for example in the template, using the regular Angular-way: {{title}}

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

Depending on how/what you want to bind, you have different options:

  • = is two-way binding
  • @ simply reads the value (one-way binding)
  • & is used to bind functions

In some cases you may want use an "external" name which differs from the "internal" name. With external I mean the attribute name on the directive-element and with internal I mean the name of the variable which is used within the directive's scope.

For example if we look at above directive, you might not want to specify another, additional attribute for the title, even though you internally want to work with a title-property. Instead you want to use your directive as follows:

<directive-name="title2"></directive-name>

This can be achieved by specifying a name behind the above mentioned option in the scope definition:

scope: {
    title: '@directiveName'
}

Please also note following things:

  • The HTML5-specification says that custom attributes (this is basically what is all over the place in Angular applications) should be prefixed with data-. Angular supports this by stripping the data--prefix from any attributes. So in above example you could specify the attribute on the element (data-title="title2") and internally everything would be the same.
  • Attributes on elements are always in the form of <div data-my-attribute="..." /> while in code (e.g. properties on scope object) they are in the form of myAttribute. I lost lots of time before I realized this.
  • For another approach to exchanging/sharing data between different Angular components (controllers, directives), you might want to have a look at services or directive controllers.
  • You can find more information on the Angular homepage (directives)

How do I use Safe Area Layout programmatically?

I'm actually using an extension for it and controlling if it is ios 11 or not.

extension UIView {

  var safeTopAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.topAnchor
    }
    return self.topAnchor
  }

  var safeLeftAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *){
      return self.safeAreaLayoutGuide.leftAnchor
    }
    return self.leftAnchor
  }

  var safeRightAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *){
      return self.safeAreaLayoutGuide.rightAnchor
    }
    return self.rightAnchor
  }

  var safeBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.bottomAnchor
    }
    return self.bottomAnchor
  }
}

How to set the timezone in Django?

Universal solution, based on Django's TZ name support:

UTC-2 = 'Etc/GMT+2'
UTC-1 = 'Etc/GMT+1'
UTC = 'Etc/GMT+0'
UTC+1 = 'Etc/GMT-1'
UTC+2 = 'Etc/GMT-2'

+/- is intentionally switched.

using extern template (C++11)

The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization

#include <MyClass>
extern template class CMyClass<int>;

The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)

template class CMyClass<int>;
template class CMyClass<float>;

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

How to hide Table Row Overflow?

If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).

To use the plugin just type

$('selector').tableoverflow();

Plugin: https://github.com/marcogrcr/jquery-tableoverflow

Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Invoking a jQuery function after .each() has completed

what about

$(parentSelect).nextAll().fadeOut(200, function() { 
    $(this).remove(); 
}).one(function(){
    myfunction();
}); 

How do I create variable variables?

You have to use globals() built in method to achieve that behaviour:

def var_of_var(k, v):
    globals()[k] = v

print variable_name # NameError: name 'variable_name' is not defined
some_name = 'variable_name'
globals()[some_name] = 123
print(variable_name) # 123

some_name = 'variable_name2'
var_of_var(some_name, 456)
print(variable_name2) # 456

How to set up file permissions for Laravel?

The Laravel 5.4 docs say:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

There are a lot of answers on this page that mention using 777 permissions. Don't do that. You'd be exposing yourself to hackers.

Instead, follow the suggestions by others about how to set permissions of 755 (or more restrictive). You may need to figure out which user your app is running as by running whoami in the terminal and then change ownership of certain directories using chown -R.

If you do not have permission to use sudo as so many other answers require...

Your server is probably a shared host such as Cloudways.

(In my case, I had cloned my Laravel application into a second Cloudways server of mine, and it wasn't completely working because the permissions of the storage and bootstrap/cache directories were messed up.)

I needed to use:

Cloudways Platform > Server > Application Settings > Reset Permission

Then I could run php artisan cache:clear in the terminal.

Node.js: how to consume SOAP XML web service

You don't have that many options.

You'll probably want to use one of:

c# open file with default application and parameters

If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.

On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:


You can do it without telling the full Acrobat path, like this:

Process myProcess = new Process();    
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();

If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:

myProcess.StartInfo.FileName = "Acrobat.exe";

You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.

Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows

What's a decent SFTP command-line client for windows?

LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.

Achtunq, it uses Cygwin, but everything is included in the bundle.

Getting Java version at runtime

Here is the answer from @mvanle, converted to Scala: scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b") javaVerPrefix: String = 1 javaVerMajor: String = 8 javaVerMinor: String = 0

How do I set specific environment variables when debugging in Visual Studio?

As environments are inherited from the parent process, you could write an add-in for Visual Studio that modifies its environment variables before you perform the start. I am not sure how easy that would be to put into your process.

Why does jQuery or a DOM method such as getElementById not find the element?

My solution was to not use the id of an anchor element: <a id='star_wars'>Place to jump to</a>. Apparently blazor and other spa frameworks have issues jumping to anchors on the same page. To get around that I had to use document.getElementById('star_wars'). However this didn't work until I put the id in a paragraph element instead: <p id='star_wars'>Some paragraph<p>.

Example using bootstrap:

<button class="btn btn-link" onclick="document.getElementById('star_wars').scrollIntoView({behavior:'smooth'})">Star Wars</button>

... lots of other text

<p id="star_wars">Star Wars is an American epic...</p>

tqdm in Jupyter Notebook prints new progress bars repeatedly

For everyone who is on windows and couldn't solve the duplicating bars issue with any of the solutions mentioned here. I had to install the colorama package as stated in tqdm's known issues which fixed it.

pip install colorama

Try it with this example:

from tqdm import tqdm
from time import sleep

for _ in tqdm(range(5), "All", ncols = 80, position = 0):
    for _ in tqdm(range(100), "Sub", ncols = 80, position = 1, leave = False):
        sleep(0.01)

Which will produce something like:

All:  60%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                | 3/5 [00:03<00:02,  1.02s/it]
Sub:  50%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                  | 50/100 [00:00<00:00, 97.88it/s]

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

Set a button group's width to 100% and make buttons equal width?

Bootstrap has the .btn-group-justified css class.

How it's structured is based on the type of tags you use.

With <a> tags

<div class="btn-group btn-group-justified" role="group" aria-label="...">
   ...
</div>

With <button> tags

<div class="btn-group btn-group-justified" role="group" aria-label="...">
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default">Left</button>
  </div>
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default">Middle</button>
  </div>
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default">Right</button>
  </div>
</div>

jQuery set checkbox checked

Have you tried running $("#estado_cat").checkboxradio("refresh") on your checkbox?

index.php not loading by default

Try creating a .htaccess file with the following

DirectoryIndex index.php

Edit: Actually, isn't there a 'php-apache' package or something that you're supposed to install with both of them?

Using Javascript in CSS

I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>
</a>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

HTTP Error 503, the service is unavailable

i see this error after install url rewrite module i try to install previous version of it from: https://www.microsoft.com/en-us/download/details.aspx?id=7435 it fixed my error

Android: Share plain text using intent (to all messaging apps)

Use the code as:

    /*Create an ACTION_SEND Intent*/
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    /*This will be the actual content you wish you share.*/
    String shareBody = "Here is the share content body";
    /*The type of the content is text, obviously.*/
    intent.setType("text/plain");
    /*Applying information Subject and Body.*/
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
    intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    /*Fire!*/
    startActivity(Intent.createChooser(intent, getString(R.string.share_using)));

How to make a owl carousel with arrows instead of next previous

The following code works for me on owl carousel .

https://github.com/OwlFonk/OwlCarousel

$(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    navigation: true,
    navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

For OwlCarousel2

https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

 $(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    nav: true,
    navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

EDIT: Please use @cbowns solution - deviceconsole is compatible with iOS9 and much easier to use.

This is a open-source program that displays the iDevice's system log in Terminal (in a manner similar to tail -F). No jailbreak is required, and the output is fully grep'able so you can filter to see output from your program only. What's particularly good about this solution is you can view the log whether or not the app was launched in debug mode from XCode.

Here's how:

Grab the libimobiledevice binary for Mac OS X from my github account at https://github.com/benvium/libimobiledevice-macosx/zipball/master

Follow the install instructions here: https://github.com/benvium/libimobiledevice-macosx/blob/master/README.md

Connect your device, open up Terminal.app and type:

idevicesyslog

Up pops a real-time display of the device's system log.

With it being a console app, you can filter the log using unix commands, such as grep

For instance, see all log messages from a particular app:

idevicesyslog | grep myappname

Taken from my blog at http://pervasivecode.blogspot.co.uk/2012/06/view-log-output-of-any-app-on-iphone-or.html

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

After experimenting on that case: android:textColor="@colors/text_color" is wrong since @color is not filename dependant. You can name your resource file foobar.xml, it doesn't matter but if you have defined some colors in it you can access them using @color/some_color.

Update:

file location: res/values/colors.xml The filename is arbitrary. The element's name will be used as the resource ID. (Source)

Why does overflow:hidden not work in a <td>?

Apply CSS table-layout:fixed; (and sometimes width:<any px or %>) to the TABLE and white-space: nowrap; overflow: hidden; style on TD. Then set CSS widths on the correct cell or column elements.

Significantly, fixed-layout table column widths are determined by the cell widths in the first row of the table. If there are TH elements in the first row, and widths are applied to TD (and not TH), then the width only applies to the contents of the TD (white-space and overflow may be ignored); the table columns will distribute evenly regardless of the set TD width (because there are no widths specified [on TH in the first row]) and the columns will have [calculated] equal widths; the table will not recalculate the column width based on TD width in subsequent rows. Set the width on the first cell elements the table will encounter.

Alternatively, and the safest way to set column widths is to use <COLGROUP> and <COL> tags in the table with the CSS width set on each fixed width COL. Cell width related CSS plays nicer when the table knows the column widths in advance.

Set Jackson Timezone for Date deserialization

Looks like older answers were fine for older Jackson versions, but since objectMapper has method setTimeZone(tz), setting time zone on a dateFormat is totally ignored.

How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

Full example

  @Test
  void test() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    JavaTimeModule module = new JavaTimeModule();
    objectMapper.registerModule(module);
    objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

    ZonedDateTime now = ZonedDateTime.now();
    String converted = objectMapper.writeValueAsString(now);

    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("converted: " + converted);
    System.out.println("restored: " + restored);

    Assertions.assertThat(now).isEqualTo(restored);
  }
`

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

document .click function for touch device

To trigger the function with click or touch, you could change this:

$(document).click( function () {

To this:

$(document).on('click touchstart', function () {

Or this:

$(document).on('click touch', function () {

The touchstart event fires as soon as an element is touched, the touch event is more like a "tap", i.e. a single contact on the surface. You should really try each of these to see what works best for you. On some devices, touch can be a little harder to trigger (which may be a good or bad thing - it prevents a drag being counted, but an accidental small drag may cause it to not be fired).

A Space between Inline-Block List Items

I had the same problem, when I used a inline-block on my menu I had the space between each "li" I found a simple solution, I don't remember where I found it, anyway here is what I did.

<li><a href="index.html" title="home" class="active">Home</a></li><!---->
<li><a href="news.html" title="news">News</a></li><!---->
<li><a href="about.html" title="about">About Us</a></li><!---->
<li><a href="contact.html" title="contact">Contact Us</a></li>

You add a comment sign between each end of, and start of : "li" Then the horizontal space disappear. Hope that answer to the question Thanks

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I had a similar problem and solved it using list...not sure if this will help or not

classes = list(unique_labels(y_true, y_pred))

How do you open a file in C++?

fstream are great but I will go a little deeper and tell you about RAII.

The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.

Update: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII.

class FileOpener
{
public:
    FileOpener(std::fstream& file, const char* fileName): m_file(file)
    { 
        m_file.open(fileName); 
    }
    ~FileOpeneer()
    { 
        file.close(); 
    }

private:
    std::fstream& m_file;
};

You can now use this class in your code like this:

int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called

Learning how RAII works can save you some headaches and some major memory management bugs.

Filtering a list based on a list of booleans

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options It is a security feature designed to prevent clickJacking attacks,

How Does clickJacking work?

  1. The evil page looks exactly like the victim page.
  2. Then it tricked users to enter their username and password.

Technically the evil has an iframe with the source to the victim page.

<html>
    <iframe src='victim_domain.com'/>
    <input id="username" type="text" style="display: none;"/>
    <input id="password" type="text" style="display: none;"/>
    <script>
        //some JS code that click jacking the user username and input from inside the iframe...
    <script/>
<html>

How the security feature work

If you want to prevent web server request to be rendered within an iframe add the x-frame-options

X-Frame-Options DENY

The options are:

  1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.
  2. DENY //do not allow my HTML to be rendered inside any iframe
  3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

This is IIS config example:

   <httpProtocol>
       <customHeaders>
           <add name="X-Frame-Options" value="SAMEORIGIN" />
       </customHeaders>
   </httpProtocol>

The solution to the question

If the web server activated the security feature it may cause a client-side SecurityError as it should.

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

Facebook Open Graph not clearing cache

I've found out that if your image is 72dpi it will give you the image size error. Use 96dpi instead. Hope this helps.

C++ - how to find the length of an integer

Closed formula for the longest int (I used int here, but works for any signed integral type):

1 + (int) ceil((8*sizeof(int)-1) * log10(2))

Explanation:

                  sizeof(int)                 // number bytes in int
                8*sizeof(int)                 // number of binary digits (bits)
                8*sizeof(int)-1               // discount one bit for the negatives
               (8*sizeof(int)-1) * log10(2)   // convert to decimal, because:
                                              // 1 bit == log10(2) decimal digits
    (int) ceil((8*sizeof(int)-1) * log10(2))  // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2))  // make room for the minus sign

For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".

If you want the number of decimal digits of some int value, you can use the following function:

unsigned base10_size(int value)
{
    if(value == 0) {
        return 1u;
    }

    unsigned ret;
    double dval;
    if(value > 0) {
        ret = 0;
        dval = value;
    } else {
        // Make room for the minus sign, and proceed as if positive.
        ret = 1;
        dval = -double(value);
    }

    ret += ceil(log10(dval+1.0));

    return ret;
}

I tested this function for the whole range of int in g++ 9.3.0 for x86-64.

What are all the possible values for HTTP "Content-Type" header?

You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml

The most common type are:

  1. Type application

    application/java-archive
    application/EDI-X12   
    application/EDIFACT   
    application/javascript   
    application/octet-stream   
    application/ogg   
    application/pdf  
    application/xhtml+xml   
    application/x-shockwave-flash    
    application/json  
    application/ld+json  
    application/xml   
    application/zip  
    application/x-www-form-urlencoded  
    
  2. Type audio

    audio/mpeg   
    audio/x-ms-wma   
    audio/vnd.rn-realaudio   
    audio/x-wav   
    
  3. Type image

    image/gif   
    image/jpeg   
    image/png   
    image/tiff    
    image/vnd.microsoft.icon    
    image/x-icon   
    image/vnd.djvu   
    image/svg+xml    
    
  4. Type multipart

    multipart/mixed    
    multipart/alternative   
    multipart/related (using by MHTML (HTML mail).)  
    multipart/form-data  
    
  5. Type text

    text/css    
    text/csv    
    text/html    
    text/javascript (obsolete)    
    text/plain    
    text/xml    
    
  6. Type video

    video/mpeg    
    video/mp4    
    video/quicktime    
    video/x-ms-wmv    
    video/x-msvideo    
    video/x-flv   
    video/webm   
    
  7. Type vnd :

    application/vnd.android.package-archive
    application/vnd.oasis.opendocument.text    
    application/vnd.oasis.opendocument.spreadsheet  
    application/vnd.oasis.opendocument.presentation   
    application/vnd.oasis.opendocument.graphics   
    application/vnd.ms-excel    
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet   
    application/vnd.ms-powerpoint    
    application/vnd.openxmlformats-officedocument.presentationml.presentation    
    application/msword   
    application/vnd.openxmlformats-officedocument.wordprocessingml.document   
    application/vnd.mozilla.xul+xml   
    

Uninstall Node.JS using Linux command line?

after installing using the "ROCK-SOLID NODE.JS PLATFORM ON UBUNTU" script, i get this output. Which tells you how to uninstall nodejs.

Done. The new package has been installed and saved to

/tmp/node-install/node-v0.8.19/nodejs_0.8.19-1_i386.deb

You can remove it from your system anytime using:

  dpkg -r nodejs

Abort a Git Merge

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

output of git status while having a merge conflict

Docker Error bind: address already in use

I had same problem, docker-compose down --rmi all (in the same directory where you run docker-compose up) helps

UPD: CAUTION - this will also delete the local docker images you've pulled (from comment)

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

How to convert a double to long without casting?

Simply by the following:

double d = 394.000;
long l = d * 1L;

How do I make the first letter of a string uppercase in JavaScript?

There is a very simple way to implement it by replace. For ECMAScript 6:

'foo'.replace(/^./, str => str.toUpperCase())

Result:

'Foo'

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

Convert ascii char[] to hexadecimal char[] in C

#include <stdio.h>
#include <string.h>

int main(void){
    char word[17], outword[33];//17:16+1, 33:16*2+1
    int i, len;

    printf("Intro word:");
    fgets(word, sizeof(word), stdin);
    len = strlen(word);
    if(word[len-1]=='\n')
        word[--len] = '\0';

    for(i = 0; i<len; i++){
        sprintf(outword+i*2, "%02X", word[i]);
    }
    printf("%s\n", outword);
    return 0;
}

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

Java String.split() Regex

You could also do something like:

String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");

It handles white spaces and words of variable length and produces the array:

[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]

Do you use NULL or 0 (zero) for pointers in C++?

If I recall correctly NULL is defined differently in the headers that I have used. For C it is defined as (void*)0, and for C++ it's defines as just 0. The code looked something like:

#ifndef __cplusplus
#define NULL (void*)0
#else
#define NULL 0
#endif

Personally I still use the NULL value to represent null pointers, it makes it explicit that you're using a pointer rather than some integral type. Yes internally the NULL value is still 0 but it isn't represented as such.

Additionally I don't rely on the automatic conversion of integers to boolean values but explicitly compare them.

For example prefer to use:

if (pointer_value != NULL || integer_value == 0)

rather than:

if (pointer_value || !integer_value)

Suffice to say that this is all remedied in C++11 where one can simply use nullptr instead of NULL, and also nullptr_t that is the type of a nullptr.

JavaScript: How to find out if the user browser is Chrome?

even shorter: var is_chrome = /chrome/i.test( navigator.userAgent );

Error: " 'dict' object has no attribute 'iteritems' "

I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.

mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS; 
85
Macon

Get last field using awk substr

You can also use:

    sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'

or

    sed -n 's/.*\/\([^\/]*\)$/\1/p'

How to update nested state properties in React

This is clearly not the right or best way to do, however it is cleaner to my view:

this.state.hugeNestedObject = hugeNestedObject; 
this.state.anotherHugeNestedObject = anotherHugeNestedObject; 

this.setState({})

However, React itself should iterate thought nested objects and update state and DOM accordingly which is not there yet.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Base on this I was able to solve this by changing the constructor of XmlSerializer I was using instead of changing the classes.

Instead of using something like this (suggested in the other answers):

[XmlInclude(typeof(Derived))]
public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>));
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

I did this:

public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>), new[] { typeof(Derived) });
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

How to install both Python 2.x and Python 3.x in Windows

Check your system environment variables after installing Python, python 3's directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

How to revert the last migration?

there is a good library to use its called djagno-nomad, although not directly related to the question asked, thought of sharing this,

scenario: most of the time when switching to project, we feel like it should revert our changes that we did on this current branch, that's what exactly this library does, checkout below

https://pypi.org/project/django-nomad/

How to detect if javascript files are loaded?

When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body> tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html> tag is parsed), which as you have found will not work.

If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body> tag :-)

EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.

Null check in an enhanced for loop

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : ListUtils.emptyIfNull(list1)){
    // Do your stuff
}

You can do the same null-safe check to other Collection classes with CollectionUtils.emptyIfNull.

Writing to an Excel spreadsheet

import xlwt

def output(filename, sheet, list1, list2, x, y, z):
    book = xlwt.Workbook()
    sh = book.add_sheet(sheet)

    variables = [x, y, z]
    x_desc = 'Display'
    y_desc = 'Dominance'
    z_desc = 'Test'
    desc = [x_desc, y_desc, z_desc]

    col1_name = 'Stimulus Time'
    col2_name = 'Reaction Time'

    #You may need to group the variables together
    #for n, (v_desc, v) in enumerate(zip(desc, variables)):
    for n, v_desc, v in enumerate(zip(desc, variables)):
        sh.write(n, 0, v_desc)
        sh.write(n, 1, v)

    n+=1

    sh.write(n, 0, col1_name)
    sh.write(n, 1, col2_name)

    for m, e1 in enumerate(list1, n+1):
        sh.write(m, 0, e1)

    for m, e2 in enumerate(list2, n+1):
        sh.write(m, 1, e2)

    book.save(filename)

for more explanation: https://github.com/python-excel

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

    try:
        res = math.exp(420000)
    except OverflowError:
        res = float('inf')
    

Notes

Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

How do I convert an enum to a list in C#?

This will return an IEnumerable<SomeEnum> of all the values of an Enum.

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

If you want that to be a List<SomeEnum>, just add .ToList() after .Cast<SomeEnum>().

To use the Cast function on an Array you need to have the System.Linq in your using section.

How to run single test method with phpunit?

Following command will execute exactly testSaveAndDrop test.

phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php

Padding characters in printf

Pure Bash, no external utilities

This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.

pad=$(printf '%0.1s' "-"{1..60})
padlength=40
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:

padlimit=60
pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}

So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.

Output:

a--------------------------------bbbbbbb
aa--------------------------------bbbbbb
aaaa-------------------------------bbbbb
aaaaaaaa----------------------------bbbb

Without subtracting the length of the second string:

a---------------------------------------bbbbbbb
aa--------------------------------------bbbbbb
aaaa------------------------------------bbbbb
aaaaaaaa--------------------------------bbbb

The first line could instead be the equivalent (similar to sprintf):

printf -v pad '%0.1s' "-"{1..60}

or similarly for the more dynamic technique:

printf -v pad '%*s' "$padlimit"

You can do the printing all on one line if you prefer:

printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"

ImportError: cannot import name main when running pip --version command in windows7 32 bit

This solved my problem in ubuntu 18.04 when trying to use python3.6:

rm -rf ~/.local/lib/python3.6

You can move the folder to another place using mv instead of deleting it too, for testing:

mv ~/.local/lib/python3.6 ./python3.6_old

What does %~dp0 mean, and how does it work?

Calling

for /?

in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).

In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

There are different letters you can use like f for "full path name", d for drive letter, p for path, and they can be combined. %~ is the beginning for each of those sequences and a number I denotes it works on the parameter %I (where %0 is the complete name of the batch file, just like you assumed).

Any free WPF themes?

Here's my expression dark theme for WPF controls.

How to change text color of cmd with windows batch script every 1 second

Try this script. This can write any text on any position of screen and don't use temporary files or ".com, .exe" executables. Just make shure you have the "debug.exe" executable in windows\system or windows\system32 folders.

http://pastebin.com/bzYhfLGc

@echo off
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init


:howuse ---------------------------------------------------------------

    echo ------------------
    echo ECOL.BAT - ver 1.0
    echo ------------------
    echo Print colored text in batch script
    echo Written by BrendanLS - http://640kbworld.forum.st
    echo.
    echo Syntax:
    echo ECOL.BAT [COLOR] [X] [Y] "Insert your text"
    echo COLOR value must be a hexadecimal number
    echo.
    echo Example:
    echo ECOL.BAT F0 20 30 "The 640KB World Forum"
    echo.
    echo Enjoy ;^)
    goto quit

:error ----------------------------------------------------------------

    set /a "_er=_er | (%~1)"
    goto quit

:geth -----------------------------------------------------------------

        set return=
        set bts=%~1

:hshift ---------------------------------------------------------------

        set /a "nn = bts & 0xff"
        set return=!h%nn%!%return%
        set /a "bts = bts >> 0x8"
        if %bts% gtr 0 goto hshift
        goto quit

:init -----------------------------------------------------------------

    if "%~4"=="" call :error 0xff

    (
        set /a _cl=0x%1
        call :error !errorlevel!
        set _cl=%1
        call :error "0x!_cl! ^>^> 8"
        set /a _px=%2
        call :error !errorlevel!
        set /a _py=%3
        call :error !errorlevel!
    ) 2>nul 1>&2

    if !_er! neq 0 (
        echo.
        echo ERROR: value exception "!_er!" occurred.
        echo.
        goto howuse
    )

    set nsys=0123456789abcdef
    set /a _val=-1

        for /l %%a in (0,1,15) do (
                for /l %%b in (0,1,15) do (
                        set /a "_val += 1"
                        set byte=!nsys:~%%a,1!!nsys:~%%b,1!
                        set h!_val!=!byte!
                )
        )

    set /a cnb=0
    set /a cnl=0

:parse ----------------------------------------------------------------

    set _ch=!_ln:~%_n%,1!
    if "%_ch%"=="" goto perform

    set /a "cnb += 1"
    if %cnb% gtr 7 (
        set /a cnb=0
        set /a "cnl += 1"
    )

    set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
    set /a "_n += 1"
    goto parse

:perform --------------------------------------------------------------

    set /a "in = ((_py * 160) + (_px * 2)) & 0xffff"
    call :geth %in%
    set ntr=!return!
    set /a jmp=0xe


    @for /l %%x in (0,1,%cnl%) do (
        set bl8086%%x=eb800:!ntr! !bln%%x!
        set /a "in=!jmp! + 0x!ntr!"
        call :geth !in!
        set ntr=!return!
        set /a jmp=0x10
    )

    (
    echo.%bl80860%&echo.%bl80861%&echo.%bl80862%&echo.%bl80863%&echo.%bl80864%
    echo.q
    )|debug >nul 2>&1

:quit

Get the Last Inserted Id Using Laravel Eloquent

You can get last inserted id with same object you call save method;

$data->save();
$inserted_id = $data->id;

So you can simply write:

if ($data->save()) {
    return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).

Tracking Google Analytics Page Views with AngularJS

If you are looking for full control of Google Analytics's new tracking code, you could use my very own Angular-GA.

It makes ga available through injection, so it's easy to test. It doesn't do any magic, apart from setting the path on every routeChange. You still have to send the pageview like here.

app.run(function ($rootScope, $location, ga) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview');
    });
});

Additionaly there is a directive ga which allows to bind multiple analytics functions to events, like this:

<a href="#" ga="[['set', 'metric1', 10], ['send', 'event', 'player', 'play', video.id]]"></a>

Java: Static vs inner class

An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"

A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Why do people hate SQL cursors so much?

In general, because on a relational database, the performance of code using cursors is an order of magnitude worse than set-based operations.

Simple way to encode a string according to a password?

Thanks for some great answers. Nothing original to add, but here are some progressive rewrites of qneill's answer using some useful Python facilities. I hope you agree they simplify and clarify the code.

import base64


def qneill_encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc))


def qneill_decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

enumerate()-- pair the items in a list with their index

iterate over the characters in a string

def encode_enumerate(key, clear):
    enc = []
    for i, ch in enumerate(clear):
        key_c = key[i % len(key)]
        enc_c = chr((ord(ch) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc))


def decode_enumerate(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i, ch in enumerate(enc):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(ch) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

build lists using a list comprehension

def encode_comprehension(key, clear):
    enc = [chr((ord(clear_char) + ord(key[i % len(key)])) % 256)
                for i, clear_char in enumerate(clear)]
    return base64.urlsafe_b64encode("".join(enc))


def decode_comprehension(key, enc):
    enc = base64.urlsafe_b64decode(enc)
    dec = [chr((256 + ord(ch) - ord(key[i % len(key)])) % 256)
           for i, ch in enumerate(enc)]
    return "".join(dec)

Often in Python there's no need for list indexes at all. Eliminate loop index variables entirely using zip and cycle:

from itertools import cycle


def encode_zip_cycle(key, clear):
    enc = [chr((ord(clear_char) + ord(key_char)) % 256)
                for clear_char, key_char in zip(clear, cycle(key))]
    return base64.urlsafe_b64encode("".join(enc))


def decode_zip_cycle(key, enc):
    enc = base64.urlsafe_b64decode(enc)
    dec = [chr((256 + ord(enc_char) - ord(key_char)) % 256)
                for enc_char, key_char in zip(enc, cycle(key))]
    return "".join(dec)

and some tests...

msg = 'The quick brown fox jumps over the lazy dog.'
key = 'jMG6JV3QdtRh3EhCHWUi'
print('cleartext: {0}'.format(msg))
print('ciphertext: {0}'.format(encode_zip_cycle(key, msg)))

encoders = [qneill_encode, encode_enumerate, encode_comprehension, encode_zip_cycle]
decoders = [qneill_decode, decode_enumerate, decode_comprehension, decode_zip_cycle]

# round-trip check for each pair of implementations
matched_pairs = zip(encoders, decoders)
assert all([decode(key, encode(key, msg)) == msg for encode, decode in matched_pairs])
print('Round-trips for encoder-decoder pairs: all tests passed')

# round-trip applying each kind of decode to each kind of encode to prove equivalent
from itertools import product
all_combinations = product(encoders, decoders)
assert all(decode(key, encode(key, msg)) == msg for encode, decode in all_combinations)
print('Each encoder and decoder can be swapped with any other: all tests passed')

>>> python crypt.py
cleartext: The quick brown fox jumps over the lazy dog.
ciphertext: vrWsVrvLnLTPlLTaorzWY67GzYnUwrSmvXaix8nmctybqoivqdHOic68rmQ=
Round-trips for encoder-decoder pairs: all tests passed
Each encoder and decoder can be swapped with any other: all tests passed

How to use a dot "." to access members of dictionary?

Use __getattr__, very simple, works in Python 3.4.3

class myDict(dict):
    def __getattr__(self,val):
        return self[val]


blockBody=myDict()
blockBody['item1']=10000
blockBody['item2']="StackOverflow"
print(blockBody.item1)
print(blockBody.item2)

Output:

10000
StackOverflow

How to grep Git commit diffs or contents for a certain word?

You can try the following command:

git log --patch --color=always | less +/searching_string

or using grep in the following way:

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

Run this command in the parent directory where you would like to search.

Count Vowels in String Python

What you want can be done quite simply like so:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>

In case you don't know them, here is a reference on map and one on the *.

How to read an external local JSON file in JavaScript?

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

Javascript - Track mouse position

If just want to track the mouse movement visually:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
</head>_x000D_
<style type="text/css">_x000D_
* { margin: 0; padding: 0; }_x000D_
html, body { width: 100%; height: 100%; overflow: hidden; }_x000D_
</style>_x000D_
<body>_x000D_
<canvas></canvas>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var_x000D_
canvas    = document.querySelector('canvas'),_x000D_
ctx       = canvas.getContext('2d'),_x000D_
beginPath = false;_x000D_
_x000D_
canvas.width  = window.innerWidth;_x000D_
canvas.height = window.innerHeight;_x000D_
_x000D_
document.body.addEventListener('mousemove', function (event) {_x000D_
 var x = event.clientX, y = event.clientY;_x000D_
_x000D_
 if (beginPath) {_x000D_
  ctx.lineTo(x, y);_x000D_
  ctx.stroke();_x000D_
 } else {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(x, y);_x000D_
  beginPath = true;_x000D_
 }_x000D_
}, false);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

What is the difference between required and ng-required?

AngularJS form elements look for the required attribute to perform validation functions. ng-required allows you to set the required attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)

As an example, <input required> and <input ng-required="true"> are essentially the same thing

If you are wondering why this is this way, (and not just make <input required="true"> or <input required="false">), it is due to the limitations of HTML - the required attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false" would be invalid HTML)

How can I sanitize user input with PHP?

There is the filter extension (howto-link, manual), which works pretty well with all GPC variables. It's not a magic-do-it-all thing though, you will still have to use it.

Getting Checkbox Value in ASP.NET MVC 4

For multiple checkbox with same name... Code to remove unnecessary false :

List<string> d_taxe1 = new List<string>(Request.Form.GetValues("taxe1"));
d_taxe1 = form_checkbox.RemoveExtraFalseFromCheckbox(d_taxe1);

Function

public class form_checkbox
{

    public static List<string> RemoveExtraFalseFromCheckbox(List<string> val)
    {
        List<string> d_taxe1_list = new List<string>(val);

        int y = 0;

        foreach (string cbox in val)
        {

            if (val[y] == "false")
            {
                if (y > 0)
                {
                    if (val[y - 1] == "true")
                    {
                        d_taxe1_list[y] = "remove";
                    }
                }

            }

            y++;
        }

        val = new List<string>(d_taxe1_list);

        foreach (var del in d_taxe1_list)
            if (del == "remove") val.Remove(del);

        return val;

    }      



}

Use it :

int x = 0;
foreach (var detail in d_prix){
factured.taxe1 = (d_taxe1[x] == "true") ? true : false;
x++;
}

Capture HTML Canvas as gif/jpg/png/pdf?

I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png");

You can use this to write the image to the page:

document.write('<img src="'+image+'"/>');

Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary 
var acceptedMimes = new Array();
for(i = 0; i < imageMimes.length; i++) {
    if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) {
        acceptedMimes[acceptedMimes.length] = imageMimes[i];
    }
}

You only need to run this once per page - it should never change through a page's lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really)
window.location.href = image;

If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

Writing html form data to a txt file without the use of a webserver

Something like this?

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">Please type in this box. When you 

click the Download button, the contents of this box will be downloaded to 

your machine at the location you specify. Pretty nifty. </textarea>
  <input type="submit" value="Download">
</form>
</body>
</html>

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

"Have you tried turning it off and on again?" (Roy of The IT crowd)

This happened to me today, which is why I ended up to this page. Seeing that error was weird since, recently, I have not made any changes in my Python environment. Interestingly, I observed that if I open a new notebook and import pandas I would not get the same error message. So, I did shutdown the troublesome notebook and started it again and voila it is working again!

Even though this solved the problem (at least for me), I cannot readily come up with an explanation as to why it happened in the first place!

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

Disable the postback on an <ASP:LinkButton>

Just been through this, the correct way to do it is to use:

  1. OnClientClick
  2. return false

as in the following example line of code:

<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />

Object cannot be cast from DBNull to other types

For others that arrive on this page from google:

DataRow also has a function .IsNull("ColumnName")

    public DateTime? TestDt; 
    public Parse(DataRow row)
    {
        if (!row.IsNull("TEST_DT"))
            TestDt = Convert.ToDateTime(row["TEST_DT"]);
    }

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

Replacing H1 text with a logo image: best method for SEO and accessibility?

A new (Keller) method is supposed to improve speed over the -9999px method:

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

How to pass anonymous types as parameters?

You can't pass an anonymous type to a non generic function, unless the parameter type is object.

public void LogEmployees (object obj)
{
    var list = obj as IEnumerable(); 
    if (list == null)
       return;

    foreach (var item in list)
    {

    }
}

Anonymous types are intended for short term usage within a method.

From MSDN - Anonymous Types:

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing.

(emphasis mine)


Update

You can use generics to achieve what you want:

public void LogEmployees<T>(IEnumerable<T> list)
{
    foreach (T item in list)
    {

    }
}

See line breaks and carriage returns in editor

I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :

cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF

When you're executing vim, the commands into .vimrc are executed, and you can see this example :

My line with CRLF eol here ^M¶

Jackson JSON: get node name from json-tree

This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera's answer for a version that works with newer versions of Jackson.


The JSON terms for "node name" is "key." Since JsonNode#iterator() does not include keys, you need to iterate differently:

for (Map.Entry<String, JsonNode> elt : rootNode.fields())
{
    if ("foo".equals(elt.getKey()))
    {
        // bar
    }
}

If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames():

for (String key : rootNode.fieldNames())
{
    if ("foo".equals(key))
    {
        // bar
    }
}

And if you just want to find the node with key "foo", you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:

JsonNode foo = rootNode.get("foo");
if (foo != null)
{
    // frob that widget
}

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

Getting the base url of the website and globally passing it to twig in Symfony 2

This is now available for free in twig templates (tested on sf2 version 2.0.14)

{{ app.request.getBaseURL() }}

In later Symfony versions (tested on 2.5), try :

{{ app.request.getSchemeAndHttpHost() }}

When to use @QueryParam vs @PathParam

Before talking about QueryParam & PathParam. Let's first understand the URL & its components. URL consists of endpoint + resource + queryParam/ PathParam.

For Example,

URL: https://app.orderservice.com/order?order=12345678

or

URL: https://app.orderservice.com/orders/12345678

where

endpoint: https://app.orderservice.com

resource: orders

queryParam: order=12345678

PathParam: 12345678

@QueryParam:

QueryParam is used when the requirement is to filter the request based on certain criteria/criterias. The criteria is specified with ? after the resource in URL. Multiple filter criterias can be specified in the queryParam by using & symbol.

For Example:

https://app.orderservice.com/orders?order=12345678 & customername=X

@PathParam:

PathParam is used when the requirement is to select the particular order based on guid/id. PathParam is the part of the resource in URL.

For Example:

https://app.orderservice.com/orders/12345678

Add disabled attribute to input element using Javascript

Working code from my sources:

HTML WORLD

<select name="select_from" disabled>...</select>

JS WORLD

var from = jQuery('select[name=select_from]');

//add disabled
from.attr('disabled', 'disabled');



//remove it
from.removeAttr("disabled");

Convert columns to string in Pandas

Using .apply() with a lambda conversion function also works in this case:

total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))

For entire dataframes you can use .applymap(). (but in any case probably .astype() is faster)

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

django templates: include and extends

Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.

css label width not taking effect

I believe labels are inline, and so they don't take a width. Maybe try using "display: block" and going from there.

Right way to split an std::string into a vector<string>

Tweaked version from Techie Delight:

#include <string>
#include <vector>

std::vector<std::string> split(const std::string& str, char delim) {
    std::vector<std::string> strings;
    size_t start;
    size_t end = 0;
    while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
        end = str.find(delim, start);
        strings.push_back(str.substr(start, end - start));
    }
    return strings;
}

css transition opacity fade background

http://jsfiddle.net/6xJQq/13/

.container {
    display: inline-block;
    padding: 5px; /*included padding to see background when img apacity is 100%*/
    background-color: black;
    opacity: 1;
}

.container:hover {
    background-color: red;
}

img {
    opacity: 1;
}

img:hover {
    opacity: 0.7;
}

.transition {
    transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -webkit-transition: all .25s  ease-in-out;
}

What is the pythonic way to detect the last element in a 'for' loop?

So, this is definitely not the "shorter" version - and one might digress if "shortest" and "Pythonic" are actually compatible.

But if one needs this pattern often, just put the logic in to a 10-liner generator - and get any meta-data related to an element's position directly on the for call. Another advantage here is that it will work wit an arbitrary iterable, not only Sequences.

_sentinel = object()

def iter_check_last(iterable):
    iterable = iter(iterable)
    current_element = next(iterable, _sentinel)
    while current_element is not _sentinel:
        next_element = next(iterable, _sentinel)
        yield (next_element is _sentinel, current_element)
        current_element = next_element
In [107]: for is_last, el in iter_check_last(range(3)):
     ...:     print(is_last, el)
     ...: 
     ...: 
False 0
False 1
True 2

Visual Studio can't build due to rc.exe

I'm on Windows 10 x64 and Visual Studio 2017. I copied and pasted rc.exe and rcdll.dll from:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

to

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64

it's works with: ( qt creator 5.7.1)

Ternary operator ?: vs if...else

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

Convert timestamp to readable date/time PHP

I just added H:i:s to Rocket's answer to get the time along with the date.

echo date('m/d/Y H:i:s', 1299446702);

Output: 03/06/2011 16:25:02

Can jQuery get all CSS styles associated with an element?

Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.

Open Url in default web browser

In React 16.8+, using functional components, you would do

import React from 'react';
import { Button, Linking } from 'react-native';

const ExternalLinkBtn = (props) => {
  return <Button
            title={props.title}
            onPress={() => {
                Linking.openURL(props.url)
                .catch(err => {
                    console.error("Failed opening page because: ", err)
                    alert('Failed to open page')
                })}}
          />
}

export default function exampleUse() {
  return (
    <View>
      <ExternalLinkBtn title="Example Link" url="https://example.com" />
    </View>
  )
}

Javascript Date - set just the date, ignoring time?

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs


Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

How can I truncate a string to the first 20 words in PHP?

I made my function:

function summery($text, $limit) {
    $words=preg_split('/\s+/', $text);
     $count=count(preg_split('/\s+/', $text));
      if ($count > $limit) {
          $text=NULL;
          for($i=0;$i<$limit;$i++)
              $text.=$words[$i].' ';
          $text.='...';
      }
      return $text;
    }

Warning: implode() [function.implode]: Invalid arguments passed

You are getting the error because $ret is not an array.

To get rid of the error, at the start of your function, define it with this line: $ret = array();

It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.

How do you unit test private methods?

For JAVA language

Here, you can over-ride a particular method of the testing class with mock behavior.

For the below code:

public class ClassToTest 
{
    public void methodToTest()
    {
        Integer integerInstance = new Integer(0);
        boolean returnValue= methodToMock(integerInstance);
        if(returnValue)
        {
            System.out.println("methodToMock returned true");
        }
        else
        {
            System.out.println("methodToMock returned true");
        }
        System.out.println();
    }
    private boolean methodToMock(int value)
    {
        return true;
    }
}

Test class would be:

public class ClassToTestTest{

    @Test
    public void testMethodToTest(){

        new Mockup<ClassToTest>(){
            @Mock
            private boolean methodToMock(int value){
                return true;
            }
        };

        ....    

    }
}

Passing $_POST values with cURL

Check out the cUrl PHP documentation page. It will help much more than just with example scripts.

How do I make a relative reference to another workbook in Excel?

Using =worksheetname() and =Indirect() function, and naming the worksheets in the parent Excel file with the name of the externally referenced Excel file. Each externally referenced excel file were in their own folders with same name. These sub-folders were only to create more clarity.


What I did was as follows:-

|----Column B---------------|----Column C------------|

R2) Parent folder --------> "C:\TEMP\Excel\"

R3) Sub folder name ---> =worksheetname()

R5) Full path --------------> ="'"&C2&C3&"["&C3&".xlsx]Sheet1'!$A$1"

R7) Indirect function-----> =INDIRECT(C5,TRUE)

In the main file, I had say, 5 worksheets labeled as Ext-1, Ext-2, Ext-3, Ext-4, Ext-5. Copy pasted the above formulas into all the five worksheets. Opened all the respectively named Excel files in the background. For some reason the results were not automatically computing, hence had to force a change by editing any cell. Volla, the value in cell A1 of each externally referenced Excel file were in the Main file.

How to get AM/PM from a datetime in PHP

<?php 
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata')); 
echo $dateTime->format("d/m/y  H:i A"); 
?>

You can use this to display the date like this

22/06/15 10:46 AM

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

sudo yum update openssl is all you need.

This will bring you up to openssl-1.0.1e-16.el6_5.7.

You need to restart Apache after the update. Or better yet, reboot the box if possible, so that all applications that use OpenSSL will load the new version.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I had the same problem in Xcode 8.1 and iOS 10.1. What worked for me was going into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH with the path where you have extracted glib.

export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH

This should keep you safe from bricking your CentOS*.

*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.