Programs & Examples On #Minimum

Minimum refers to the value in a collection of values that is the least or smallest.

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

How to scale down a range of numbers with a known min and max value

I've taken Irritate's answer and refactored it so as to minimize the computational steps for subsequent computations by factoring it into the fewest constants. The motivation is to allow a scaler to be trained on one set of data, and then be run on new data (for an ML algo). In effect, it's much like SciKit's preprocessing MinMaxScaler for Python in usage.

Thus, x' = (b-a)(x-min)/(max-min) + a (where b!=a) becomes x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a which can be reduced to two constants in the form x' = x*Part1 + Part2.

Here's a C# implementation with two constructors: one to train, and one to reload a trained instance (e.g., to support persistence).

public class MinMaxColumnSpec
{
    /// <summary>
    /// To reduce repetitive computations, the min-max formula has been refactored so that the portions that remain constant are just computed once.
    /// This transforms the forumula from
    /// x' = (b-a)(x-min)/(max-min) + a
    /// into x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
    /// which can be further factored into
    /// x' = x*Part1 + Part2
    /// </summary>
    public readonly double Part1, Part2;

    /// <summary>
    /// Use this ctor to train a new scaler.
    /// </summary>
    public MinMaxColumnSpec(double[] columnValues, int newMin = 0, int newMax = 1)
    {
        if (newMax <= newMin)
            throw new ArgumentOutOfRangeException("newMax", "newMax must be greater than newMin");

        var oldMax = columnValues.Max();
        var oldMin = columnValues.Min();

        Part1 = (newMax - newMin) / (oldMax - oldMin);
        Part2 = newMin + (oldMin * (newMin - newMax) / (oldMax - oldMin));
    }

    /// <summary>
    /// Use this ctor for previously-trained scalers with known constants.
    /// </summary>
    public MinMaxColumnSpec(double part1, double part2)
    {
        Part1 = part1;
        Part2 = part2;
    }

    public double Scale(double x) => (x * Part1) + Part2;
}

Java Minimum and Maximum values in Array

getMaxValue(array);
// get smallest number
getMinValue(array);

You are calling the methods but not using the returned values.

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

Get the key corresponding to the minimum value within a dictionary

Is this what you are looking for?

d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'

print d[min(d.keys())]

Prints 'fourteen'

How to configure logging to syslog in Python?

import syslog
syslog.openlog(ident="LOG_IDENTIFIER",logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
syslog.syslog('Log processing initiated...')

the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.

MongoDB: Combine data from multiple collections into one..how?

If there is no bulk insert into mongodb, we loop all objects in the small_collection and insert them one by one into the big_collection:

db.small_collection.find().forEach(function(obj){ 
   db.big_collection.insert(obj)
});

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

How to get the absolute coordinates of a view

Just in addition to the above answers, for the question where and when you should call getLocationOnScreen?

For any information that is related to the view, will be available only after the view has been laid out(created) on the screen. So to get the location put your code inside view.post(Runnable) which is called after view has been laid out, like this:

view.post(new Runnable() {
            @Override
            public void run() {

               // This code will run when view created and rendered on screen

               // So as the answer to this question, you can put the code here
               int[] location = new int[2];
               myView.getLocationOnScreen(location);
               int x = location[0];
               int y = location[1];
            }
        });  

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

MVC razor form with multiple different submit buttons?

You could also try this:

<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />

Then in your default function you call the functions you want:

if( Request.Form["submitbutton1"] != null)
{
    // Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
    // code for function 2
}

How to sum a list of integers with java streams?

Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like

list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

From the Errata: ModelState.AddRuleViolations(dinner.GetRuleViolations());

Should be:

ModelState.AddModelErrors(dinner.GetRuleViolations());

Reference: http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611,descCd-ERRATA.html

Storing query results into a variable and modifying it inside a Stored Procedure

Try this example

CREATE PROCEDURE MyProc
BEGIN
    --Stored Procedure variables
    Declare @maxOr int; 
    Declare @maxCa int; 

    --Getting query result in the variable (first variant of syntax)
    SET @maxOr = (SELECT MAX(orId) FROM [order]); 

    --Another variant of seting variable from query
    SELECT @maxCa=MAX(caId) FROM [cart]; 

    --Updating record through the variable
    INSERT INTO [order_cart] (orId,caId)
    VALUES(@maxOr, @maxCa); 

    --return values to the program as dataset
    SELECT
       @maxOr AS maxOr,
       @maxCa AS maxCa

    -- return one int value as "return value"
    RETURN @maxOr
END
GO

SQL-command to call the stored procedure

EXEC MyProc

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

After some research I understand - I have very similar, but different root project locations and its cached in /bootstrap/cache. After cache clearing project started.

How to convert integer to char in C?

You can try atoi() library function. Also sscanf() and sprintf() would help.

Here is a small example to show converting integer to character string:

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
  // Now str contains the integer as characters
} 

Here for another Example

#include <stdio.h>

int main(void)
{
   char text[] = "StringX";
   int digit;
   for (digit = 0; digit < 10; ++digit)
   {
      text[6] = digit + '0';
      puts(text);
   }
   return 0;
}

/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

How to add column to numpy array

I think that your problem is that you are expecting np.append to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays

Returns
-------
append : ndarray
    A copy of `arr` with `values` appended to `axis`.  Note that `append`
    does not occur in-place: a new array is allocated and filled.  If
    `axis` is None, `out` is a flattened array.

so you need to save the output all_data = np.append(...):

my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)

Alternative ways:

all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)

I believe that the only difference between these three functions (as well as np.vstack) are their default behaviors for when axis is unspecified:

  • concatenate assumes axis = 0
  • hstack assumes axis = 1 unless inputs are 1d, then axis = 0
  • vstack assumes axis = 0 after adding an axis if inputs are 1d
  • append flattens array

Based on your comment, and looking more closely at your example code, I now believe that what you are probably looking to do is add a field to a record array. You imported both genfromtxt which returns a structured array and recfromcsv which returns the subtly different record array (recarray). You used the recfromcsv so right now my_data is actually a recarray, which means that most likely my_data.shape = (210,) since recarrays are 1d arrays of records, where each record is a tuple with the given dtype.

So you could try this:

import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
#       (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
#       (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588  , 2.121903762680979 ),
#       (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
#       (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675  , 1.4957409515009568),
#       (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308  , 2.4853911958174133),
#       (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103  , 1.275756904913104 ),
#       (0.684075052174589  , 0.6654774682866273 , 0.5246593820025259  , 1.8742119024637423),
#       (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
#       (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)], 
#      dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')

How do I exit the Vim editor?

Vim has three modes of operation: Input mode, Command mode & Ex mode.

Input mode - everything that you type, all keystrokes are echoed on the screen.

Command mode or Escape mode - everything that you type in this mode is interpreted as a command.

Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.

In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.

Exiting from ex mode

  1. You need to be sure that you are in the Command mode. To do that, simply press the Esc key.

  2. Go to the ex mode by pressing the : key

  3. Use any of the following combinations in ex mode to exit:

    :q - quit :q! - quit without saving :wq - save & quit or write & quit :wq! - same as wq, but force write in case file permissions are readonly :x - write & quit :qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt

Exiting from command mode

  1. Press the escape key. You probably have done this already if you are in command mode.

  2. Press capital ZZ (shift zz) - save & exit

  3. Press capital ZQ (shift zq) - exit without saving.

Why does Maven have such a bad rep?

Maven does solve working problems, it builds java softwares, and easy dependence management. But it is very different from Ant, and GNU Make, or other Unix-like package management system. This make new-comer have to pay a lot to learn it.

There are lots Maven document, but some of them pushing you away, like this from "using m2eclipse":

