Programs & Examples On #Code swarm

Evenly distributing n points on a sphere

This is known as packing points on a sphere, and there is no (known) general, perfect solution. However, there are plenty of imperfect solutions. The three most popular seem to be:

  1. Create a simulation. Treat each point as an electron constrained to a sphere, then run a simulation for a certain number of steps. The electrons' repulsion will naturally tend the system to a more stable state, where the points are about as far away from each other as they can get.
  2. Hypercube rejection. This fancy-sounding method is actually really simple: you uniformly choose points (much more than n of them) inside of the cube surrounding the sphere, then reject the points outside of the sphere. Treat the remaining points as vectors, and normalize them. These are your "samples" - choose n of them using some method (randomly, greedy, etc).
  3. Spiral approximations. You trace a spiral around a sphere, and evenly-distribute the points around the spiral. Because of the mathematics involved, these are more complicated to understand than the simulation, but much faster (and probably involving less code). The most popular seems to be by Saff, et al.

A lot more information about this problem can be found here

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Update to Tomcat 7.0.58 (or newer).

See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16

The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.

How to replace list item in best way

i find best for do it fast and simple

  1. find ur item in list

    var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
    
  2. make clone from current

    OrderDetail dd = d;
    
  3. Update ur clone

    dd.Quantity++;
    
  4. find index in list

    int idx = Details.IndexOf(d);
    
  5. remove founded item in (1)

      Details.Remove(d);
    
  6. insert

     if (idx > -1)
          Details.Insert(idx, dd);
      else
          Details.Insert(Details.Count, dd);
    

Is it possible to run one logrotate check manually?

Edit /var/lib/logrotate.status (or /var/lib/loglogrotate/logrotate.status) to reset the 'last rotated' date on the log file you want to test.

Then run logrotate YOUR_CONFIG_FILE.

Or you can use the --force flag, but editing logrotate.status gives you more precision over what does and doesn't get rotated.

Boolean vs boolean in Java

You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

  1. With primitives you guarantee that you will not pass null values.
    You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):

    public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans

How to load a model from an HDF5 file in Keras?

According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras

you can do :

first test if you have h5py installed by running the

import h5py

if you dont have errors while importing h5py you are good to save:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

If you need to install h5py http://docs.h5py.org/en/latest/build.html

Difference between JOIN and INNER JOIN

As the other answers already state there is no difference in your example.

The relevant bit of grammar is documented here

<join_type> ::= 
    [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
    JOIN

Showing that all are optional. The page further clarifies that

INNER Specifies all matching pairs of rows are returned. Discards unmatched rows from both tables. When no join type is specified, this is the default.

The grammar does also indicate that there is one time where the INNER is required though. When specifying a join hint.

See the example below

CREATE TABLE T1(X INT);
CREATE TABLE T2(Y INT);

SELECT *
FROM   T1
       LOOP JOIN T2
         ON X = Y;

SELECT *
FROM   T1
       INNER LOOP JOIN T2
         ON X = Y;

enter image description here

ASP.Net MVC 4 Form with 2 submit buttons/actions

_x000D_
_x000D_
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
_x000D_
_x000D_

write the following code in Controler.

[HttpPost]
        public ActionResult Login(string button)
        {
            switch (button)
            {
                case "Create":
                    return RedirectToAction("Deshboard", "Home");
                    break;
                case "Reset":
                    return RedirectToAction("Login", "Home");
                    break;
            }

            return View();
        }

Deleting multiple elements from a list

I'm a total beginner in Python, and my programming at the moment is crude and dirty to say the least, but my solution was to use a combination of the basic commands I learnt in early tutorials:

some_list = [1,2,3,4,5,6,7,8,10]
rem = [0,5,7]

for i in rem:
    some_list[i] = '!' # mark for deletion

for i in range(0, some_list.count('!')):
    some_list.remove('!') # remove
print some_list

Obviously, because of having to choose a "mark-for-deletion" character, this has its limitations.

As for the performance as the size of the list scales, I'm sure that my solution is sub-optimal. However, it's straightforward, which I hope appeals to other beginners, and will work in simple cases where some_list is of a well-known format, e.g., always numeric...

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

I would just do:

private static Timer timer;
 private static void Main()
 {
   timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
   Console.ReadLine();
 }

  private static void OnCallBack()
  {
    timer.Dispose();
    Thread.Sleep(3000); //doing some long operation
    timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
  }

And ignore the period parameter, since you're attempting to control the periodicy yourself.


Your original code is running as fast as possible, since you keep specifying 0 for the dueTime parameter. From Timer.Change:

If dueTime is zero (0), the callback method is invoked immediately.

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

How to split a string between letters and digits (or between digits and letters)?

Wouldn't this "d+|D+" do the job instead of the cumbersome: "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)" ?

'Source code does not match the bytecode' when debugging on a device

This can also happen in case you have enabled ProGuard. In buildTypes set minifyEnabled false, shrinkResources false, useProguard false

Get integer value from string in swift

Swift 2.0 you can initialize Integer using constructor

var stringNumber = "1234"
var numberFromString = Int(stringNumber)

MSSQL Select statement with incremental integer column... not from a table

Try ROW_NUMBER()

http://msdn.microsoft.com/en-us/library/ms186734.aspx

Example:

SELECT
  col1,
  col2,
  ROW_NUMBER() OVER (ORDER BY col1) AS rownum
FROM tbl

Loop through all nested dictionary values?

As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.

Something like :

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))

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

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:

str(tdate.time())[0:5]

What is the purpose of meshgrid in Python / NumPy?

Actually the purpose of np.meshgrid is already mentioned in the documentation:

np.meshgrid

Return coordinate matrices from coordinate vectors.

Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.

So it's primary purpose is to create a coordinates matrices.

You probably just asked yourself:

Why do we need to create coordinate matrices?

The reason you need coordinate matrices with Python/NumPy is that there is no direct relation from coordinates to values, except when your coordinates start with zero and are purely positive integers. Then you can just use the indices of an array as the index. However when that's not the case you somehow need to store coordinates alongside your data. That's where grids come in.

Suppose your data is:

1  2  1
2  5  2
1  2  1

However, each value represents a 3 x 2 kilometer area (horizontal x vertical). Suppose your origin is the upper left corner and you want arrays that represent the distance you could use:

import numpy as np
h, v = np.meshgrid(np.arange(3)*3, np.arange(3)*2)

where v is:

array([[0, 0, 0],
       [2, 2, 2],
       [4, 4, 4]])

and h:

array([[0, 3, 6],
       [0, 3, 6],
       [0, 3, 6]])

So if you have two indices, let's say x and y (that's why the return value of meshgrid is usually xx or xs instead of x in this case I chose h for horizontally!) then you can get the x coordinate of the point, the y coordinate of the point and the value at that point by using:

h[x, y]    # horizontal coordinate
v[x, y]    # vertical coordinate
data[x, y]  # value

That makes it much easier to keep track of coordinates and (even more importantly) you can pass them to functions that need to know the coordinates.

A slightly longer explanation

However, np.meshgrid itself isn't often used directly, mostly one just uses one of similar objects np.mgrid or np.ogrid. Here np.mgrid represents the sparse=False and np.ogrid the sparse=True case (I refer to the sparse argument of np.meshgrid). Note that there is a significant difference between np.meshgrid and np.ogrid and np.mgrid: The first two returned values (if there are two or more) are reversed. Often this doesn't matter but you should give meaningful variable names depending on the context.

For example, in case of a 2D grid and matplotlib.pyplot.imshow it makes sense to name the first returned item of np.meshgrid x and the second one y while it's the other way around for np.mgrid and np.ogrid.

np.ogrid and sparse grids

>>> import numpy as np
>>> yy, xx = np.ogrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])
       

As already said the output is reversed when compared to np.meshgrid, that's why I unpacked it as yy, xx instead of xx, yy:

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), sparse=True)
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])

This already looks like coordinates, specifically the x and y lines for 2D plots.

Visualized:

yy, xx = np.ogrid[-5:6, -5:6]
plt.figure()
plt.title('ogrid (sparse meshgrid)')
plt.grid()
plt.xticks(xx.ravel())
plt.yticks(yy.ravel())
plt.scatter(xx, np.zeros_like(xx), color="blue", marker="*")
plt.scatter(np.zeros_like(yy), yy, color="red", marker="x")

enter image description here

np.mgrid and dense/fleshed out grids

>>> yy, xx = np.mgrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])
       

The same applies here: The output is reversed compared to np.meshgrid:

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6))
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])
       

Unlike ogrid these arrays contain all xx and yy coordinates in the -5 <= xx <= 5; -5 <= yy <= 5 grid.

yy, xx = np.mgrid[-5:6, -5:6]
plt.figure()
plt.title('mgrid (dense meshgrid)')
plt.grid()
plt.xticks(xx[0])
plt.yticks(yy[:, 0])
plt.scatter(xx, yy, color="red", marker="x")

enter image description here

Functionality

It's not only limited to 2D, these functions work for arbitrary dimensions (well, there is a maximum number of arguments given to function in Python and a maximum number of dimensions that NumPy allows):

>>> x1, x2, x3, x4 = np.ogrid[:3, 1:4, 2:5, 3:6]
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
x1
array([[[[0]]],


       [[[1]]],


       [[[2]]]])
x2
array([[[[1]],

        [[2]],

        [[3]]]])
x3
array([[[[2],
         [3],
         [4]]]])
x4
array([[[[3, 4, 5]]]])