By simply entering a groupId into the query field, m2eclipse queries the repository indexes and even shows a version of the artifact that is currently in my local Maven repository. This option is preferred because it is such a tremendous time saver.

I really hate to figure out a long sentence and found it says nothing. I can remember how good feel when reading python official tutorial, and erlang's. Good document will show the author has good senses.

Maven appears strange to newcomers, it's command line style is different from Unix command line traditions. If you pay time to go through "maven by examples" or "The Definitive Guide", it pay off, you can find it on http://www.sonatype.com/. But even if you read all those documents, and can use the tool with confidences, you can come across troubles time by time, some caused by software bugs. And expert get ways to live with it and keep productive.

After all, Maven is open source software, it contributes knowledges to freelance engineers. And this make it respectful. When people talks more about it's bad reputation, it is doing good job for open source world.

So, as how skilled people use any tools, just use it, and don't depend on it, depend on yourself.

PHP Warning: PHP Startup: Unable to load dynamic library

In Windows, it could be a wrong path in "System environment variables". "Path" to the php.exe directory must be the good one.

Oracle Age calculation from Date of birth and Today

SQL> select trunc(months_between(sysdate,dob)/12) year,
  2         trunc(mod(months_between(sysdate,dob),12)) month,
  3         trunc(sysdate-add_months(dob,trunc(months_between(sysdate,dob)/12)*12+trunc(mod(months_between(sysdate,dob),12)))) day
  4  from (Select to_date('15122000','DDMMYYYY') dob from dual);

      YEAR      MONTH        DAY
---------- ---------- ----------
         9          5         26

SQL>

How to get a file or blob from an object URL?

If you show the file in a canvas anyway you can also convert the canvas content to a blob object.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

How can I set a UITableView to grouped style

swift 4

if you don't want use storyboard, this might be help.

you can add table view and set properties in a closure:

lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)

        tableView.backgroundColor = UIColor(named: Palette.secondaryLight.rawValue)
        tableView.rowHeight = 68
        tableView.separatorStyle = .none
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()

then add in subview and set constraints.

Get current value selected in dropdown using jQuery

To get the text of the selected option

$("#your_select :selected").text();

To get the value of the selected option

$("#your_select").val();

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

Any difference between await Promise.all() and multiple await?

First difference - Fail Fast

I agree with @zzzzBov's answer, but the "fail fast" advantage of Promise.all is not the only difference. Some users in the comments have asked why using Promise.all is worth it when it's only faster in the negative scenario (when some task fails). And I ask, why not? If I have two independent async parallel tasks and the first one takes a very long time to resolve but the second is rejected in a very short time, why leave the user to wait for the longer call to finish to receive an error message? In real-life applications we must consider the negative scenario. But OK - in this first difference you can decide which alternative to use: Promise.all vs. multiple await.

Second difference - Error Handling

But when considering error handling, YOU MUST use Promise.all. It is not possible to correctly handle errors of async parallel tasks triggered with multiple awaits. In the negative scenario you will always end with UnhandledPromiseRejectionWarning and PromiseRejectionHandledWarning, regardless of where you use try/ catch. That is why Promise.all was designed. Of course someone could say that we can suppress those errors using process.on('unhandledRejection', err => {}) and process.on('rejectionHandled', err => {}) but this is not good practice. I've found many examples on the internet that do not consider error handling for two or more independent async parallel tasks at all, or consider it but in the wrong way - just using try/ catch and hoping it will catch errors. It's almost impossible to find good practice in this.

Summary

TL;DR: Never use multiple await for two or more independent async parallel tasks, because you will not be able to handle errors correctly. Always use Promise.all() for this use case.

Async/ await is not a replacement for Promises, it's just a pretty way to use promises. Async code is written in "sync style" and we can avoid multiple thens in promises.

Some people say that when using Promise.all() we can't handle task errors separately, and that we can only handle the error from the first rejected promise (separate handling can be useful e.g. for logging). This is not a problem - see "Addition" heading at the bottom of this answer.

Examples

Consider this async task...

const task = function(taskNum, seconds, negativeScenario) {
  return new Promise((resolve, reject) => {
    setTimeout(_ => {
      if (negativeScenario)
        reject(new Error('Task ' + taskNum + ' failed!'));
      else
        resolve('Task ' + taskNum + ' succeed!');
    }, seconds * 1000)
  });
};

When you run tasks in the positive scenario there is no difference between Promise.all and multiple awaits. Both examples end with Task 1 succeed! Task 2 succeed! after 5 seconds.