>>> # equivalent meshgrid output, note how the first two arguments are reversed and the unpacking
>>> x2, x1, x3, x4 = np.meshgrid(np.arange(1,4), np.arange(3), np.arange(2, 5), np.arange(3, 6), sparse=True)
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
# Identical output so it's omitted here.

Even if these also work for 1D there are two (much more common) 1D grid creation functions:

Besides the start and stop argument it also supports the step argument (even complex steps that represent the number of steps):

>>> x1, x2 = np.mgrid[1:10:2, 1:10:4j]
>>> x1  # The dimension with the explicit step width of 2
array([[1., 1., 1., 1.],
       [3., 3., 3., 3.],
       [5., 5., 5., 5.],
       [7., 7., 7., 7.],
       [9., 9., 9., 9.]])
>>> x2  # The dimension with the "number of steps"
array([[ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.]])
       

Applications

You specifically asked about the purpose and in fact, these grids are extremely useful if you need a coordinate system.

For example if you have a NumPy function that calculates the distance in two dimensions:

def distance_2d(x_point, y_point, x, y):
    return np.hypot(x-x_point, y-y_point)
    

And you want to know the distance of each point:

>>> ys, xs = np.ogrid[-5:5, -5:5]
>>> distances = distance_2d(1, 2, xs, ys)  # distance to point (1, 2)
>>> distances
array([[9.21954446, 8.60232527, 8.06225775, 7.61577311, 7.28010989,
        7.07106781, 7.        , 7.07106781, 7.28010989, 7.61577311],
       [8.48528137, 7.81024968, 7.21110255, 6.70820393, 6.32455532,
        6.08276253, 6.        , 6.08276253, 6.32455532, 6.70820393],
       [7.81024968, 7.07106781, 6.40312424, 5.83095189, 5.38516481,
        5.09901951, 5.        , 5.09901951, 5.38516481, 5.83095189],
       [7.21110255, 6.40312424, 5.65685425, 5.        , 4.47213595,
        4.12310563, 4.        , 4.12310563, 4.47213595, 5.        ],
       [6.70820393, 5.83095189, 5.        , 4.24264069, 3.60555128,
        3.16227766, 3.        , 3.16227766, 3.60555128, 4.24264069],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.        , 5.        , 4.        , 3.        , 2.        ,
        1.        , 0.        , 1.        , 2.        , 3.        ],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128]])
        

The output would be identical if one passed in a dense grid instead of an open grid. NumPys broadcasting makes it possible!

Let's visualize the result:

plt.figure()
plt.title('distance to point (1, 2)')
plt.imshow(distances, origin='lower', interpolation="none")
plt.xticks(np.arange(xs.shape[1]), xs.ravel())  # need to set the ticks manually
plt.yticks(np.arange(ys.shape[0]), ys.ravel())
plt.colorbar()

enter image description here

And this is also when NumPys mgrid and ogrid become very convenient because it allows you to easily change the resolution of your grids:

ys, xs = np.ogrid[-5:5:200j, -5:5:200j]
# otherwise same code as above

enter image description here

However, since imshow doesn't support x and y inputs one has to change the ticks by hand. It would be really convenient if it would accept the x and y coordinates, right?

It's easy to write functions with NumPy that deal naturally with grids. Furthermore, there are several functions in NumPy, SciPy, matplotlib that expect you to pass in the grid.

I like images so let's explore matplotlib.pyplot.contour:

ys, xs = np.mgrid[-5:5:200j, -5:5:200j]
density = np.sin(ys)-np.cos(xs)
plt.figure()
plt.contour(xs, ys, density)

enter image description here

Note how the coordinates are already correctly set! That wouldn't be the case if you just passed in the density.

Or to give another fun example using astropy models (this time I don't care much about the coordinates, I just use them to create some grid):

from astropy.modeling import models
z = np.zeros((100, 100))
y, x = np.mgrid[0:100, 0:100]
for _ in range(10):
    g2d = models.Gaussian2D(amplitude=100, 
                           x_mean=np.random.randint(0, 100), 
                           y_mean=np.random.randint(0, 100), 
                           x_stddev=3, 
                           y_stddev=3)
    z += g2d(x, y)
    a2d = models.AiryDisk2D(amplitude=70, 
                            x_0=np.random.randint(0, 100), 
                            y_0=np.random.randint(0, 100), 
                            radius=5)
    z += a2d(x, y)
    

enter image description here

Although that's just "for the looks" several functions related to functional models and fitting (for example scipy.interpolate.interp2d, scipy.interpolate.griddata even show examples using np.mgrid) in Scipy, etc. require grids. Most of these work with open grids and dense grids, however some only work with one of them.

Declare global variables in Visual Studio 2010 and VB.NET

The first guy with a public class makes a lot more sense. The original guy has multiple forms and if global variables are needed then the global class will be better. Think of someone coding behind him and needs to use a global variable in a class you have IntelliSense, it will also make coding a modification 6 months later a lot easier.

Also if I have a brain fart and use like in an example parts on a module level then want my global parts I can do something like

Dim Parts as Integer
parts = 3
GlobalVariables.parts += Parts  '< Not recommended but it works

At least that's why I would go the class route.

Best way to incorporate Volley (or other library) into Android Studio project

I have set up Volley as a separate Project. That way its not tied to any project and exist independently.

I also have a Nexus server (Internal repo) setup so I can access volley as
compile 'com.mycompany.volley:volley:1.0.4' in any project I need.

Any time I update Volley project, I just need to change the version number in other projects.

I feel very comfortable with this approach.

Correct use for angular-translate in controllers

Recommended: don't translate in the controller, translate in your view

I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:

<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>

Using the provided service

Angular Translate provides the $translate service which you can use in your Controllers.

An example usage of the $translate service can be:

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $translate('PAGE.TITLE')
        .then(function (translatedValue) {
            $scope.pageTitle = translatedValue;
        });
});

The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant():

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

The downside with using $translate.instant() could be that the language file isn't loaded yet if you are loading it async.

Using the provided filter

This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.

.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
    var $translate = $filter('translate');

    $scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

Using the provided directive

Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

For anybody reading this in the future, here is a simpler answer:

var s = "11:41:02PM";
var time = s.match(/\d{2}/g);
if (time[0] === "12") time[0] = "00";
if (s.indexOf("PM") > -1) time[0] = parseInt(time[0])+12;
return time.join(":");

What's the difference between Invoke() and BeginInvoke()

Just adding why and when to use Invoke().

Both Invoke() and BeginInvoke() marshal the code you specify to the dispatcher thread.

But unlike BeginInvoke(), Invoke() stalls your thread until the dispatcher executes your code. You might want to use Invoke() if you need to pause an asynchronous operation until the user has supplied some sort of feedback.

For example, you could call Invoke() to run a snippet of code that shows an OK/Cancel dialog box. After the user clicks a button and your marshaled code completes, the invoke() method will return, and you can act upon the user's response.

See Pro WPF in C# chapter 31

Which ORM should I use for Node.js and MySQL?

One major difference between Sequelize and Persistence.js is that the former supports a STRING datatype, i.e. VARCHAR(255). I felt really uncomfortable making everything TEXT.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

It may be useful for someone, so I'll post it here. I was missing this dependency on my pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Numpy matrix to array

First, Mv = numpy.asarray(M.T), which gives you a 4x1 but 2D array.

Then, perform A = Mv[0,:], which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:].

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

How do I make a MySQL database run completely in memory?

If your database is small enough (or if you add enough memory) your database will effectively run in memory since it your data will be cached after the first request.

Changing the database table definitions to use the memory engine is probably more complicated than you need.

If you have enough memory to load the tables into memory with the MEMORY engine, you have enough to tune the innodb settings to cache everything anyway.

How to launch multiple Internet Explorer windows/tabs from batch file?

You can use either of these two scripts to open the URLs in separate tabs in a (single) new IE window. You can call either of these scripts from within your batch script (or at the command prompt):

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var intArrUBound = 0;
var navFlags = navOpenInBackgroundTab;
var arrstrUrl = new Array(3);
var objIE;

    intArrUBound = arrstrUrl.length;

    arrstrUrl[0] = "http://bing.com/";
    arrstrUrl[1] = "http://google.com/";
    arrstrUrl[2] = "http://msn.com/";
    arrstrUrl[3] = "http://yahoo.com/";

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(arrstrUrl[0]);

    for (intLoop=1;intLoop<=intArrUBound;intLoop++) {

        objIE.Navigate2(arrstrUrl[intLoop], navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop       : intLoop = 0
Dim intArrUBound  : intArrUBound = 0
Dim navFlags      : navFlags = navOpenInBackgroundTab

Dim arrstrUrl(3)
Dim objIE

    intArrUBound = UBound(arrstrUrl)

    arrstrUrl(0) = "http://bing.com/"
    arrstrUrl(1) = "http://google.com/"
    arrstrUrl(2) = "http://msn.com/"
    arrstrUrl(3) = "http://yahoo.com/"

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 arrstrUrl(0)

    For intLoop = 1 to intArrUBound

        objIE.Navigate2 arrstrUrl(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


Once you decide on "JavaScript" or "VB Script", you have a few choices:

If your URLs are static:

1) You could write the "JS/VBS" script file (above) and then just call it from a batch script.

From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.vbs
cscript //nologo urls.js


If the URLs change infrequently:

2) You could have the batch script write the "JS/VBS" script on the fly and then call it.


If the URLs could be different each time:

3) Use the "JS/VBS" scripts (below) and pass the URLs of the pages to open as command line arguments:

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var navFlags = navOpenInBackgroundTab;
var objIE;
var intArgsLength = WScript.Arguments.Length;

    if (intArgsLength == 0) {

        WScript.Echo("Missing parameters");
        WScript.Quit(1);

    }

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(WScript.Arguments(0));

    for (intLoop=1;intLoop<intArgsLength;intLoop++) {

        objIE.Navigate2(WScript.Arguments(intLoop), navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop
Dim navFlags      : navFlags = navOpenInBackgroundTab
Dim objIE

    If WScript.Arguments.Count = 0 Then

        WScript.Echo "Missing parameters"
        WScript.Quit(1)

    End If

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 WScript.Arguments(0)

    For intLoop = 1 to (WScript.Arguments.Count-1)

        objIE.Navigate2 WScript.Arguments(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


If the script is called without any parameters, these will return %errorlevel%=1, otherwise they will return %errorlevel%=0. No checking is done regarding the "validity" or "availability" of any of the URLs.


From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.js "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"
cscript //nologo urls.vbs "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"

OR even:

cscript //nologo urls.js "bing.com" "google.com" "msn.com" "yahoo.com"
cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"


If for some reason, you wanted to run these with "wscript" instead, remember to use "start /w" so the exit codes (%errorlevel%) will be returned to your batch script:

start /w "" wscript //nologo urls.js "url1" "url2" ...
start /w "" wscript //nologo urls.vbs "url1" "url2" ...


Edit: 21-Sep-2016

There has been a comment that my solution is too complicated. I disagree. You pick the JavaScript solution, or the VB Script solution (not both), and each is only about 10 lines of actual code (less if you eliminate the error checking/reporting), plus a few lines to initialize constants and variables.

Once you have decided (JS or VB), you write that script one time, and then you call that script from batch, passing the URLs, anytime you want to use it, like:

cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"

The reason I wrote this answer, is because all the other answers, which work for some people, will fail to work for others, depending on:

  1. The current Internet Explorer settings for "open popups in a new tab", "open in current/new window/tab", etc... Assuming you already have those setting set how you like them for general browsing, most people would find it undesirable to have change those settings back and forth in order to make the script work.
  2. Their behavior is (can be) inconsistent depending on whether or not there was an IE window already open before the "new" links were opened. If there was an IE window (perhaps with many open tabs) already open, then all the new tabs would be added there as well. This might not be desired.

The solution I provided doesn't have these issues and should behave the same, regardless of any IE Settings or any existing IE Windows. (Please let me know if I'm wrong about this and I'll try to address it.)

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

Enable Hibernate logging

Hibernate logging has to be also enabled in hibernate configuration.

Add lines

hibernate.show_sql=true
hibernate.format_sql=true

either to

server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml

or to application's persistence.xml in <persistence-unit><properties> tag.

Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.

There is an alternative way of using log4jdbc for any kind of sql logging.

The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.

Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:

   <logger category="org.hibernate">
     <level name="DEBUG"/>
   </logger>

Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.

If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

It seems that Firefox gets installed in the App data folder Path C:\Users\users\AppData\Local\Mozilla Firefox

So you can set the firefox bin property as below

System.setProperty("webdriver.firefox.bin", "C:\\Users\\*USERNAME*\\AppData\\Local\\Mozilla Firefox\\Firefox.exe");

Adding this resolved the issue for me

Use of alloc init instead of new

+new is equivalent to +alloc/-init in Apple's NSObject implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new.

How to delete columns in pyspark dataframe

Adding to @Patrick's answer, you can use the following to drop multiple columns

columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)

Bootstrap 3: pull-right for col-lg only

.pull-right-not-xs, .pull-right-not-sm, .pull-right-not-md, .pull-right-not-lg{
    float: right;
}

.pull-left-not-xs, .pull-left-not-sm, .pull-left-not-md, .pull-left-not-lg{
    float: left;
}
@media (max-width: 767px) {    
    .pull-right-not-xs, .pull-left-not-xs{
        float: none;
    }
    .pull-right-xs {
        float: right;
    }
    .pull-left-xs {
        float: left;
    }
}
@media (min-width: 768px) and (max-width: 991px) {
    .pull-right-not-sm, .pull-left-not-sm{
        float: none;
    }
    .pull-right-sm {
        float: right;
    }
    .pull-left-sm {
        float: left;
    }
}
@media (min-width: 992px) and (max-width: 1199px) {
    .pull-right-not-md, .pull-left-not-md{
        float: none;
    }
    .pull-right-md {
        float: right;
    }
    .pull-left-md {
        float: left;
    }
}
@media (min-width: 1200px) {
    .pull-right-not-lg, .pull-left-not-lg{
        float: none;
    }
    .pull-right-lg {
        float: right;
    }
    .pull-left-lg {
        float: left;
    }
}

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

How to show Page Loading div until the page has finished loading?

I have another below simple solution for this which perfectly worked for me.

First of all, create a CSS with name Lockon class which is transparent overlay along with loading GIF as shown below

.LockOn {
    display: block;
    visibility: visible;
    position: absolute;
    z-index: 999;
    top: 0px;
    left: 0px;
    width: 105%;
    height: 105%;
    background-color:white;
    vertical-align:bottom;
    padding-top: 20%; 
    filter: alpha(opacity=75); 
    opacity: 0.75; 
    font-size:large;
    color:blue;
    font-style:italic;
    font-weight:400;
    background-image: url("../Common/loadingGIF.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}

Now we need to create our div with this class which cover entire page as an overlay whenever the page is getting loaded

<div id="coverScreen"  class="LockOn">
</div>

Now we need to hide this cover screen whenever the page is ready and so that we can restrict the user from clicking/firing any event until the page is ready

$(window).on('load', function () {
$("#coverScreen").hide();
});

Above solution will be fine whenever the page is loading.

Now the question is after the page is loaded, whenever we click a button or an event which will take a long time, we need to show this in the client click event as shown below

$("#ucNoteGrid_grdViewNotes_ctl01_btnPrint").click(function () {
$("#coverScreen").show();
});

That means when we click this print button (which will take a long time to give the report) it will show our cover screen with GIF which gives this result and once the page is ready above windows on load function will fire and which hide the cover screen once the screen is fully loaded.

How to make div same height as parent (displayed as table-cell)

You have to set the height for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):

.child {
  width: 30px;
  background-color: red;
  display: table-cell;
  vertical-align: top;
  position:relative;
}

.content {
  position:absolute;
  top:0;
  bottom:0;
  width:100%;
  background-color: blue;
}

Fiddle

How to recompile with -fPIC

Before compiling make sure that "rules.mk" file is included properly in Makefile or include it explicitly by:

"source rules.mk"

String literals and escape characters in postgresql

I find it highly unlikely for Postgres to truncate your data on input - it either rejects it or stores it as is.

milen@dev:~$ psql
Welcome to psql 8.2.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

milen=> create table EscapeTest (text varchar(50));
CREATE TABLE
milen=> insert into EscapeTest (text) values ('This will be inserted \n This will not be');
WARNING:  nonstandard use of escape in a string literal
LINE 1: insert into EscapeTest (text) values ('This will be inserted...
                                              ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
INSERT 0 1
milen=> select * from EscapeTest;
          text
------------------------
 This will be inserted
  This will not be
(1 row)

milen=>

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

Input placeholders for Internet Explorer

In looking at the "Web Forms : input placeholder" section of HTML5 Cross Browser Polyfills, one I saw was jQuery-html5-placeholder.

I tried the demo out with IE9, and it looks like it wraps your <input> with a span and overlays a label with the placeholder text.

<label>Text:
  <span style="position: relative;">
    <input id="placeholder1314588474481" name="text" maxLength="6" type="text" placeholder="Hi Mom">
    <label style="font: 0.75em/normal sans-serif; left: 5px; top: 3px; width: 147px; height: 15px; color: rgb(186, 186, 186); position: absolute; overflow-x: hidden; font-size-adjust: none; font-stretch: normal;" for="placeholder1314588474481">Hi Mom</label>
  </span>
</label>

There are also other shims there, but I didn't look at them all. One of them, Placeholders.js, advertises itself as "No dependencies (so no need to include jQuery, unlike most placeholder polyfill scripts)."

Edit: For those more interested in "how" that "what", How to create an advanced HTML5 placeholder polyfill which walks through the process of creating a jQuery plugin that does this.

Also, see keep placeholder on focus in IE10 for comments on how placeholder text disappears on focus with IE10, which differs from Firefox and Chrome. Not sure if there is a solution for this problem.

Java JDBC connection status

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.

Month name as a string

For getting month in string variable use the code below

For example the month of September:

M -> 9

MM -> 09

MMM -> Sep

MMMM -> September

String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())

Collection was modified; enumeration operation may not execute

The accepted answer is imprecise and incorrect in the worst case . If changes are made during ToList(), you can still end up with an error. Besides lock, which performance and thread-safety needs to be taken into consideration if you have a public member, a proper solution can be using immutable types.

In general, an immutable type means that you can't change the state of it once created. So your code should look like:

public class SubscriptionServer : ISubscriptionServer
{
    private static ImmutableDictionary<Guid, Subscriber> subscribers = ImmutableDictionary<Guid, Subscriber>.Empty;
    public void SubscribeEvent(string id)
    {
        subscribers = subscribers.Add(Guid.NewGuid(), new Subscriber());
    }
    public void NotifyEvent()
    {
        foreach(var sub in subscribers.Values)
        {
            //.....This is always safe
        }
    }
    //.........
}

This can be especially useful if you have a public member. Other classes can always foreach on the immutable types without worrying about the collection being modified.

Git commit -a "untracked files"?

For others having the same problem, try running

git add . which will add all files of the current directory to track (including untracked) and then use

git commit -a to commit all tracked files.

As suggested by @Pacerier, one liner that does the same thing is

git add -A

Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.

JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.

setTimeout(myFunction, 3000);

// if you have defined a function named myFunction 
// it will run after 3 seconds (3000 milliseconds)

Remember, this is completely different from how sleep method, if it existed, would behave.

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.

function test2()
{
    // defer the execution of anonymous function for 
    // 3 seconds and go to next line of code.
    setTimeout(function(){ 

        alert('hello');
    }, 3000);  

    alert('hi');
}

If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

Is there any way to delete local commits in Mercurial?

You can get around this even more easily with the Rebase extension, just use hg pull --rebase and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

hadoop No FileSystem for scheme: file

I also came across similar issue. Added core-site.xml and hdfs-site.xml as resources of conf (object)

Configuration conf = new Configuration(true);    
conf.addResource(new Path("<path to>/core-site.xml"));
conf.addResource(new Path("<path to>/hdfs-site.xml"));

Also edited version conflicts in pom.xml. (e.g. If configured version of hadoop is 2.8.1, but in pom.xml file, dependancies has version 2.7.1, then change that to 2.8.1) Run Maven install again.

This solved error for me.

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

Better way to set distance between flexbox items

_x000D_
_x000D_
#box {_x000D_
  display: flex;_x000D_
  width: 100px;_x000D_
}_x000D_
.item {_x000D_
  background: gray;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
/* u mean utility */_x000D_
.u-gap-10 > *:not(:last-child) {_x000D_
  margin-right: 10px;_x000D_
}
_x000D_
<div id='box' class="u-gap-10">_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Auto increment primary key in SQL Server Management Studio 2012

Make sure that the Key column's datatype is int and then setting identity manually, as image shows

enter image description here

Or just run this code

-- ID is the name of the  [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID 
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)

the code will run, if ID is not the only column in the table

image reference fifo's

How to lock orientation of one view controller to portrait mode only in Swift

Here is a simple way that works for me with Swift 4.2 (iOS 12.2), put this in a UIViewController for which you want to disable shouldAutorotate:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

The .portrait part tells it in which orientation(s) to remain, you can change this as you like. Choices are: .portrait, .all, .allButUpsideDown, .landscape, .landscapeLeft, .landscapeRight, .portraitUpsideDown.

UIView bottom border?

Swift 4/3

You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.

class ResizeBorderView: UIView {
    var color = UIColor.white
    var lineWidth: CGFloat = 1
    var edges = [UIRectEdge](){
        didSet {
            setNeedsDisplay()
        }
    }
    override func draw(_ rect: CGRect) {
        if edges.contains(.top) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.bottom) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.left) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
        if edges.contains(.right) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
    }
}
  1. Set your UIView's class to ResizeBorderView
  2. Set the color and line width by using yourview.color and yourview.lineWidth in your viewDidAppear method
  3. Set the edges, example: yourview.edges = [.right, .left] ([.all]) for all
  4. Enjoy quick start and resizing borders

How to test android apps in a real device with Android Studio?

To test an android apps in a real device with Android Studio, You must keep two things in mind

  1. You should enable USB debugging option on your android phone.
  2. You must have driver installed on your computer.

Now , let me tell you how you can enable USB debugging on your android phone:

  1. Go to Settings on your android phone
  2. Scroll down to the bottom and click on About phone
  3. On this menu also scroll down to the bottom, you should see something Build number
  4. Click on Build number 7 times
  5. Now your Developer Option enables, once you done click on back button and you should see a new option on your android screen i.e. Developer Options
  6. Click On Developer Options
  7. Scroll down until you see USB Debugging
  8. Go ahead and click the check box next to the USB debugging
  9. Now your USB Debugging option enables.
  10. Connect your android device to your computer with the help of USB connector.

Now let me tell you how you can download the driver on your Windows PC:

  1. Your windows machine need a software called driver to communicate with your phone.
  2. Go To OEM USB Driver Website to install your appropriate driver
  3. Scroll down and select the driver appropriate for your device. Check the screen shoot
  4. Once you download it , you have to unzip your file
  5. After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  6. Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  7. Select Device Manager –> Portable Devices –> Your Device Name
  8. Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  9. Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  10. Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

node.js shell command execution

A simplified version of the accepted answer (third point), just worked for me.

function run_cmd(cmd, args, callBack ) {
    var spawn = require('child_process').spawn;
    var child = spawn(cmd, args);
    var resp = "";

    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stdout.on('end', function() { callBack (resp) });
} // ()

Usage:

run_cmd( "ls", ["-l"], function(text) { console.log (text) });

run_cmd( "hostname", [], function(text) { console.log (text) });

ExpressionChangedAfterItHasBeenCheckedError Explained

Tried most of the solutions suggested above. Only this worked for me in this scenario. I was using *ngIf to toggle angular material's indeterminate progressive bar based on api calls and it was throwing ExpressionChangedAfterItHasBeenCheckedError.

In the component in question:

constructor(
    private ngZone: NgZone,
    private changeDetectorRef: ChangeDetectorRef,
) {}

ngOnInit() {
    this.ngZone.runOutsideAngular(() => {
        this.appService.appLoader$.subscribe(value => {
            this.loading = value;
            this.changeDetectorRef.detectChanges();
        });
    });
}

The trick is to bypass angular component's change detection using ngzone.

PS: Not sure if this is an elegant solution but using AfterContentChecked and AfterViewChecked lifecycle hook is bound to raise performance issues as your application gets bigger as it is triggered numerous times.

How to loop through a plain JavaScript object with the objects as members?

The solution that work for me is the following

_private.convertParams=function(params){
    var params= [];
    Object.keys(values).forEach(function(key) {
        params.push({"id":key,"option":"Igual","value":params[key].id})
    });
    return params;
}

How do I install TensorFlow's tensorboard?

you may have installed tensorflow to virtualenv. activate it and tensorboard command will become available.

Transfer files to/from session I'm logged in with PuTTY

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (the pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY button.

See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.

See Opening PuTTY in the Same Directory.

(I'm the author of WinSCP)

Find text in string with C#

Simply add this code:

if (string.Contains("search_text")) { MessageBox.Show("Message."); }

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Java - What does "\n" mean?

\n is an escape character for strings that is replaced with the new line object. Writing \n in a string that prints out will print out a new line instead of the \n

Java Escape Characters

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

give polpetta a try ...

npm install -g polpetta

then you can

polpetta ~/folder

and you are ready to go :-)

How do you check in python whether a string contains only numbers?

As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit() method is not totally accurate for this use case, because it returns True for some digit-like characters:

>>> "\u2070".isdigit() # unicode escaped 'superscript zero' 
True

If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":

import string

def contains_only_digits(s):
    # True for "", "0", "123"
    # False for "1.2", "1,2", "-1", "a", "a1"
    for ch in s:
        if not ch in string.digits:
            return False
    return True

Used in the example from the question:

if len(isbn) == 10 and contains_only_digits(isbn):
    print ("Works")

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

How to increase the Java stack size?

Add this option

--driver-java-options -Xss512m

to your spark-submit command will fix this issue.

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

Batch files : How to leave the console window open

put at the end it will reopen your console

start cmd 

Which version of CodeIgniter am I currently using?

Try this code working fine check codeigniter version

Just go to 'system' > 'core' > 'CodeIgniter.php' and look for the lines,

/**
 * CodeIgniter Version
 *
 * @var    string
 *
 */
    define('CI_VERSION', '3.0.0');

Alternate method to check codeigniter version, you can echo the constant value 'CI_VERSION' somewhere in codeigniter controller/view file.

<?php
    echo CI_VERSION;
?>

More Information with demo: how to check codeigniter version

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

How can I add a variable to console.log?

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

How to get the list of all printers in computer

You can also use the LocalPrintServer class. See: System.Printing.LocalPrintServer

    public List<string>  InstalledPrinters
    {
        get
        {
            return (from PrintQueue printer in new LocalPrintServer().GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local,
                EnumeratedPrintQueueTypes.Connections }).ToList()
                    select printer.Name).ToList(); 
        } 
    }