// Promise.all alternative
const run = async function() {
  // tasks run immediate in parallel and wait for both results
  let [r1, r2] = await Promise.all([
    task(1, 5, false),
    task(2, 5, false)
  ]);
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
  // tasks run immediate in parallel
  let t1 = task(1, 5, false);
  let t2 = task(2, 5, false);
  // wait for both results
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!

However, when the first task takes 10 seconds and succeeds, and the second task takes 5 seconds but fails, there are differences in the errors issued.

// Promise.all alternative
const run = async function() {
  let [r1, r2] = await Promise.all([
      task(1, 10, false),
      task(2, 5, true)
  ]);
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
  let t1 = task(1, 10, false);
  let t2 = task(2, 5, true);
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!

We should already notice here that we are doing something wrong when using multiple awaits in parallel. Let's try handling the errors:

// Promise.all alternative
const run = async function() {
  let [r1, r2] = await Promise.all([
    task(1, 10, false),
    task(2, 5, true)
  ]);
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!

As you can see, to successfully handle errors, we need to add just one catch to the run function and add code with catch logic into the callback. We do not need to handle errors inside the run function because async functions do this automatically - promise rejection of the task function causes rejection of the run function.

To avoid a callback we can use "sync style" (async/ await + try/ catch)
try { await run(); } catch(err) { }
but in this example it's not possible, because we can't use await in the main thread - it can only be used in async functions (because nobody wants to block main thread). To test if handling works in "sync style" we can call the run function from another async function or use an IIFE (Immediately Invoked Function Expression: MDN):

(async function() { 
  try { 
    await run(); 
  } catch(err) { 
    console.log('Caught error', err); 
  }
})();

This is the only correct way to run two or more async parallel tasks and handle errors. You should avoid the examples below.

Bad Examples

// multiple await alternative
const run = async function() {
  let t1 = task(1, 10, false);
  let t2 = task(2, 5, true);
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};

We can try to handle errors in the code above in several ways...

try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled 

... nothing got caught because it handles sync code but run is async.

run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... huh? We see firstly that the error for task 2 was not handled and later that it was caught. Misleading and still full of errors in console, it's still unusable this way.

(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... the same as above. User @Qwerty in his deleted answer asked about this strange behavior where an error seems to be caught but are also unhandled. We catch error the because run() is rejected on the line with the await keyword and can be caught using try/ catch when calling run(). We also get an unhandled error because we are calling an async task function synchronously (without the await keyword), and this task runs and fails outside the run() function.
It is similar to when we are not able to handle errors by try/ catch when calling some sync function which calls setTimeout:

function test() {
  setTimeout(function() { 
    console.log(causesError); 
    }, 0);
}; 
try { 
  test(); 
} catch(e) { 
  /* this will never catch error */ 
}`.

Another poor example:

const run = async function() {
  try {
    let t1 = task(1, 10, false);
    let t2 = task(2, 5, true);
    let r1 = await t1;
    let r2 = await t2;
  }
  catch (err) {
    return new Error(err);
  }
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... "only" two errors (3rd one is missing) but nothing is caught.

Addition (handling separate task errors and also first-fail error)

const run = async function() {
  let [r1, r2] = await Promise.all([
    task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
    task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
  ]);
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!

... note that in this example I rejected both tasks to better demonstrate what happens (throw err is used to fire final error).

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

Count character occurrences in a string in C++

There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.

Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

Decompile .smali files on an APK

I second that.

Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.

However, JDGUI generates .java files which have ,more often than not, errors.

It has got something to do with code obfuscation I guess.

XAMPP: Couldn't start Apache (Windows 10)

I have tried all the above solutions. But it was not working in any way.

Finally, I just uninstalled XAMPP and installed it again. Then it worked for me.

Now I am able to run the server on any port (including 80).

Inner text shadow with CSS

text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);

for box shadow:

-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
-moz-box-shadow:    7px 7px 5px rgba(50, 50, 50, 0.75);
box-shadow:         7px 7px 5px rgba(50, 50, 50, 0.75);

you can see online text and box shadow: online text and box shadow

for more example you can go to this address : more example code freeclup

How do I pass environment variables to Docker containers?

The problem I had was that I was putting the --env-file at the end of the command

docker run -it --rm -p 8080:80 imagename --env-file ./env.list

Fix

docker run --env-file ./env.list -it --rm -p 8080:80 imagename

trigger body click with jQuery

As mentioned by Seeker, the problem could have been that you setup the click() function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.

An important point is to run such scripts after the document is ready. This is done by placing the click() initialization within that other function as in:

jQuery(document).ready(function()
  {
    jQuery("body").click(function()
      {
        // ... your click code here ...
      });
  });

This is usually the best method, especially if you include your JavaScript code in your <head> tag. If you include it at the very bottom of the page, then the ready() function is less important, but it may still be useful.

Adding placeholder attribute using Jquery

You just need this:

$(".hidden").attr("placeholder", "Type here to search");

classList is used for manipulating classes and not attributes.

Java generics - why is "extends T" allowed but not "implements T"?

Probably because for both sides (B and C) only the type is relevant, not the implementation. In your example

public class A<B extends C>{}

B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.

interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}

I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

Description Box using "onmouseover"

Assuming popup is the ID of your "description box":

HTML

<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

Alternatively you can get rid of JavaScript entirely and do it just with CSS:

CSS

#parent #popup {
  display: none;
}

#parent:hover #popup {
  display: block;
}

Read .mat files in Python

Reading the file

import scipy.io
mat = scipy.io.loadmat(file_name)

Inspecting the type of MAT variable

print(type(mat))
#OUTPUT - <class 'dict'>

The keys inside the dictionary are MATLAB variables, and the values are the objects assigned to those variables.

Python can't find module in the same folder

Here is the generic solution I use. It solves the problem for importing from modules in the same folder:

import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

Put this at top of the module which gives the error "No module named xxxx"

Absolute Positioning & Text Alignment

Try this:

http://jsfiddle.net/HRz6X/2/

You need to add left: 0 and right: 0 (not supported by IE6). Or specify a width

MySQL: When is Flush Privileges in MySQL really needed?

Just to give some examples. Let's say you modify the password for an user called 'alex'. You can modify this password in several ways. For instance:

mysql> update* user set password=PASSWORD('test!23') where user='alex'; 
mysql> flush privileges;

Here you used UPDATE. If you use INSERT, UPDATE or DELETE on grant tables directly you need use FLUSH PRIVILEGES in order to reload the grant tables.

Or you can modify the password like this:

mysql> set password for 'alex'@'localhost'= password('test!24');

Here it's not necesary to use "FLUSH PRIVILEGES;" If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.

Using PowerShell credentials without being prompted for a password

I have to run SCOM 2012 functions from a remote server that requires a different credential. I avoid clear-text passwords by passing the output of a password decryption function as input to ConvertTo-SecureString. For clarity, this is not shown here.

I like to strongly type my declarations. The type declaration for $strPass works correctly.

[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = '' 

$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)

Combination of async function + await + setTimeout

Made a util inspired from Dave's answer

Basically passed in a done callback to call when the operation is finished.

// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
  cb(resolve);
  setTimeout(() => reject('Request is taking too long to response'), timeout);
});

This is how I use it:

try {
  await setAsyncTimeout(async done => {
    const requestOne = await someService.post(configs);
    const requestTwo = await someService.get(configs);
    const requestThree = await someService.post(configs);
    done();
  }, 5000); // 5 seconds max for this set of operations
}
catch (err) {
  console.error('[Timeout] Unable to complete the operation.', err);
}

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

I don't know if this will help you but..

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers    
    where !(from o in dc.Orders    
            select o.CustomerID)    
           .Contains(c.CustomerID)    
    select c;

foreach (var c in query) Console.WriteLine( c );

from The NOT IN clause in LINQ to SQL by Marco Russo

How to get value of Radio Buttons?

I found that using the Common Event described above works well and you could have the common event set up like this:

private void checkChanged(object sender, EventArgs e)
    {
        foreach (RadioButton r in yourPanel.Controls)
        {
            if (r.Checked)
                textBox.Text = r.Text;
        }
    }

Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)

Repeat rows of a data.frame

My solution similar as mefa:::rep.data.frame, but a little faster and cares about row names:

rep.data.frame <- function(x, times) {
    rnames <- attr(x, "row.names")
    x <- lapply(x, rep.int, times = times)
    class(x) <- "data.frame"
    if (!is.numeric(rnames))
        attr(x, "row.names") <- make.unique(rep.int(rnames, times))
    else
        attr(x, "row.names") <- .set_row_names(length(rnames) * times)
    x
}

Compare solutions:

library(Lahman)
library(microbenchmark)
microbenchmark(
    mefa:::rep.data.frame(Batting, 10),
    rep.data.frame(Batting, 10),
    Batting[rep.int(seq_len(nrow(Batting)), 10), ],
    times = 10
)
#> Unit: milliseconds
#>                                            expr       min       lq     mean   median        uq       max neval cld
#>              mefa:::rep.data.frame(Batting, 10) 127.77786 135.3480 198.0240 148.1749  278.1066  356.3210    10  a 
#>                     rep.data.frame(Batting, 10)  79.70335  82.8165 134.0974  87.2587  191.1713  307.4567    10  a 
#>  Batting[rep.int(seq_len(nrow(Batting)), 10), ] 895.73750 922.7059 981.8891 956.3463 1018.2411 1127.3927    10   b

Class method decorator with self arguments?

Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr if you don't want to hardcode the attribute name:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

Angular 2 filter/search list

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Error: Selection does not contain a main type

The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.

Form/JavaScript not working on IE 11 with error DOM7011

This error occurred for me when using window.location.reload(). Replacing with window.location = window.location.href solved the problem.

How do I create sql query for searching partial matches?

This may work as well.

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

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

In my case, the issue was not resolved by updating butterknife

from: "com.jakewharton:butterknife:8.4.0" to: "com.jakewharton:butterknife:8.8.1"

I've tried to @BindView inside Adapter class and no success. As soon I used .findViewById(R.id.message_time), compilation had been completed successfully.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:

http://www.youtube.com/watch?v=y1c7WFMMkZ4

When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.

What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

How to style the option of an html "select" element?

You can add a class and gives font-weight:700; in option. But by using this all the text will become bold.

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.

Calculating a directory's size using Python?

You can do something like this :

import commands   
size = commands.getoutput('du -sh /path/').split()[0]

in this case I have not tested the result before returning it, if you want you can check it with commands.getstatusoutput.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Loop through an array of strings in Bash?

The declare array doesn't work for Korn shell. Use the below example for the Korn shell:

promote_sla_chk_lst="cdi xlob"

set -A promote_arry $promote_sla_chk_lst

for i in ${promote_arry[*]};
    do
            echo $i
    done

Table header to stay fixed at the top when user scrolls it out of view with jQuery

Fix your issue with this

tbody {
  display: table-caption;
  height: 200px;
  caption-side: bottom;
  overflow: auto;
}

Get MD5 hash of big files in Python

Below I've incorporated suggestion from comments. Thank you al!

python < 3.7

import hashlib

def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
    h = hash_factory()
    with open(filename,'rb') as f: 
        for chunk in iter(lambda: f.read(chunk_num_blocks*h.block_size), b''): 
            h.update(chunk)
    return h.digest()

python 3.8 and above

import hashlib

def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
    h = hash_factory()
    with open(filename,'rb') as f: 
        while chunk := f.read(chunk_num_blocks*h.block_size): 
            h.update(chunk)
    return h.digest()

original post

if you care about more pythonic (no 'while True') way of reading the file check this code:

import hashlib

def checksum_md5(filename):
    md5 = hashlib.md5()
    with open(filename,'rb') as f: 
        for chunk in iter(lambda: f.read(8192), b''): 
            md5.update(chunk)
    return md5.digest()

Note that the iter() func needs an empty byte string for the returned iterator to halt at EOF, since read() returns b'' (not just '').

Where should I put the log4j.properties file?

You have to put it in the root directory, that corresponds to your execution context.

Example:

    MyProject
       src
           MyClass.java
           log4j.properties

If you start executing from a different project, you need to have that file in the project used for starting the execution. For example, if a different project holds some JUnit tests, it needs to have also its log4j.properties file.


I suggest using log4j.xml instead of the log4j.properties. You have more options, get assistance from your IDE and so on...

How can I convert an integer to a hexadecimal string in C?

Interesting that these answers utilize printf like it is a given. printf converts the integer to a Hexadecimal string value.

//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base        = number base for conversion;  decimal=10,hex=16
// char sign       = signed or unsigned output
// char *outbuf   = buffer to hold the output number
//*************************************************************

void prntnum(unsigned long n, int base, char sign, char *outbuf)
{

    int i = 12;
    int j = 0;

    do{
        outbuf[i] = "0123456789ABCDEF"[num % base];
        i--;
        n = num/base;
    }while( num > 0);

    if(sign != ' '){
        outbuf[0] = sign;
        ++j;
    }

    while( ++i < 13){
       outbuf[j++] = outbuf[i];
    }

    outbuf[j] = 0;

}

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

How to clear or stop timeInterval in angularjs?

var promise = $interval(function(){
    if($location.path() == '/landing'){
        $rootScope.$emit('testData',"test");
        $interval.cancel(promise);
    }
},2000);

Jquery each - Stop loop and return object

here :

http://jsbin.com/ucuqot/3/edit

function findXX(word)
{  
  $.each(someArray, function(i,n)
  {
    $('body').append('-> '+i+'<br />');
    if(n == word)
    {
      return false;
    }   
  });  
}

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

Client on Node.js: Uncaught ReferenceError: require is not defined

I confirm. We must add:

webPreferences: {
    nodeIntegration: true
}

For example:

mainWindow = new BrowserWindow({webPreferences: {
    nodeIntegration: true
}});

For me, the problem has been resolved with that.

Export to CSV via PHP

I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.

ffmpeg usage to encode a video to H264 codec format

I believe you have libx264 installed and configured with ffmpeg to convert video to h264... Then you can try with -vcodec libx264... The -format option is for showing available formats, this is not a conversion option I think...

Printing the last column of a line in a file

ls -l | awk '{print $9}' | tail -n1

Jenkins: Failed to connect to repository

In our case git had to be installed on the Jenkins server.

Count the Number of Tables in a SQL Server Database

USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();

jQuery AJAX form data serialize using PHP

_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
    var form=$("#myForm");_x000D_
    $("#smt").click(function(){_x000D_
        $.ajax({_x000D_
            type:"POST",_x000D_
            url:form.attr("action"),_x000D_
            data:form.serialize(),_x000D_
            success: function(response){_x000D_
                console.log(response);  _x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

This is perfect code , there is no problem.. You have to check that in php script.

Write applications in C or C++ for Android?

The official position seems to be that this isn't something you'd ever "want to do". See this thread on the Android Developers list. Google envisage android running on a variety of different devices (CPUs, displays, etc). The best way to enable development is therefore to use (portable) managed code that targets the Dalvik VM. For this reason, the Android SDK doesn't support C/C++.

BUT, take a look at this page:

Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.

The managed application framework appears to be layered on-top of these libraries. The page goes on to list the C/C++ libs: standard C library, media, 3D, SQL lite, and others.

So all you need is a compiler chain that will compile C/C++ to the appropriate CPU (ARM, in the case of the G1). Some brief instructions on how to do this are here.

What I don't know is where to find descriptions of the APIs that these libraries provide. I'd guess there may be header files buried in the SDK somewhere, but documentation may be sketchy/missing. But I think it can be done!

Hope thats useful. For the record, I haven't written any native android apps - just a few simple managed ones.

Andy

How do I ignore a directory with SVN?

To expand slightly, if you're doing this with the svn command-line tool, you want to type:

svn propedit svn:ignore path/to/dir

which will open your text-editor of choice, then type '*' to ignore everything inside it, and save+quit - this will include the directory itself in svn, but ignore all the files inside it, to ignore the directory, use the path of the parent, and then type the name of the directory in the file. After saving, run an update ('svn up'), and then check in the appropriate path.

How do MySQL indexes work?

Let's suppose you have a book, probably a novel, a thick one with lots of things to read, hence lots of words. Now, hypothetically, you brought two dictionaries, consisting of only words that are only used, at least one time in the novel. All words in that two dictionaries are stored in typical alphabetical order. In hypothetical dictionary A, words are printed only once while in hypothetical dictionary B words are printed as many numbers of times it is printed in the novel. Remember, words are sorted alphabetically in both the dictionaries. Now you got stuck at some point while reading a novel and need to find the meaning of that word from anyone of those hypothetical dictionaries. What you will do? Surely you will jump to that word in a few steps to find its meaning, rather look for the meaning of each of the words in the novel, from starting, until you reach that bugging word.

This is how the index works in SQL. Consider Dictionary A as PRIMARY INDEX, Dictionary B as KEY/SECONDARY INDEX, and your desire to get for the meaning of the word as a QUERY/SELECT STATEMENT. The index will help to fetch the data at a very fast rate. Without an index, you will have to look for the data from the starting, unnecessarily time-consuming costly task.

For more about indexes and types, look this.

How do I use a Boolean in Python?

Unlike Java where you would declare boolean flag = True, in Python you can just declare myFlag = True

Python would interpret this as a boolean variable

Pure Javascript listen to input value change

Default usage

el.addEventListener('input', function () {
    fn();
});

But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

var event = new Event('input');
el.addEventListener('input', function () { 
  fn();
});
form.addEventListener('input', function () { 
  anotherFn();
});


el.value = 'something';
el.dispatchEvent(input);

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

"ssl module in Python is not available" when installing package with pip3

Downgrading openssl worked for me,

brew switch openssl 1.0.2s

How to initialize an array in angular2 and typescript

hi @JackSlayer94 please find the below example to understand how to make an array of size 5.

_x000D_
_x000D_
class Hero {_x000D_
    name: string;_x000D_
    constructor(text: string) {_x000D_
        this.name = text;_x000D_
    }_x000D_
_x000D_
    display() {_x000D_
        return "Hello, " + this.name;_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
    heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
    console.log(heros[i].display());_x000D_
}
_x000D_
_x000D_
_x000D_

Find the most popular element in int[] array

You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.

Second largest element: Let us take example : [1,5,4,2,3] in this case, Second largest element will be 4.

  1. Sort the Array in descending order, once the sort done output will be A = [5,4,3,2,1]

  2. Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.

private static int getMostOccuringElement(int[] A) { Map occuringMap = new HashMap();

    //count occurences
    for (int i = 0; i < A.length; i++) { 
        if (occuringMap.get(A[i]) != null) {
            int val = occuringMap.get(A[i]) + 1;
            occuringMap.put(A[i], val);
        } else {
            occuringMap.put(A[i], 1);
        }
    }

    //find maximum occurence
    int max = Integer.MIN_VALUE; 
    int element = -1;
    for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            element = entry.getKey();
        }
    }
    return element;
}

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Can you break from a Groovy "each" closure?

You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Insert default value when parameter is null

chrisofspades,

As far as I know that behavior is not compatible with the way the db engine works, but there is a simple (i don't know if elegant, but performant) solution to achive your two objectives of DO NOT

  1. maintain the default value in multiple places, and
  2. use multiple insert statements.

The solution is to use two fields, one nullable for insert, and other one calculated to selections:

CREATE TABLE t (
    insValue VARCHAR(50) NULL
    , selValue AS ISNULL(insValue, 'something')
)

DECLARE @d VARCHAR(10)
INSERT INTO t (insValue) VALUES (@d) -- null
SELECT selValue FROM t

This method even let You centralize the management of business defaults in a parameter table, placing an ad hoc function to do this, vg changing:

selValue AS ISNULL(insValue, 'something')

for

selValue AS ISNULL(insValue, **getDef(t,1)**)

I hope this helps.

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Launch custom android application from android browser

example.php:

<?php
if(!isset($_GET['app_link'])){  ?>   
    <iframe src="example.php?app_link=YourApp://blabla" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <iframe src="example.php?full_link=http://play.google.com/xyz" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <?php 
}
else { ?>
    <script type="text/javascript">
    self.window.location        = '<?php echo $_GET['app_link'];?>';
    window.parent.location.href = '<?php echo $_GET['full_link'];?>';
    </script>
<?php 
}

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

How to get request URI without context path?

With Spring you can do:

String path = new UrlPathHelper().getPathWithinApplication(request);

Error With Port 8080 already in use

It has been long time, but I faced the same Issue, and solved it as follow: 1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..

  1. My Issue, was that more than 1 instance of java was running, I was changing ports, and not looking back, so it kept running other java processes, with that specific port. for windows users, : ALT+Shift+Esc, and end java processes that you are not using and now you should be able to re-use your port 8080

Cannot hide status bar in iOS7

Try adding the following method to your app's root view controller:

- (BOOL)prefersStatusBarHidden
    {
        return YES;
    }

Deny access to one specific folder in .htaccess

We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.

Order Allow,Deny 
Deny from all 

Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

your final .htaccess file will look like

Order Allow,Deny 
Deny from all 

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

Source from Allow access to specific file types in a protected directory

How to define a circle shape in an Android XML drawable file?

You can use VectorDrawable as below :

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="200dp"
    android:viewportHeight="64"
    android:viewportWidth="64">

    <path
        android:fillColor="#ff00ff"
        android:pathData="M22,32
        A10,10 0 1,1 42,32
        A10,10 0 1,1 22,32 Z" />
</vector>

The above xml renders as :

enter image description here

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

How can I specify a [DllImport] path at runtime?

set the dll path in the config file

<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />

before calling the dll in you app, do the following

string dllPath= ConfigurationManager.AppSettings["dllPath"];    
   string appDirectory = Path.GetDirectoryName(dllPath);
   Directory.SetCurrentDirectory(appDirectory);

then call the dll and you can use like below

 [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Run cron job only if it isn't already running

The way I am doing it when I am running php scripts is:

The crontab:

* * * * * php /path/to/php/script.php &

The php code:

<?php
if (shell_exec('ps aux | grep ' . __FILE__ . ' | wc  -l') > 1) {
    exit('already running...');
}
// do stuff

This command is searching in the system process list for the current php filename if it exists the line counter (wc -l) will be greater then one because the search command itself containing the filename

so if you running php crons add the above code to the start of your php code and it will run only once.

Scala: write string to file in one statement

import sys.process._
"echo hello world" #> new java.io.File("/tmp/example.txt") !

What exactly does an #if 0 ..... #endif block do?

I'd like to add on for the #else case:

#if 0
   /* Code here will NOT be complied. */
#else
   /* Code will be compiled. */
#endif


#if 1
   /* Code will be complied. */
#else
   /* Code will NOT be compiled. */
#endif

Indenting code in Sublime text 2?

No one seems to love mac re-indentation, So here How I do it:

[
   { "keys": ["command+shift+i"], "command": "reindent"}
]

In Preferences > Key Binding - User

One more extra tip: add

{ "keys": ["command+0"], "command": "focus_side_bar" }

to have sidebar file tree view navigation using keyboard.

Note: Add , at the end of each {}, if you have more than one {} set of objects

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

PHPUnit assert that an exception was thrown?

<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.

How to comment out a block of code in Python

In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.

Windows batch - concatenate multiple text files into one

Place all files need to copied in a separate folder, for ease place them in c drive.

Open Command Prompt - windows>type cmd>select command prompt.

You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.

After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.

Now type : 'copy *.txt [newfile_name].txt' and press enter.

Done!

All the text in individual files will be copied to [newfile_name].txt

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:

If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="@this" to your command components.

As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both @form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="@this" and render="@none" respectively.

Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

Remove CSS class from element with JavaScript (no jQuery)

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.


UPDATE: To support class names containing dash character, such as "My-Class", use

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

How can you float: right in React Native?

<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
  <Text>
  Some Text
  </Text>
</View>

flexDirection: If you want to move horizontally (row) or vertically (column)

justifyContent: the direction you want to move.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

Update v3: https://www.npmjs.com/package/windows-build-tools

npm install --global windows-build-tools

downloads and installs Visual C++ Build Tools 2015, provided free of charge by Microsoft. These tools are required to compile popular native modules. It will also install Python 2.7, configuring your machine and npm appropriately.

Update v2:

node-gyp updated their readme to include HOW-TO for windows

Original:

No need for the entire visual studio, you can download just the build tools

Microsoft Build Tools 2013 : http://www.microsoft.com/en-us/download/details.aspx?id=40760

run cmd to set global flag to use the 2013 version:

npm config set msvs_version 2013 --global

after this everything should be back to normal and your npm install / node-gyp rebuild will work

Truncate (not round) decimal places in SQL Server

SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;

Would give you 2 values after the decimal point. (MS SQL SERVER)

How do I set cell value to Date and apply default Excel date format?

This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos is position of column.

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Test{ 
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
    row=iterator.next();

    cell=row.getCell(pos-1);
    //CellStyle cellStyle = wb.createCellStyle();
    XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d=null;
    try {
        d= sdf.parse(cell.getStringCellValue());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        d=null;
        e.printStackTrace();
        continue;
    }
    cell.setCellValue(d);
    cell.setCellStyle(cellStyle);
   }

file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Nginx -- static file serving confusion with root & alias

server {
    server_name xyz.com;
    root /home/ubuntu/project_folder/;

    client_max_body_size 10M;
    access_log  /var/log/nginx/project.access.log;
    error_log  /var/log/nginx/project.error.log;

    location /static {
        index index.html;
    }

    location /media {
        alias /home/ubuntu/project/media/;
    }
}

Server block to live the static page on nginx.

Center icon in a div - horizontally and vertically

Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:

CSS

#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */
}

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

HTML

<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>
    </a>
</div>

JSFiddle

Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.

facebook: permanent Page Access Token?

Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:

  1. From (Graph Explorer tool)0, select the relevant permissions and get the short lived page access token.
  2. (Go to debugger tool)1 and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
  3. Copy the the extended token and use it in this API:
  4. https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
  5. This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.

Why should we typedef a struct so often in C?

typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:

struct bar;
struct foo;

struct foo {
    struct bar *b;
};

struct bar {
    struct foo *f;
};

Of course you can always add:

typedef struct foo foo_t;
typedef struct bar bar_t;

What exactly is the point of that?

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  
# define __SYSCALL_SLONG_TYPE   __SQUAD_TYPE  
#else
# define __SYSCALL_SLONG_TYPE   __SLONGWORD_TYPE
#endif  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
#else
__extension__ typedef long long int __quad_t;

Modify property value of the objects in list using Java 8 streams

You can do it using streams map function like below, get result in new stream for further processing.

Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
        newFruits.forEach(fruit->{
            System.out.println(fruit.name);
        });

How to extract string following a pattern with grep, regex or perl

this could do it:

perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'

Delegation: EventEmitter or Observable in Angular

Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.


Original answer: (don't do this)

Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:

import {EventEmitter} from 'angular2/core';

export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emit(number) {
    this.navchange.emit(number);
  }
  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.navchange.subscribe(data => call.callback(component, data));
  }
}

@Component({
  selector: 'obs-comp',
  template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private navService:NavService) {
   this.subscription = this.navService.subscribe(this, this.selectedNavItem);
  }
  selectedNavItem(item: number) {
    console.log('item index changed!', item);
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
  `,
})
export class Navigation {
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emit(item);
  }
}

If you try the Plunker, there are a few things I don't like about this approach:

  • ObservingComponent needs to unsubscribe when it is destroyed
  • we have to pass the component to subscribe() so that the proper this is set when the callback is called

Update: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange EventEmitter property:

constructor(private navService:NavService) {
   this.subscription = this.navService.navchange.subscribe(data =>
     this.selectedNavItem(data));
}

If we subscribe directly, then we wouldn't need the subscribe() method on the NavService.

To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter() method and use that:

getNavChangeEmitter() { return this.navchange; }  // in NavService

constructor(private navService:NavService) {  // in ObservingComponent
   this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
     this.selectedNavItem(data));
}

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