As stated in the docs: Classes within the System.Printing namespace are not supported for use within a Windows service or ASP.NET application or service.

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

From the Official documentation,

For example, to set the background color to orange:

<meta name="theme-color" content="#db5945">

In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:

<link rel="icon" sizes="192x192" href="nice-highres.png">

Difference between File.separator and slash in paths

OK let's inspect some code.
File.java lines 428 to 435 in File.<init>:

String p = uri.getPath();
if (p.equals(""))
    throw new IllegalArgumentException("URI path component is empty");

// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);

And let's read fs/*(FileSystem)*/.fromURIPath() docs:

java.io.FileSystem
public abstract String fromURIPath(String path)
Post-process the given URI path string if necessary. This is used on win32, e.g., to transform "/c:/foo" into "c:/foo". The path string still has slash separators; code in the File class will translate them after this method returns.

This means FileSystem.fromURIPath() does post processing on URI path only in Windows, and because in the next line:

p = p.replace('/', File.separatorChar);

It replaces each '/' with system dependent seperatorChar, you can always be sure that '/' is safe in every OS.

Is there any way to change input type="date" format?

After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.

HTML Code:

<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />

CSS Code:

#dt {
  text-indent: -500px;
  height: 25px;
  width: 200px;
}

Javascript Code :

function mydate() {
  //alert("");
  document.getElementById("dt").hidden = false;
  document.getElementById("ndt").hidden = true;
}

function mydate1() {
  d = new Date(document.getElementById("dt").value);
  dt = d.getDate();
  mn = d.getMonth();
  mn++;
  yy = d.getFullYear();
  document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
  document.getElementById("ndt").hidden = false;
  document.getElementById("dt").hidden = true;
}

Output:

enter image description here

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

asp.net validation to make sure textbox has integer values

You can use java script for this:-

<asp:TextBox ID="textbox1" runat="server" Width="150px" MaxLength="8" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;"></asp:TextBox>

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

PHP cURL GET request and request's body

The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );

EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

How do I remove accents from characters in a PHP string?

WordPress' implementation is definitly the safest for UTF8 strings. For Latin1 strings, a simple strtr does the job, but ensure you're saving your script in LATIN1 format, not UTF-8.

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

How to convert dataframe into time series?

Late to the party, but the tsbox package is designed to perform conversions like this. To convert your data into a ts-object, you can do:

dta <- data.frame(
  Dates = c("3/14/2013", "3/15/2013", "3/18/2013", "3/19/2013"),
  Bajaj_close = c(1854.8, 1850.3, 1812.1, 1835.9),
  Hero_close = c(1669.1, 1684.45, 1690.5, 1645.6)
)

dta
#>       Dates Bajaj_close Hero_close
#> 1 3/14/2013      1854.8    1669.10
#> 2 3/15/2013      1850.3    1684.45
#> 3 3/18/2013      1812.1    1690.50
#> 4 3/19/2013      1835.9    1645.60

library(tsbox)
ts_ts(ts_long(dta))
#> Time Series:
#> Start = 2013.1971293045 
#> End = 2013.21081883954 
#> Frequency = 365.2425 
#>          Bajaj_close Hero_close
#> 2013.197      1854.8    1669.10
#> 2013.200      1850.3    1684.45
#> 2013.203          NA         NA
#> 2013.205          NA         NA
#> 2013.208      1812.1    1690.50
#> 2013.211      1835.9    1645.60

It automatically parses the dates, detects the frequency and makes the missing values at the weekends explicit. With ts_<class>, you can convert the data to any other time series class.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In this case no conditionals are needed to set the variable.

This one-liner XPath expression:

boolean(joined-subclass)

is true() only when the child of the current node, named joined-subclass exists and it is false() otherwise.

The complete stylesheet is:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="class">
   <xsl:variable name="subexists"
        select="boolean(joined-subclass)"
   />

   subexists:  <xsl:text/>
   <xsl:value-of select="$subexists" />
 </xsl:template>
</xsl:stylesheet>

Do note, that the use of the XPath function boolean() in this expression is to convert a node (or its absense) to one of the boolean values true() or false().

Extracting numbers from vectors of strings

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

WampServer orange icon

Adding to what @Hitesh-sahu said you need all the VC++ redistribution packages for it to turn green. I referred to this thread from wampserver forum. You can install this little tool (check_vcredist) from the tools section here which will check if all the needed dependencies are installed (see attached image) and it will also provide links to missing ones. If you are using x64 version of Windows like I do and your wampserver does not turn green even after installing all the packages then uninstall and do a fresh installation again. Hope it helps.

enter image description here

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

The only elasticsearch vs solr performance comparison I've been able to find so far is here:

Solr vs elasticsearch Deathmatch!

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

Tremendous thanks to ArturZ for pointing me in the right direction on this. I don't have tmpwatch installed on my system so that isn't the cause of the problem in my case. But the end result is the same: The private /tmp that systemd creates is getting removed. Here's what happens:

  1. systemd creates a new process via clone() with the CLONE_NEWNS flag to obtain a private namespace. Or maybe it calls unshare() with CLONE_NEWNS. Same thing.

  2. systemd creates a subdirectory in /tmp (e.g. /tmp/systemd-namespace-XRiWad/private) and mounts it on /tmp. Because CLONE_NEWNS was set in #1, this mountpoint is invisible to all other processes.

  3. systemd then invokes mysqld in this private namespace.

  4. Some specific database operations (e.g. "describe ;") create & remove temporary files, which has the side effect of updating the timestamp on /tmp/systemd-namespace-XRiWad/private. Other database operations execute without using /tmp at all.

  5. Eventually 10 days go by where even though the database itself remains active, no operations occur that update the timestamp on /tmp/systemd-namespace-XRiWad/private.

  6. /bin/systemd-tmpfiles comes along and removes the "old" /tmp/systemd-namespace-XRiWad/private directory, effectively rendering the private /tmp unusable for mysqld while the public /tmp remains available for everything else on the system.

Restarting mysqld works because this starts everything over again at step #1, with a brand new private /tmp directory. However, the problem eventually comes back again. And again.

The simple solution is to configure /bin/systemd-tmpfiles so that it preserves anything in /tmp with the name /tmp/systemd-namespace-*. I did this by creating /etc/tmpfiles.d/privatetmp.conf with the following contents:

x   /tmp/systemd-namespace-*
x   /tmp/systemd-namespace-*/private

Problem solved.

SQL Server Installation - What is the Installation Media Folder?

If you are using an executable,

  • just run the executable (for example: "en_sql_server_2012_express_edition_with_advanced_services_x64.exe")
  • Navigate to the "options" tab
  • Copy the "Installation Media Root Directory" (should look something like the below snipping)
  • Paste it into the open "Browse for SQL server Installation Media" window

enter image description here

Save yourself the hastle of renaming and unzipping etc.!

How to capitalize the first letter of a String in Java?

You may try this

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

Split a List into smaller lists of N size

Addition after very useful comment of mhand at the end

Original answer

Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.

The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:

public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
    (this IEnumerable<TSource> source, int chunkSize)
{
    while (source.Any())                     // while there are elements left
    {   // still something to chunk:
        yield return source.Take(chunkSize); // return a chunk of chunkSize
        source = source.Skip(chunkSize);     // skip the returned chunk
    }
}

How many times will this Enumerate the sequence?

Suppose you divide your source into chunks of chunkSize. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.

While(source.Any())
{
     ...
}

the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times

yield return source.Take(chunkSize);

According to the reference source this will do something like:

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
    return TakeIterator<TSource>(source, count);
}

static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
    foreach (TSource element in source)
    {
        yield return element;
        if (--count == 0) break;
    }
}

This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.

If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:

  • get the enumerator
  • call MoveNext() and Current M times.
  • Dispose the enumerator

After the first chunk has been yield returned, we skip this first Chunk:

source = source.Skip(chunkSize);

Once again: we'll take a look at reference source to find the skipiterator

static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
    using (IEnumerator<TSource> e = source.GetEnumerator()) 
    {
        while (count > 0 && e.MoveNext()) count--;
        if (count <= 0) 
        {
            while (e.MoveNext()) yield return e.Current;
        }
    }
}

As you see, the SkipIterator calls MoveNext() once for every element in the Chunk. It doesn't call Current.

So per Chunk we see that the following is done:

  • Any(): GetEnumerator; 1 MoveNext(); Dispose Enumerator;
  • Take():

    • nothing if the content of the chunk is not enumerated.
    • If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;

    • Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator

If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current for the TSource items you actually decide to access.

If you take N Chunks of size chunkSize, then calls to MoveNext()

  • N times for Any()
  • not yet any time for Take, as long as you don't enumerate the Chunks
  • N times chunkSize for Skip()

If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.

The total

MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)

So if you decide to enumerate all elements of all chunks:

MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once

Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.

But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.

It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks

How can I shrink the drawable on a button?

If you want to use 1 image and display it in different size, you can use scale drawable ( http://developer.android.com/guide/topics/resources/drawable-resource.html#Scale ).

How do I show/hide a UIBarButtonItem?

For Swift version, here is the code:

For UINavigationBar:

self.navigationItem.rightBarButtonItem = nil

self.navigationItem.leftBarButtonItem = nil

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I had the same error. It is solved by following steps

Go to IIS -> find your site -> right click on the site -> Manage Website -> Advanced Setting -> Check your physical path is correct or not.

If it is wrong, locate the correct path. This will solve issue.

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:

Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

Remove sensitive files and their commits from Git history

Use filter-branch:

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *file_path_relative_to_git_repo*' --prune-empty --tag-name-filter cat -- --all

git push origin *branch_name* -f

Java Returning method which returns arraylist?

You can use on another class

public ArrayList<Integer> myNumbers = new Foo().myNumbers();

or

Foo myClass = new Foo();
 public ArrayList<Integer> myNumbers = myclass.myNumbers();

Open Url in default web browser

Try this:

import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
  Linking.openURL(url);
};

const App = () => {
  return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};

Hope this will solve your problem.

What characters are allowed in an email address?

I created this regex according to RFC guidelines:

^[\\w\\.\\!_\\%#\\$\\&\\'=\\?\\*\\+\\-\\/\\^\\`\\{\\|\\}\\~]+@(?:\\w+\\.(?:\\w+\\-?)*)+$

VBA - If a cell in column A is not blank the column B equals

Use the function IF :

=IF ( logical_test, value_if_true, value_if_false )

Reading a text file and splitting it into single words in python

f = open('words.txt')
for word in f.read().split():
    print(word)

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

How do you style a TextInput in react native for password input

A little plus:

version = RN 0.57.7

secureTextEntry={true}

does not work when the keyboardType was "phone-pad" or "email-address"

Iif equivalent in C#

C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not the way it is.

If you really want IIf() in C#, you can have it:

object IIf(bool expression, object truePart, object falsePart) 
{return expression?truePart:falsePart;}

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart) 
{return expression?truePart:falsePart;}