Finding Key associated with max Value in a Java Map

For completeness, here is a way of doing it

countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();

or

Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();

or

Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();

Insert json file into mongodb

Below command worked for me

mongoimport --db test --collection docs --file example2.json

when i removed the extra newline character before Email attribute in each of the documents.

example2.json

{"FirstName": "Bruce", "LastName": "Wayne", "Email": "[email protected]"}
{"FirstName": "Lucius", "LastName": "Fox", "Email": "[email protected]"}
{"FirstName": "Dick", "LastName": "Grayson", "Email": "[email protected]"}

Angular2 set value for formGroup

I have implemented a temporary solution until angular2 support form updateValue

 initFormGroup(form: FormGroup, data: any) {
        for(var key in form.controls) {
          console.log(key);
          if(form.controls[key] instanceof FormControl) {
            if(data[key]){
              let control = <FormControl>form.controls[key];
              this.initFormControl(control,data[key]);
            }
          } else if(form.controls[key] instanceof FormGroup) {
            if(data[key]){
              this.initFormGroup(<FormGroup>form.controls[key],data[key]);
            }
          } else if(form.controls[key] instanceof FormArray) {
            var control = <FormArray>form.controls[key];
            if(data[key])
            this.initFormArray(control, data[key]);
          }
        }
      }
      initFormArray(array: FormArray, data: Array<any>){
    if(data.length>0){
      var clone = array.controls[0];
      array.removeAt(0);
      for(var idx in data) {
        array.push(_.cloneDeep(clone));
        if(clone instanceof FormGroup)
          this.initFormGroup(<FormGroup>array.controls[idx], data[idx]);
        else if(clone instanceof FormControl)
          this.initFormControl(<FormControl>array.controls[idx], data[idx]);
        else if(clone instanceof FormArray)
          this.initFormArray(<FormArray>array.controls[idx], data[idx]);
      }
    }
  }