On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If() operator that works like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

How would you do a "not in" query with LINQ?

One could also use All()

var notInList = list1.Where(p => list2.All(p2 => p2.Email != p.Email));

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

How to go back to previous page if back button is pressed in WebView?

here is a code with confirm exit:

@Override
    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Exit!")
            .setMessage("Are you sure you want to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();    
                }

            })
            .setNegativeButton("No", null)
            .show();    
        }   
    }

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

Only get hash value using md5sum (without filename)

For the sake of completeness a way with sed using regex and capture group:

md5=$(md5sum "${my_iso_file}" | sed -r 's:\\*([^ ]*).*:\1:')

The regulare expression is capturing everything in a group until a space is reached. To get capture group working you need to capture everything in sed. (More about sed and caputer groups here: https://stackoverflow.com/a/2778096/10926293)
As delimiter in sed i use colons because they are not valid in file paths and i don't have to escape the slashed in the filepath.

How to convert date into this 'yyyy-MM-dd' format in angular 2

The date can be converted in typescript to this format 'yyyy-MM-dd' by using Datepipe

import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
 this.date=new Date();
 let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}

and just add Datepipe in 'providers' array of app.module.ts. Like this:

import { DatePipe } from '@angular/common'
...
providers: [DatePipe]

execute shell command from android

A modification of the code by @CarloCannas:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You are welcome to find a better place for outputStream.close())

Usage example:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

Update: To get the result (the output to stdout), use:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

The utility to silently close a number of Closeables (So?ket may be no Closeable) is:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

How can I check the size of a file in a Windows batch script?

Another example

  FOR %I in (file1.txt) do @ECHO %~zI

What determines the monitor my app runs on?

Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.

So I am not sure there is a way to tell every program where to open. Hope that helps some.

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

The same problem happened to me using PostgreSQL I cleared all migrations in migrations folder and in migrations cache folder, and then in my PGADMIN ran:

delete from django_migrations where app='your_app'

Returning JSON from PHP to JavaScript?

Usually you would be interested in also having some structure to your data in the receiving end:

json_encode($result)

This will preserve the array keys as well.

Do remember that json_encode only works on utf8 -encoded data.

Difference in boto3 between resource, client, and session?

Here's some more detailed information on what Client, Resource, and Session are all about.

Client:

  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here's an example of client-level access to an S3 bucket's objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.

Resource:

  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here's the equivalent example using resource-level access to an S3 bucket's objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.

Session:

  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.

Duplicate keys in .NET dictionaries?

This is a tow way Concurrent dictionary I think this will help you:

public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
    private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
    private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();

    public ICollection<T1> Keys
    {
        get
        {
            return _keyValue.Keys;
        }
    }

    public ICollection<T2> Values
    {
        get
        {
            return _valueKey.Keys;
        }
    }

    public int Count
    {
        get
        {
            return _keyValue.Count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public List<T2> this[T1 index]
    {
        get { return _keyValue[index]; }
        set { _keyValue[index] = value; }
    }

    public List<T1> this[T2 index]
    {
        get { return _valueKey[index]; }
        set { _valueKey[index] = value; }
    }

    public void Add(T1 key, T2 value)
    {
        lock (this)
        {
            if (!_keyValue.TryGetValue(key, out List<T2> result))
                _keyValue.TryAdd(key, new List<T2>() { value });
            else if (!result.Contains(value))
                result.Add(value);

            if (!_valueKey.TryGetValue(value, out List<T1> result2))
                _valueKey.TryAdd(value, new List<T1>() { key });
            else if (!result2.Contains(key))
                result2.Add(key);
        }
    }

    public bool TryGetValues(T1 key, out List<T2> value)
    {
        return _keyValue.TryGetValue(key, out value);
    }

    public bool TryGetKeys(T2 value, out List<T1> key)
    {
        return _valueKey.TryGetValue(value, out key);
    }

    public bool ContainsKey(T1 key)
    {
        return _keyValue.ContainsKey(key);
    }

    public bool ContainsValue(T2 value)
    {
        return _valueKey.ContainsKey(value);
    }

    public void Remove(T1 key)
    {
        lock (this)
        {
            if (_keyValue.TryRemove(key, out List<T2> values))
            {
                foreach (var item in values)
                {
                    var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
                }
            }
        }
    }

    public void Remove(T2 value)
    {
        lock (this)
        {
            if (_valueKey.TryRemove(value, out List<T1> keys))
            {
                foreach (var item in keys)
                {
                    var remove2 = _keyValue.TryRemove(item, out List<T2> values);
                }
            }
        }
    }

    public void Clear()
    {
        _keyValue.Clear();
        _valueKey.Clear();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _keyValue.GetEnumerator();
    }
}

examples:

public class TestA
{
    public int MyProperty { get; set; }
}

public class TestB
{
    public int MyProperty { get; set; }
}

            HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();

            var a = new TestA() { MyProperty = 9999 };
            var b = new TestB() { MyProperty = 60 };
            var b2 = new TestB() { MyProperty = 5 };
            hashMapDictionary.Add(a, b);
            hashMapDictionary.Add(a, b2);
            hashMapDictionary.TryGetValues(a, out List<TestB> result);
            foreach (var item in result)
            {
                //do something
            }

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

Similar to accepted answer but allows use of ColumnNames and binds to RowDataBound().

Dictionary<string, int> _headerIndiciesForAbcGridView = null;

protected void abcGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (_headerIndiciesForAbcGridView == null) // builds once per http request
    {
        int index = 0;
        _headerIndiciesForAbcGridView = ((Table)((GridView)sender).Controls[0]).Rows[0].Cells
            .Cast<TableCell>()
            .ToDictionary(c => c.Text, c => index++);
    }

    e.Row.Cells[_headerIndiciesForAbcGridView["theColumnName"]].Visible = false;
}

Not sure if it works with RowCreated().

How to set cornerRadius for only top-left and top-right corner of a UIView?

After change bit of code @apinho In swift 4.3 working fine

extension UIView {
func roundCornersWithLayerMask(cornerRadii: CGFloat, corners: UIRectCorner) {
    let path = UIBezierPath(roundedRect: bounds,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: cornerRadii, height: cornerRadii))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath
    layer.mask = maskLayer
  }
}

To use this function for you view

YourViewName. roundCornersWithLayerMask(cornerRadii: 20,corners: [.topLeft,.topRight])

Parse JSON String into a Particular Object Prototype in JavaScript

Do you want to add JSON serialization/deserialization functionality, right? Then look at this:

You want to achieve this:

UML

toJson() is a normal method.
fromJson() is a static method.

Implementation:

var Book = function (title, author, isbn, price, stock){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + this.author + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +
        "}");
    };
};

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};

Usage:

var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Note: If you want you can change all property definitions like this.title, this.author, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.

Generate random int value from 3 to 6

Lamak's answer as a function:

-- Create RANDBETWEEN function
-- Usage: SELECT dbo.RANDBETWEEN(0,9,RAND(CHECKSUM(NEWID())))
CREATE FUNCTION dbo.RANDBETWEEN(@minval TINYINT, @maxval TINYINT, @random NUMERIC(18,10))
RETURNS TINYINT
AS
BEGIN
  RETURN (SELECT CAST(((@maxval + 1) - @minval) * @random + @minval AS TINYINT))
END
GO

Remove quotes from String in Python

if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]

How can I open the interactive matplotlib window in IPython notebook?

Restart kernel and clear output (if not starting with new notebook), then run

%matplotlib tk

For more info go to Plotting with matplotlib

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

Convert python datetime to epoch with strftime

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.

How to customize the background color of a UITableViewCell?

This will work in the latest Xcode.

-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
    cell.backgroundColor = [UIColor grayColor];
}

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Visual Studio Code Tab Key does not insert a tab

To fix the issue

Pressing ctrl+M causes the ? Tab key to move focus instead of inserting a ? Tab character.
Turn it off by pressing the shortcut again.

To disable the shortcut

  1. Open "Keyboard Shortcuts" with ctrl+K, then ctrl+S.
    Or go to File > Preferences > Keyboard Shortcuts.
  2. Search for toggle tab key moves focus.
  3. Right Click, Remove Keybinding.

hexadecimal string to byte array in python

provided I understood correctly, you should look for binascii.unhexlify

import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

change image captcha refresh

html:

 <img id="captcha_img" src="http://localhost/captcha.php" /> 

jquery:

$("#captcha_img").click(function()
    {
        var capt_rand=Math.floor((Math.random() * 9999) + 1);
        $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
    });

jQuery UI Dialog with ASP.NET button postback

Fantastic! This solved my problem with ASP:Button event not firing inside jQuery modal. Please note, using the jQuery UI modal with the following allows the button event to fire:

// Dialog Link
$('#dialog_link').click(function () {
    $('#dialog').dialog('open');
    $('#dialog').parent().appendTo($("form:first"))
    return false;
});

The following line is the key to get this working!

$('#dialog').parent().appendTo($("form:first"))

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

Probably because both SQL Server and Sybase (to name two I am familiar with) used to have a 255 character maximum in the number of characters in a VARCHAR column. For SQL Server, this changed in version 7 in 1996/1997 or so... but old habits sometimes die hard.

How to check internet access on Android? InetAddress never times out

This method gives you the option for a really fast method (for real time feedback) or a slower method (for one off checks that require reliability)