initFormControl(control: FormControl, value:any){
    control.updateValue(value);
  }

usage:

this.initFormGroup(this.form, {b:"data",c:"data",d:"data",e:["data1","data2"],f:data});

note: form and data must have the same structure and i have used lodash for deepcloning jQuery and other libs can do as well

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

How to get rid of blank pages in PDF exported from SSRS

The problem for me was that SSRS purposely treats your white space as if you intend it be honored:

enter image description here

As well as white space, make sure there is no right margin.

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

phpmailer error "Could not instantiate mail function"

This worked for me

$mail->SetFrom("[email protected]","my name", 0); //notice the third parameter

How to succinctly write a formula with many variables from a data frame?

A slightly different approach is to create your formula from a string. In the formula help page you will find the following example :

## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))

Then if you look at the generated formula, you will get :

R> fmla
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    x22 + x23 + x24 + x25

throwing exceptions out of a destructor

I am in the group that considers that the "scoped guard" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to std::terminate since destructors are implicitly annotated with noexcept.

Andrzej Krzemienski has a great post on the topic of destructors that throw:

He points out that C++11 has a mechanism to override the default noexcept for destructors:

In C++11, a destructor is implicitly specified as noexcept. Even if you add no specification and define your destructor like this:

  class MyType {
        public: ~MyType() { throw Exception(); }            // ...
  };

The compiler will still invisibly add specification noexcept to your destructor. And this means that the moment your destructor throws an exception, std::terminate will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:

  • Explicitly specify your destructor as noexcept(false),
  • Inherit your class from another one that already specifies its destructor as noexcept(false).
  • Put a non-static data member in your class that already specifies its destructor as noexcept(false).

Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to std::terminate and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using std::uncaught_exception().

Return from a promise then()

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

Hope this helps!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }

Convert pandas dataframe to NumPy array

You can use the to_records method, but have to play around a bit with the dtypes if they are not what you want from the get go. In my case, having copied your DF from a string, the index type is string (represented by an object dtype in pandas):

In [102]: df
Out[102]: 
label    A    B    C
ID                  
1      NaN  0.2  NaN
2      NaN  NaN  0.5
3      NaN  0.2  0.5
4      0.1  0.2  NaN
5      0.1  0.2  0.5
6      0.1  NaN  0.5
7      0.1  NaN  NaN

In [103]: df.index.dtype
Out[103]: dtype('object')
In [104]: df.to_records()
Out[104]: 
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
In [106]: df.to_records().dtype
Out[106]: dtype([('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Converting the recarray dtype does not work for me, but one can do this in Pandas already:

In [109]: df.index = df.index.astype('i8')
In [111]: df.to_records().view([('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Out[111]:
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Note that Pandas does not set the name of the index properly (to ID) in the exported record array (a bug?), so we profit from the type conversion to also correct for that.

At the moment Pandas has only 8-byte integers, i8, and floats, f8 (see this issue).

Why does GitHub recommend HTTPS over SSH?

It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.

Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.

Set Canvas size using javascript

Try this:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);

document.write('')

works for iframe and well.

How to access data/data folder in Android device?

you can copy this db file to somewhere in eclipse explorer (eg:sdcard or PC),and you can use sqlite to access and update this db file .

How do I raise the same Exception with a custom message in Python?

None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.

This worked for me:

exception_raised = False
try:
    do_something_that_might_raise_an_exception()
except ValueError as e:
    message = str(e)
    exception_raised = True

if exception_raised:
    message_to_prepend = "Custom text"
    raise ValueError(message_to_prepend + message)

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

This worked for me when I encountered the same issue on my KitKat. Remove your account from the device (Settings > Accounts > Google > Remove Account)

Remove the following data: Settings> Applications > All> Downloads > delete data. Settings> Applications > All> Play Store> delete data. Settings> Apps > All> Google Services Framework (or if they have it in English: Google Service Framework) > delete data.

Log in again and it was fixed for me.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Like the other answers said, sp_reset_connection indicates that connection pool is being reused. Be aware of one particular consequence!

Jimmy Mays' MSDN Blog said:

sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.

UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.

ref: SQL Server: Isolation level leaks across pooled connections

Here is some additional information:

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • All error states and numbers (like @@error)

  • Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query

  • Waits for any outstanding I/O operations that is outstanding

  • Frees any held buffers on the server by the connection

  • Unlocks any buffer resources that are used by the connection

  • Releases all allocated memory owned by the connection

  • Clears any work or temporary tables that are created by the connection

  • Kills all global cursors owned by the connection

  • Closes any open SQL-XML handles that are open

  • Deletes any open SQL-XML related work tables

  • Closes all system tables

  • Closes all user tables

  • Drops all temporary objects

  • Aborts open transactions

  • Defects from a distributed transaction when enlisted

  • Decrements the reference count for users in current database which releases shared database locks

  • Frees acquired locks

  • Releases any acquired handles

  • Resets all SET options to the default values

  • Resets the @@rowcount value

  • Resets the @@identity value

  • Resets any session level trace options using dbcc traceon()

  • Resets CONTEXT_INFO to NULL in SQL Server 2005 and newer [ not part of the original article ]

sp_reset_connection will NOT reset:

  • Security context, which is why connection pooling matches connections based on the exact connection string

  • Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when sp_setapprole is executed.

Note: I am including the list here as I do not want it to be lost in the ever transient web.

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

Why is it OK to return a 'vector' from a function?

This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.

The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.

On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.

So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

/Users/{user}/Library/Application Support/Sublime Text 2/Packages

Get to it quickly from within Sublime via the menu at Sublime Text 2... Preferences... Browse Packages

How do I get an animated gif to work in WPF?

Its very simple if you use <MediaElement>:

<MediaElement  Height="113" HorizontalAlignment="Left" Margin="12,12,0,0" 
Name="mediaElement1" VerticalAlignment="Top" Width="198" Source="C:\Users\abc.gif"
LoadedBehavior="Play" Stretch="Fill" SpeedRatio="1" IsMuted="False" />

Java for loop syntax: "for (T obj : objects)"

That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries().

Stylesheet not updating

I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.

  1. This is how I do it in my Django template:

<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>

Where adding ?{% now 'U' %} to the end of your css file would fix this issue.

  1. How you would do it with just CSS (hopefully someone edits this to a cleaner version, this looks a little janky but it does work, tested it):

<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />

Where ?Wednesday 2nd February 2020 12PM (current date) seems to fix the issue, I also noticed just putting the time fixes it too.

How to do a regular expression replace in MySQL?

We can use IF condition in SELECT query as below:

Suppose that for anything with "ABC","ABC1","ABC2","ABC3",..., we want to replace with "ABC" then using REGEXP and IF() condition in the SELECT query, we can achieve this.

Syntax:

SELECT IF(column_name REGEXP 'ABC[0-9]$','ABC',column_name)
FROM table1 
WHERE column_name LIKE 'ABC%';

Example:

SELECT IF('ABC1' REGEXP 'ABC[0-9]$','ABC','ABC1');

How do I combine 2 select statements into one?

If they are from the same table, I think UNION is the command you're looking for.

(If you'd ever need to select values from columns of different tables, you should look at JOIN instead...)

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

CSS Circular Cropping of Rectangle Image

I know many of the solutions mentioned above works, you can as well try flex.

But my image was rectangular and not fitting properly. so this is what i did.

.parentDivClass {
    position: relative;
    height: 100px;
    width: 100px;
    overflow: hidden;
    border-radius: 50%;
    margin: 20px;
    display: flex;
    justify-content: center;
}

and for the image inside, you can use,

child Img {
    display: block;
    margin: 0 auto;
    height: 100%;
    width: auto;
}

This is helpful when you are using bootstrap 4 classes.

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

how to change class name of an element by jquery

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');

SQL - select distinct only on one column

Since you don't care, I chose the max ID for each number.

select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id

Query Explanation

 select 
    tbl.*  -- give me all the data from the base table (tbl) 
 from 
    tbl    
    inner join (  -- only return rows in tbl which match this subquery
        select 
            max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
        from 
            tbl 
        group by 
            NUMBER            -- how to group rows for the MAX aggregation
    ) maxID
        on maxID.maxID = tbl.id -- join condition ie only return rows in tbl 
                                -- whose ID is also a MAX ID for a given NUMBER

How to set and reference a variable in a Jenkinsfile

I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)

    pipeline {
        agent any
            stages {
                stage("foo") {
                    steps {
                        script {
                            try {                    
                                env.FILENAME = readFile 'output.txt'
                                echo "${env.FILENAME}"
                            }
                            catch(Exception e) {
                                //do something, e.g. echo 'File not found'
                            }
                        }
                   }
    }

Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

How can I use optional parameters in a T-SQL stored procedure?

This also works:

    ...
    WHERE
        (FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
        (LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
        (Title IS NULL OR Title = ISNULL(@Title, Title))

javascript create array from for loop

You need to push i

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i < yearEnd+1; i++) {
    arr.push(i);
}

Then, your resulting array will be:

arr = [2000, 2001, 2003, ... 2039, 2040]

Hope this helps

Align DIV to bottom of the page

Try position:fixed; bottom:0;. This will make your div to stay fixed at the bottom.

WORKING DEMO

The HTML:

<div id="bottom-stuff">
  <div id="search"> MY DIV </div>
</div>
<div id="bottom"> MY DIV </div>

The CSS:

#bottom-stuff {

    position: relative;
}

#bottom{

    position: fixed; 
    background:gray; 
    width:100%;
    bottom:0;
}

#search{height:5000px; overflow-y:scroll;}

Hope this helps.

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

_x000D_
_x000D_
//find duplicates:_x000D_
//sort, then reduce - concat values equal previous element, skip others_x000D_
_x000D_
//input_x000D_
var a = [1, 2, 3, 1, 2, 1, 2]_x000D_
_x000D_
//short version:_x000D_
var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]_x000D_
_x000D_
//readable version:_x000D_
var duplicates = a.sort().reduce((output, element, index, input) => {_x000D_
  if ((index > 0) && (element === input[index - 1]))_x000D_
    return output.concat(element)_x000D_
  return output_x000D_
}, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]
_x000D_
_x000D_
_x000D_

$.focus() not working

Some of the answers here suggest using setTimeout to delay the process of focusing on the target element. One of them mentions that the target is inside a modal dialog. I cannot comment further on the correctness of the setTimeoutsolution without knowing the specific details of where it was used. However, I thought I should provide an answer here to help out people who run into this thread just as I did

The simple fact of the matter is that you cannot focus on an element which is not yet visible. If you run into this problem ensure that the target is actually visible when the attempt to focus it is made. In my own case I was doing something along these lines

$('#elementid').animate({left:0,duration:'slow'});
$('#elementid').focus();

This did not work. I only realized what was going on when I executed $('#elementid').focus()` from the console which did work. The difference - in my code above the target there is no certainty that the target will infact be visible since the animation may not be complete. And there lies the clue

$('#elementid').animate({left:0,duration:'slow',complete:focusFunction});

function focusFunction(){$('#elementid').focus();}

works just as expected. I too had initially put in a setTimeout solution and it worked too. However, an arbitrarily chosen timeout is bound to break the solution sooner or later depending on how slowly the host device goes about the process of ensuring that the target element is visible.

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<button>
  <a href="https://accounts.google.com/ServiceLogin?continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Den-ha-apac-in-bk-refresh14&service=mail&dsh=-3966619600017513905"
     style="cursor:default">sign in</a>
</button>

Unable to copy a file from obj\Debug to bin\Debug

in my case problem was in web config. I just removed

<system.web>
    <hostingEnvironment shadowCopyBinAssemblies="false" />
  </system.web>

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

Generating a random hex color code with PHP

Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.

See Wikipedia for more info.

In other words, use any colour from #000000 to #FFFFFF.

edit: Dear downvoters. Check the edit history for the question first.

Change priorityQueue to max priorityqueue

How about like this:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...

Integer val = null;
while( (val = queue.poll()) != null) {
    System.out.println(val);
}

The Collections.reverseOrder() provides a Comparator that would sort the elements in the PriorityQueue in a the oposite order to their natural order in this case.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

Can anyone explain IEnumerable and IEnumerator to me?

Differences between IEnumerable and IEnumerator :

  • IEnumerable uses IEnumerator internally.
  • IEnumerable doesn't know which item/object is executing.
  • Whenever we pass IEnumerator to another function, it knows the current position of item/object.
  • Whenever we pass an IEnumerable collection to another function, it doesn't know the current position of item/object (doesn't know which item its executing)

    IEnumerable have one method GetEnumerator()

public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

IEnumerator has one property called Current and two methods, Reset() and MoveNext() (which is useful for knowing the current position of an item in a list).

public interface IEnumerator
{
     object Current { get; }
     bool MoveNext();
     void Reset();
}

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

<script type="text/javascript">
                    $(document).ready(function(e) {
                        $(".mqimg").mouseover(function()
                        {
                            $("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />"); 
                        })
                        $(".mqimg").mouseout(function()
                        {
                            $("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
                        })
                    });
                    </script>
                    <style>
                    .mqimg{ cursor:pointer;}
                    </style>
                    <div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
                    <div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />

Variable length (Dynamic) Arrays in Java

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

But your best option is to use IntList from jacarta commons. (here)

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

Iterate through a HashMap

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

How to get the last day of the month?

from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)

How to connect to a remote Windows machine to execute commands using python?

I have personally found pywinrm library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

Disabling Log4J Output in Java

You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.

You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.

You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.

PyCharm import external library

Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.

My project is now behaving as I would expect.

These are the windows you would see while following the instructions

Calling a php function by onclick event

In Your HTML

<input type="button" name="Release" onclick="hello();" value="Click to Release" />

In Your JavaScript

<script type="text/javascript">
    function hello(){
        alert('Your message here');
    }
</script>

If you need to run PHP in JavaScript You need to use JQuery Ajax Function

<script type="text/javascript">
function hello(){
    $.ajax(
{     
 type:    'post',
 url:     'folder/my_php_file.php',
 data:    '&id=' + $('#id').val() + '&name=' +     $('#name').val(),
 dataType: 'json',
 //alert(data);
 success: function(data) 
 {
  //alert(data);
 }   
});
}
</script>

Now in your my_php_file.php file

<?php 
    echo 'hello';
?>

Good Luck !!!!!

Get underlined text with Markdown

You can wrote **_bold and italic_** and re-style it to underlined text, like this:

strong>em,
em>strong,
b>i,
i>b {
    font-style:normal;
    font-weight:normal;
    text-decoration:underline;
}

How to remove package using Angular CLI?

I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes. Be careful of untracked files from .gitignore.

Android ListView with different layouts for each row

In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.

What is the id( ) function used for?

Be carefull (concerning the answer just below)...That's only true because 123 is between -5 and 256...

In [111]: q = 257                                                         

In [112]: id(q)                                                            
Out[112]: 140020248465168

In [113]: w = 257                                                         

In [114]: id(w)                                                           
Out[114]: 140020274622544

In [115]: id(257)                                                         
Out[115]: 140020274622768

.NET String.Format() to add commas in thousands place for a number

String.Format("0,###.###"); also works with decimal places

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

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

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

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

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

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

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

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

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

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

Symfony - generate url with parameter in controller

Get the router from the container.

$router = $this->get('router');

Then use the router to generate the Url

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));

Find the least number of coins required that can make any change from 1 to 99 cents

What you are looking for is Dynamic Programming.

You don't actually have to enumerate all the possible combinations for every possible values, because you can build it on top of previous answers.

You algorithm need to take 2 parameters:

  • The list of possible coin values, here [1, 5, 10, 25]
  • The range to cover, here [1, 99]

And the goal is to compute the minimal set of coins required for this range.

The simplest way is to proceed in a bottom-up fashion:

Range     Number of coins (in the minimal set)
          1   5   10   25
[1,1]     1
[1,2]     2
[1,3]     3
[1,4]     4
[1,5]     5
[1,5]*    4   1             * two solutions here
[1,6]     4   1
[1,9]     4   1
[1,10]    5   1             * experience tells us it's not the most viable one :p
[1,10]    4   2             * not so viable either
[1,10]    4   1   1
[1,11]    4   1   1
[1,19]    4   1   1
[1,20]    5   1   1         * not viable (in the long run)
[1,20]    4   2   1         * not viable (in the long run)
[1,20]    4   1   2

It is somewhat easy, at each step we can proceed by adding at most one coin, we just need to know where. This boils down to the fact that the range [x,y] is included in [x,y+1] thus the minimal set for [x,y+1] should include the minimal set for [x,y].

As you may have noticed though, sometimes there are indecisions, ie multiple sets have the same number of coins. In this case, it can only be decided later on which one should be discarded.

It should be possible to improve its running time, when noticing that adding a coin usually allows you to cover a far greater range that the one you added it for, I think.

For example, note that:

 [1,5]    4*1  1*5
 [1,9]    4*1  1*5

we add a nickel to cover [1,5] but this gives us up to [1,9] for free!

However, when dealing with outrageous input sets [2,3,5,10,25] to cover [2,99], I am unsure as how to check quickly the range covered by the new set, or it would be actually more efficient.

SQL select only rows with max value on a column

I like to use a NOT EXIST-based solution for this problem:

SELECT 
  id, 
  rev
  -- you can select other columns here
FROM YourTable t
WHERE NOT EXISTS (
   SELECT * FROM YourTable t WHERE t.id = id AND rev > t.rev
)

This will select all records with max value within the group and allows you to select other columns.

PHP Unset Array value effect on other indexes

The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain.

$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)

How to run a class from Jar which is not the Main-Class in its Manifest file

This answer is for Spring-boot users:

If your JAR was from a Spring-boot project and created using the command mvn package spring-boot:repackage, the above "-cp" method won't work. You will get:

Error: Could not find or load main class your.alternative.class.path

even if you can see the class in the JAR by jar tvf yours.jar.

In this case, run your alternative class by the following command:

java -cp yours.jar -Dloader.main=your.alternative.class.path org.springframework.boot.loader.PropertiesLauncher

As I understood, the Spring-boot's org.springframework.boot.loader.PropertiesLauncher class serves as a dispatching entrance class, and the -Dloader.main parameter tells it what to run.

Reference: https://github.com/spring-projects/spring-boot/issues/20404

What is the best collation to use for MySQL with PHP?

Be very, very aware of this problem that can occur when using utf8_general_ci.

MySQL will not distinguish between some characters in select statements, if the utf8_general_ci collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.

This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.

I'm no DBA, but to avoid this problem, I always go with utf8-bin instead of a case-insensitive one.

The script below describes the problem by example.

-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;

-- next, make sure that your client connection is of the same 
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci

-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
    CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');

-- (verify)
SELECT * FROM `test`;

-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are 
-- case insensitive (ending with _ci) do not distinguish between 
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to 
-- do the same with the 'latin1' charset:
--

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci

-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected). This shows 
-- that the problem with utf8/utf8_generic_ci isn't present 
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same 
-- way (for any sceptics out there):

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Two keys.
--

DROP DATABASE sandbox;