public boolean isNetworkAvailable(bool SlowButMoreReliable) {
    bool Result = false; 
    try {
        if(SlowButMoreReliable){
            ConnectivityManager MyConnectivityManager = null;
            MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo MyNetworkInfo = null;
            MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo();

            Result = MyNetworkInfo != null && MyNetworkInfo.isConnected();

        } else
        {
            Runtime runtime = Runtime.getRuntime();
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");

            int i = ipProcess.waitFor();

            Result = i== 0;

        }

    } catch(Exception ex)
    {
        //Common.Exception(ex); //This method is one you should have that displays exceptions in your log
    }
    return Result;
}

How to copy sheets to another workbook using vba?

You can simply write

Worksheets.Copy

in lieu of running a cycle. By default the worksheet collection is reproduced in a new workbook.

It is proven to function in 2010 version of XL.

How to set thousands separator in Java?

For decimals:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));

Stopping a JavaScript function when a certain condition is met

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

How to show particular image as thumbnail while implementing share on Facebook?

I see that all the answers provided are correct. However, one important detail was overlooked: The size of the image MUST be at least 200 X 200 px, otherwise Facebook will substitute the thumbnail with the first available image that meets the criteria on the page. Another fact is that the minimum required is to include the 3 metas that Facebook requires for the og:image to take effect:

<meta property="og:title" content="Title of the page" />
<!-- NEXT LINE Even if page is dynamically generated and URL contains query parameters -->
<meta property="og:url" content="http://yoursite.com" />
<meta property="og:image" content="http://convertaholics.com/convertaholics-og.png" />

Debug your page with Facebook debugger and fix all the warnings and it should work like a charm! https://developers.facebook.com/tools/debug

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

I've had this happen (405 method not allowed) when the web api post method I was calling had primitive types for parameters, instead of a complex type that was accessed from the body. Like so:

This worked:

 [Route("update"), Authorize, HttpPost]
  public int Update([FromBody] updateObject update)

This didn't:

 [Route("update"), Authorize, HttpPost]
 public int Update(string whatever, int whatever, string whatever)

Reliable and fast FFT in Java

I wrote a function for the FFT in Java: http://www.wikijava.org/wiki/The_Fast_Fourier_Transform_in_Java_%28part_1%29

It's in the Public Domain so you can use those functions everywhere (personal or business projects too). Just cite me in the credits and send me just a link of your work, and you're ok.

It is completely reliable. I've checked its output against the Mathematica's FFT and they were always correct until the 15th decimal digit. I think it's a very good FFT implementation for Java. I wrote it on the J2SE 1.6 version, and tested it on the J2SE 1.5-1.6 version.

If you count the number of instruction (it's a lot much simpler than a perfect computational complexity function estimation) you can clearly see that this version is great even if it's not optimized at all. I'm planning to publish the optimized version if there are enough requests.

Let me know if it was useful, and tell me any comment you like.

I share the same code right here:

/**
* @author Orlando Selenu
*
*/
public class FFTbase {
/**
 * The Fast Fourier Transform (generic version, with NO optimizations).
 *
 * @param inputReal
 *            an array of length n, the real part
 * @param inputImag
 *            an array of length n, the imaginary part
 * @param DIRECT
 *            TRUE = direct transform, FALSE = inverse transform
 * @return a new array of length 2n
 */
public static double[] fft(final double[] inputReal, double[] inputImag,
                           boolean DIRECT) {
    // - n is the dimension of the problem
    // - nu is its logarithm in base e
    int n = inputReal.length;

    // If n is a power of 2, then ld is an integer (_without_ decimals)
    double ld = Math.log(n) / Math.log(2.0);

    // Here I check if n is a power of 2. If exist decimals in ld, I quit
    // from the function returning null.
    if (((int) ld) - ld != 0) {
        System.out.println("The number of elements is not a power of 2.");
        return null;
    }

    // Declaration and initialization of the variables
    // ld should be an integer, actually, so I don't lose any information in
    // the cast
    int nu = (int) ld;
    int n2 = n / 2;
    int nu1 = nu - 1;
    double[] xReal = new double[n];
    double[] xImag = new double[n];
    double tReal, tImag, p, arg, c, s;

    // Here I check if I'm going to do the direct transform or the inverse
    // transform.
    double constant;
    if (DIRECT)
        constant = -2 * Math.PI;
    else
        constant = 2 * Math.PI;

    // I don't want to overwrite the input arrays, so here I copy them. This
    // choice adds \Theta(2n) to the complexity.
    for (int i = 0; i < n; i++) {
        xReal[i] = inputReal[i];
        xImag[i] = inputImag[i];
    }

    // First phase - calculation
    int k = 0;
    for (int l = 1; l <= nu; l++) {
        while (k < n) {
            for (int i = 1; i <= n2; i++) {
                p = bitreverseReference(k >> nu1, nu);
                // direct FFT or inverse FFT
                arg = constant * p / n;
                c = Math.cos(arg);
                s = Math.sin(arg);
                tReal = xReal[k + n2] * c + xImag[k + n2] * s;
                tImag = xImag[k + n2] * c - xReal[k + n2] * s;
                xReal[k + n2] = xReal[k] - tReal;
                xImag[k + n2] = xImag[k] - tImag;
                xReal[k] += tReal;
                xImag[k] += tImag;
                k++;
            }
            k += n2;
        }
        k = 0;
        nu1--;
        n2 /= 2;
    }

    // Second phase - recombination
    k = 0;
    int r;
    while (k < n) {
        r = bitreverseReference(k, nu);
        if (r > k) {
            tReal = xReal[k];
            tImag = xImag[k];
            xReal[k] = xReal[r];
            xImag[k] = xImag[r];
            xReal[r] = tReal;
            xImag[r] = tImag;
        }
        k++;
    }

    // Here I have to mix xReal and xImag to have an array (yes, it should
    // be possible to do this stuff in the earlier parts of the code, but
    // it's here to readibility).
    double[] newArray = new double[xReal.length * 2];
    double radice = 1 / Math.sqrt(n);
    for (int i = 0; i < newArray.length; i += 2) {
        int i2 = i / 2;
        // I used Stephen Wolfram's Mathematica as a reference so I'm going
        // to normalize the output while I'm copying the elements.
        newArray[i] = xReal[i2] * radice;
        newArray[i + 1] = xImag[i2] * radice;
    }
    return newArray;
}

/**
 * The reference bitreverse function.
 */
private static int bitreverseReference(int j, int nu) {
    int j2;
    int j1 = j;
    int k = 0;
    for (int i = 1; i <= nu; i++) {
        j2 = j1 / 2;
        k = 2 * k + j1 - 2 * j2;
        j1 = j2;
    }
    return k;
  }
}

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

How to print spaces in Python?

Space char is hexadecimal 0x20, decimal 32 and octal \040.

>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '

How do I create a MessageBox in C#?

This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)

More information can be found here

Create table variable in MySQL

They don't exist in MySQL do they? Just use a temp table:

CREATE PROCEDURE my_proc () BEGIN 

CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100)); 
INSERT INTO TempTable SELECT tblid, tblfield FROM Table1; 

/* Do some more stuff .... */

From MySQL here

"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"

How to compile Go program consisting of multiple files?

You can use

go build *.go 
go run *.go

both will work also you may use

go build .
go run .

Copy file or directories recursively in Python

Unix cp doesn't 'support both directories and files':

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.

There is some disconnect here though - cp -r when passed a filename as the source will happily copy just the single file; copytree won't.

Setting PATH environment variable in OSX permanently

You can open any of the following files:

/etc/profile
~/.bash_profile
~/.bash_login   (if .bash_profile does not exist)
~/.profile      (if .bash_login does not exist)

And add:

export PATH="$PATH:your/new/path/here"

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

Select SQL Server database size

If you want to simply check single database size, you can do it using SSMS Gui

Go to Server Explorer -> Expand it -> Right click on Database -> Choose Properties -> In popup window choose General tab ->See Size

Source: Check database size in Sql server ( Various Ways explained)

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

plain count up timer in javascript

Timer for jQuery - smaller, working, tested.

_x000D_
_x000D_
    var sec = 0;_x000D_
    function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
    setInterval( function(){_x000D_
        $("#seconds").html(pad(++sec%60));_x000D_
        $("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
    }, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
_x000D_
_x000D_

Pure JavaScript:

_x000D_
_x000D_
    var sec = 0;_x000D_
    function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
    setInterval( function(){_x000D_
        document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
    }, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
_x000D_
_x000D_

Update:

This answer shows how to pad.

Stopping setInterval MDN is achieved with clearInterval MDN

var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );

Fiddle

Exiting out of a FOR loop in a batch file?

you do not need a seperate batch file to exit a loop using exit /b if you are using call instead of goto like

call :loop

echo loop finished

goto :eof

:loop
FOR /L %%I IN (1,1,10) DO (
    echo %%I
    IF %%I==5 exit /b
)

in this case, the "exit /b" will exit the 'call' and continue from the line after 'call' So the output is this:

1
2
3
4
5
loop finished

How to know if docker is already logged in to a docker registry server

For private registries, nothing is shown in docker info. However, the logout command will tell you if you were logged in:

 $ docker logout private.example.com
 Not logged in to private.example.com

(Though this will force you to log in again.)

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

All the other answers in here are also valid, but if none of them solve the issue it is also worth checking that the actual headers are being passed to the server.

For example, in a load balanced environment behind nginx, the default configuration is to strip out the __RequestVerificationToken header before passing the request on to the server, see: simple nginx reverse proxy seems to strip some headers

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

In my case, this error was caused by renaming my client machine. I used a new name longer than 13 characters (despite the warning), which resulted in the NETBIOS name being truncated and being different from the full machine name. Once I re-renamed the client to a shorter name, the error went away.

How to start Activity in adapter?

When implementing the onClickListener, you can use v.getContext.startActivity.

btn.setOnClickListener(new OnClickListener() {                  
    @Override
    public void onClick(View v) {
        v.getContext().startActivity(PUT_YOUR_INTENT_HERE);
    }
});

How to check a not-defined variable in JavaScript

I've often done:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

How to check whether a pandas DataFrame is empty?

To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:

if len(df.columns) == 0: 1

Reason:

According to the Pandas Reference API, there is a distinction between:

  • an empty dataframe with 0 rows and 0 columns
  • an empty dataframe with rows containing NaN hence at least 1 column

Arguably, they are not the same. The other answers are imprecise in that df.empty, len(df), or len(df.index) make no distinction and return index is 0 and empty is True in both cases.

Examples

Example 1: An empty dataframe with 0 rows and 0 columns

In [1]: import pandas as pd
        df1 = pd.DataFrame()
        df1
Out[1]: Empty DataFrame
        Columns: []
        Index: []

In [2]: len(df1.index)  # or len(df1)
Out[2]: 0

In [3]: df1.empty
Out[3]: True

Example 2: A dataframe which is emptied to 0 rows but still retains n columns

In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df2
Out[4]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

In [5]: df2 = df2[df2['AA'] == 5]
        df2
Out[5]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

In [6]: len(df2.index)  # or len(df2)
Out[6]: 0

In [7]: df2.empty
Out[7]: True

Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.

In [8]: len(df1.columns)
Out[8]: 0

In [9]: len(df2.columns)
Out[9]: 2

Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.

Why it matters

Let's add a new column to these dataframes to understand the implications:

# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
         df1
Out[10]:    CC
         0 111
         1 222
         2 333
In [11]: len(df1.columns)
Out[11]: 1

# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
         df2
Out[12]:    AA  BB   CC
         0 NaN NaN  111
         1 NaN NaN  222
         2 NaN NaN  333
In [13]: len(df2.columns)
Out[13]: 3

It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns) to see if a dataframe is empty.

Practical solution

# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df
Out[1]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
        df
Out[2]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2

# And accordingly, the other answers on this page
In [4]: len(df.index)  # or len(df)
Out[4]: 0

In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0:  # <--- here
            # Do something, e.g. 
            # drop any columns containing rows with `NaN`
            # to make the df really empty
            df = df.dropna(how='all', axis=1)
        df
Out[6]: Empty DataFrame
        Columns: []
        Index: []

# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0

Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN):

In [8]: df['CC'] = [111, 222, 333]
         df
Out[8]:    CC
         0 111
         1 222
         2 333
In [9]: len(df.columns)
Out[9]: 1

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

Capture Image from Camera and Display in Activity

I know it's a quite old thread, but all these solutions are not completed and don't work on some devices when user rotates camera because data in onActivityResult is null. So here is solution which I have tested on lots of devices and haven't faced any problem so far.

First declare your Uri variable in your activity:

private Uri uriFilePath;

Then create your temporary folder for storing captured image and make intent for capturing image by camera:

PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
    File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
         if (!mainDirectory.exists())
             mainDirectory.mkdirs();

          Calendar calendar = Calendar.getInstance();

          uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis()));
          intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
          startActivityForResult(intent, 1);
}

And now here comes one of the most important things, you have to save your uriFilePath in onSaveInstanceState, because if you didn't do that and user rotated his device while using camera, your uri would be null.

@Override
protected void onSaveInstanceState(Bundle outState) {
     if (uriFilePath != null)
         outState.putString("uri_file_path", uriFilePath.toString());
     super.onSaveInstanceState(outState);
}

After that you should always recover your uri in your onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
         if (uriFilePath == null && savedInstanceState.getString("uri_file_path") != null) {
             uriFilePath = Uri.parse(savedInstanceState.getString("uri_file_path"));
         }
    } 
}

And here comes last part to get your Uri in onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
    if (resultCode == RESULT_OK) {
         if (requestCode == 1) {
            String filePath = uriFilePath.getPath(); // Here is path of your captured image, so you can create bitmap from it, etc.
         }
    }
 }

P.S. Don't forget to add permissions for Camera and Ext. storage writing to your Manifest.

How to launch Safari and open URL from iOS app

Here one check is required that the url going to be open is able to open by device or simulator or not. Because some times (majority in simulator) i found it causes crashes.

Objective-C

NSURL *url = [NSURL URLWithString:@"some url"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
   [[UIApplication sharedApplication] openURL:url];
}

Swift 2.0

let url : NSURL = NSURL(string: "some url")!
if UIApplication.sharedApplication().canOpenURL(url) {
     UIApplication.sharedApplication().openURL(url)
}

Swift 4.2

guard let url = URL(string: "some url") else {
    return
}
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

Pair/tuple data type in Go

You can do this. It looks more wordy than a tuple, but it's a big improvement because you get type checking.

Edit: Replaced snippet with complete working example, following Nick's suggestion. Playground link: http://play.golang.org/p/RNx_otTFpk

package main

import "fmt"

func main() {
    queue := make(chan struct {string; int})
    go sendPair(queue)
    pair := <-queue
    fmt.Println(pair.string, pair.int)
}

func sendPair(queue chan struct {string; int}) {
    queue <- struct {string; int}{"http:...", 3}
}

Anonymous structs and fields are fine for quick and dirty solutions like this. For all but the simplest cases though, you'd do better to define a named struct just like you did.

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

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

WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
   if("Germany".equals(option.getText()))
       option.click();   
}

Getting a list of values from a list of dicts

I think as simple as below would give you what you are looking for.

In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']

You can do this with a combination of map and lambda as well but list comprehension looks more elegant and pythonic.

For a smaller input list comprehension is way to go but if the input is really big then i guess generators are the ideal way.

In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'

Here is a comparison of all possible solutions for bigger input

 In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
  ...:     for i in l:
  ...:         yield i.get('value', None)
  ...: 
In[4]: def list_comp_verison():
  ...:     return [i.get('value', None) for i in l]
  ...: 
In[5]: def list_verison():
  ...:     ll = []
  ...:     for i in l:
  ...:         ll.append(i.get('value', None))
  ...:     return ll
In[10]: def map_lambda_version():
   ...:      m = map(lambda i:i.get('value', None), l)
   ...:      return m
   ...: 
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As you can see, generators are a better solution in comparison to the others, map is also slower compared to generator for reason I will leave up to OP to figure out.

How do I share a global variable between c files?

Use the extern keyword to declare the variable in the other .c file. E.g.:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

Prevent redirect after form is submitted

Instead of return false, you could try event.preventDefault(); like this:

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

Best way to find the intersection of multiple sets?

Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

Guido might dislike reduce, but I'm kind of fond of it :)

How to parse float with two decimal places in javascript?

You can use .toFixed() to for float value 2 digits

Exampale

let newValue = parseFloat(9.990000).toFixed(2)

//output
9.99

filters on ng-model in an input

You can try this

$scope.$watch('tags ',function(){

    $scope.tags = $filter('lowercase')($scope.tags);

});

Unsafe JavaScript attempt to access frame with URL

I was getting the same error message when I tried to change the domain for iframe.src.

For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.

Worked like a charm.:)

Can I set a TTL for @Cacheable

this can be done by extending org.springframework.cache.interceptor.CacheInterceptor , and override "doPut" method - org.springframework.cache.interceptor.AbstractCacheInvoker your override logic should use the cache provider put method that knows to set TTL for cache entry (in my case I use HazelcastCacheManager)

@Autowired
@Qualifier(value = "cacheManager")
private CacheManager hazelcastCacheManager;

@Override
protected void doPut(Cache cache, Object key, Object result) {
        //super.doPut(cache, key, result); 
        HazelcastCacheManager hazelcastCacheManager = (HazelcastCacheManager) this.hazelcastCacheManager;
        HazelcastInstance hazelcastInstance = hazelcastCacheManager.getHazelcastInstance();
        IMap<Object, Object> map = hazelcastInstance.getMap("CacheName");
        //set time to leave 18000 secondes
        map.put(key, result, 18000, TimeUnit.SECONDS);



}

on your cache configuration you need to add those 2 bean methods , creating your custom interceptor instance .

@Bean
public CacheOperationSource cacheOperationSource() {
    return new AnnotationCacheOperationSource();
}


@Primary
@Bean
public CacheInterceptor cacheInterceptor() {
    CacheInterceptor interceptor = new MyCustomCacheInterceptor();
    interceptor.setCacheOperationSources(cacheOperationSource());    
    return interceptor;
}

This solution is good when you want to set the TTL on the entry level , and not globally on cache level

How to delete a workspace in Perforce (using p4v)?

  1. Ctrl + 5

view workspace in p4v

  1. Delete the relevant workspace

enter image description here

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

Python list of dictionaries search

You can achieve this with the usage of filter and next methods in Python.

filter method filters the given sequence and returns an iterator. next method accepts an iterator and returns the next element in the list.

So you can find the element by,

my_dict = [
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5},
    {"name": "Pam", "age": 7}
]

next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)

and the output is,

{'name': 'Pam', 'age': 7}

Note: The above code will return None incase if the name we are searching is not found.

Choose folders to be ignored during search in VS Code

Extending the most voted answer, now there is an extension to achieve what is described there to toggle quickly in a GUI way. It's called Explorer Exclude. You can install this with this command:

ext install RedVanWorkshop.explorer-exclude-vscode-extension

Demo:

enter image description here