Programs & Examples On #Partitioning

Partitioning is a performance strategy whereby you divide possibly very large groups of data into some number of smaller groups of data.

How to define partitioning of DataFrame?

Use the DataFrame returned by:

yourDF.orderBy(account)

There is no explicit way to use partitionBy on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.

I just stumbled upon the same exact issue, with a dataframe that I want to partition by account. I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions() etc), right?

The following untracked working tree files would be overwritten by merge, but I don't care

The problem is when we have incoming changes that will merge untracked file, git complains. These commands helped me:

git clean -dxf
git pull origin master

JPA : How to convert a native query result set to POJO class collection

Since others have already mentioned all the possible solutions, I am sharing my workaround solution.

In my situation with Postgres 9.4, while working with Jackson,

//Convert it to named native query.
List<String> list = em.createNativeQuery("select cast(array_to_json(array_agg(row_to_json(a))) as text) from myschema.actors a")
                   .getResultList();

List<ActorProxy> map = new ObjectMapper().readValue(list.get(0), new TypeReference<List<ActorProxy>>() {});

I am sure you can find same for other databases.

Also FYI, JPA 2.0 native query results as map

How to install a package inside virtualenv?

To further clarify the other answer here:

Under the current version of virtualenv, the --no-site-packages flag is the default behavior, so you don't need to specify it. However, you are overriding the default by explicitly using the --system-site-packages flag, and that's probably not what you want. The default behavior (without specifying either flag) is to create the virtual environment such that when you are using it, any Python packages installed outside the environment are not accessible. That's typically the right choice because it best isolates the virtual environment from your local computer environment. Python packages installed within the environment will not affect your local computer and vice versa.

Secondly, to use a virtual environment after it's been created, you need to navigate into the virtual environment directory and then run:

bin/activate

What this does is to configure environment variables so that Python packages and any executables in the virtual environment's bin folders will be used before those in the standard locations on your local computer. So, for example, when you type "pip", the version of pip that is inside your virtual environment will run instead of the version of pip on your local machine. This is desirable because pip inside the virtual environment will install packages inside the virtual environment.

The problem you are having is because you are running programs (like ipython) from your local machine, when you instead want to install and run copies of those programs isolated inside your virtual environment. You set this up by creating the environment (without specifying any site-packages flags if you are using the current version), running the activate script mentioned above, then running pip to install any packages you need (which will go inside the environment).

How can I handle the warning of file_get_contents() function in PHP?

try {
   $site="http://www.google.com";
   $content = file_get_content($site);
   echo $content;
} catch (ErrorException $e) {
    // fix the url

}

set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

Display a float with two decimal places in Python

If you actually want to change the number itself instead of only displaying it differently use format()

Format it to 2 decimal places:

format(value, '.2f')

example:

>>> format(5.00000, '.2f')
'5.00'

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

SET versus SELECT when assigning variables?

I believe SET is ANSI standard whereas the SELECT is not. Also note the different behavior of SET vs. SELECT in the example below when a value is not found.

declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */

set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */

How to see the values of a table variable at debug time in T-SQL?

Why not just select the Table and view the variable that way?

SELECT * FROM @d

How can I plot separate Pandas DataFrames as subplots?

Building on @joris response above, if you have already established a reference to the subplot, you can use the reference as well. For example,

ax1 = plt.subplot2grid((50,100), (0, 0), colspan=20, rowspan=10)
...

df.plot.barh(ax=ax1, stacked=True)

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x

With Bootstrap 4 (and Font Awesome), we still can use the input-group wrapper around our form-control element, and now we can use an input-group-append (or input-group-prepend) wrapper with an input-group-text to get the job done:

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
  <div class="input-group-append">
    <span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
  </div>
</div>

It will look something like this (thanks to KyleMit for the screenshot):

enter image description here

Learn more by visiting the Input group documentation.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Label encoding across multiple columns in scikit-learn

Instead of LabelEncoder we can use OrdinalEncoder from scikit learn, which allows multi-column encoding.

Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.

>>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 3], ['Male', 1]])
array([[0., 2.],
       [1., 0.]])

Both the description and example were copied from its documentation page which you can find here:

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html#sklearn.preprocessing.OrdinalEncoder

React JS - Uncaught TypeError: this.props.data.map is not a function

If you're using react hooks you have to make sure that data was initialized as an array. Here's is how it must look like:

const[data, setData] = useState([])

Get the distance between two geo points

private float getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] distance = new float[2];
        Location.distanceBetween(lat1, lon1, lat2, lon2, distance);
        return distance[0];
    }

What's the purpose of SQL keyword "AS"?

When you aren't sure which syntax to choose, especially when there doesn't seem to be much to separate the choices, consult a book on heuristics. As far as I know, the only heuristics book for SQL is 'Joe Celko's SQL Programming Style':

A correlation name is more often called an alias, but I will be formal. In SQL-92, they can have an optional AS operator, and it should be used to make it clear that something is being given a new name. [p16]

This way, if your team doesn't like the convention, you can blame Celko -- I know I do ;)


UPDATE 1: IIRC for a long time, Oracle did not support the AS (preceding correlation name) keyword, which may explain why some old timers don't use it habitually.


UPDATE 2: the term 'correlation name', although used by the SQL Standard, is inappropriate. The underlying concept is that of a ‘range variable’.


UPDATE 3: I just re-read what Celko wrote and he is wrong: the table is not being renamed! I now think:

A correlation name is more often called an alias, but I will be formal. In Standard SQL they can have an optional AS keyword but it should not be used because it may give the impression that something is being renamed when it is not. In fact, it should be omitted to enforce the point that it is a range variable.

How to find nth occurrence of character in a string?

public static int nth(String source, String pattern, int n) {

   int i = 0, pos = 0, tpos = 0;

   while (i < n) {

      pos = source.indexOf(pattern);
      if (pos > -1) {
         source = source.substring(pos+1);
         tpos += pos+1;
         i++;
      } else {
         return -1;
      }
   }

   return tpos - 1;
}

PDO closing connection

$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    // If this is your connection then you have to assign null
    // to your connection variable as follows:
$conn=null;
    // By this way you can close connection in PDO.

How do I get TimeSpan in minutes given two Dates?

double totalMinutes = (end-start).TotalMinutes;

Best way to format multiple 'or' conditions in an if statement (Java)

No you cannot do that in Java. you can however write a method as follows:

boolean isContains(int i, int ... numbers) {
    // code to check if i is one of the numbers
    for (int n : numbers) {
        if (i == n) return true;
    }
    return false;
}

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

Ruby on Rails: How do I add placeholder text to a f.text_field?

For those using Rails(4.2) Internationalization (I18n):

Set the placeholder attribute to true:

f.text_field :attr, placeholder: true

and in your local file (ie. en.yml):

en:
  helpers:
    placeholder:
      model_name:
        attr: "some placeholder text"

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Sorting table rows according to table header column using javascript or jquery

I think this might help you:
Here is the JSFiddle demo:

And here is the code:

_x000D_
_x000D_
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
  init: function() {_x000D_
    if (arguments.callee.done) return;_x000D_
    arguments.callee.done = true;_x000D_
    if (_timer) clearInterval(_timer);_x000D_
    if (!document.createElement || !document.getElementsByTagName) return;_x000D_
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
    forEach(document.getElementsByTagName('table'), function(table) {_x000D_
      if (table.className.search(/\bsortable\b/) != -1) {_x000D_
        sorttable.makeSortable(table);_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
  makeSortable: function(table) {_x000D_
    if (table.getElementsByTagName('thead').length == 0) {_x000D_
      the = document.createElement('thead');_x000D_
      the.appendChild(table.rows[0]);_x000D_
      table.insertBefore(the, table.firstChild);_x000D_
    }_x000D_
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
    if (table.tHead.rows.length != 1) return;_x000D_
    sortbottomrows = [];_x000D_
    for (var i = 0; i < table.rows.length; i++) {_x000D_
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
        sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
      }_x000D_
    }_x000D_
    if (sortbottomrows) {_x000D_
      if (table.tFoot == null) {_x000D_
        tfo = document.createElement('tfoot');_x000D_
        table.appendChild(tfo);_x000D_
      }_x000D_
      for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
        tfo.appendChild(sortbottomrows[i]);_x000D_
      }_x000D_
      delete sortbottomrows;_x000D_
    }_x000D_
    headrow = table.tHead.rows[0].cells;_x000D_
    for (var i = 0; i < headrow.length; i++) {_x000D_
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
        if (mtch) {_x000D_
          override = mtch[1];_x000D_
        }_x000D_
        if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
          headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
        } else {_x000D_
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
        }_x000D_
        headrow[i].sorttable_columnindex = i;_x000D_
        headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
        dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
          if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted',_x000D_
              'sorttable_sorted_reverse');_x000D_
            this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
            sortrevind = document.createElement('span');_x000D_
            sortrevind.id = "sorttable_sortrevind";_x000D_
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';_x000D_
            this.appendChild(sortrevind);_x000D_
            return;_x000D_
          }_x000D_
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
              'sorttable_sorted');_x000D_
            this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
            sortfwdind = document.createElement('span');_x000D_
            sortfwdind.id = "sorttable_sortfwdind";_x000D_
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
            this.appendChild(sortfwdind);_x000D_
            return;_x000D_
          }_x000D_
          theadrow = this.parentNode;_x000D_
          forEach(theadrow.childNodes, function(cell) {_x000D_
            if (cell.nodeType == 1) {_x000D_
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
              cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
            }_x000D_
          });_x000D_
          sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
          if (sortfwdind) {_x000D_
            sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
          }_x000D_
          sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
          if (sortrevind) {_x000D_
            sortrevind.parentNode.removeChild(sortrevind);_x000D_
          }_x000D_
_x000D_
          this.className += ' sorttable_sorted';_x000D_
          sortfwdind = document.createElement('span');_x000D_
          sortfwdind.id = "sorttable_sortfwdind";_x000D_
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
          this.appendChild(sortfwdind);_x000D_
          row_array = [];_x000D_
          col = this.sorttable_columnindex;_x000D_
          rows = this.sorttable_tbody.rows;_x000D_
          for (var j = 0; j < rows.length; j++) {_x000D_
            row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
          }_x000D_
          row_array.sort(this.sorttable_sortfunction);_x000D_
          tb = this.sorttable_tbody;_x000D_
          for (var j = 0; j < row_array.length; j++) {_x000D_
            tb.appendChild(row_array[j][1]);_x000D_
          }_x000D_
          delete row_array;_x000D_
        });_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
_x000D_
  guessType: function(table, column) {_x000D_
    sortfn = sorttable.sort_alpha;_x000D_
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
      if (text != '') {_x000D_
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
          return sorttable.sort_numeric;_x000D_
        }_x000D_
        possdate = text.match(sorttable.DATE_RE)_x000D_
        if (possdate) {_x000D_
          first = parseInt(possdate[1]);_x000D_
          second = parseInt(possdate[2]);_x000D_
          if (first > 12) {_x000D_
            return sorttable.sort_ddmm;_x000D_
          } else if (second > 12) {_x000D_
            return sorttable.sort_mmdd;_x000D_
          } else {_x000D_
            sortfn = sorttable.sort_ddmm;_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return sortfn;_x000D_
  },_x000D_
  getInnerText: function(node) {_x000D_
    if (!node) return "";_x000D_
    hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
      node.getElementsByTagName('input').length;_x000D_
    if (node.getAttribute("sorttable_customkey") != null) {_x000D_
      return node.getAttribute("sorttable_customkey");_x000D_
    } else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
      return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
      return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
      return node.text.replace(/^\s+|\s+$/g, '');_x000D_
    } else {_x000D_
      switch (node.nodeType) {_x000D_
        case 3:_x000D_
          if (node.nodeName.toLowerCase() == 'input') {_x000D_
            return node.value.replace(/^\s+|\s+$/g, '');_x000D_
          }_x000D_
        case 4:_x000D_
          return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        case 1:_x000D_
        case 11:_x000D_
          var innerText = '';_x000D_
          for (var i = 0; i < node.childNodes.length; i++) {_x000D_
            innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
          }_x000D_
          return innerText.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        default:_x000D_
          return '';_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
  reverse: function(tbody) {_x000D_
    // reverse the rows in a tbody_x000D_
    newrows = [];_x000D_
    for (var i = 0; i < tbody.rows.length; i++) {_x000D_
      newrows[newrows.length] = tbody.rows[i];_x000D_
    }_x000D_
    for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
      tbody.appendChild(newrows[i]);_x000D_
    }_x000D_
    delete newrows;_x000D_
  },_x000D_
  sort_numeric: function(a, b) {_x000D_
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(aa)) aa = 0;_x000D_
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(bb)) bb = 0;_x000D_
    return aa - bb;_x000D_
  },_x000D_
  sort_alpha: function(a, b) {_x000D_
    if (a[0] == b[0]) return 0;_x000D_
    if (a[0] < b[0]) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_ddmm: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_mmdd: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  shaker_sort: function(list, comp_func) {_x000D_
    var b = 0;_x000D_
    var t = list.length - 1;_x000D_
    var swap = true;_x000D_
    while (swap) {_x000D_
      swap = false;_x000D_
      for (var i = b; i < t; ++i) {_x000D_
        if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i + 1];_x000D_
          list[i + 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      t--;_x000D_
_x000D_
      if (!swap) break;_x000D_
_x000D_
      for (var i = t; i > b; --i) {_x000D_
        if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i - 1];_x000D_
          list[i - 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      b++;_x000D_
_x000D_
    }_x000D_
  }_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
    var script = document.getElementById("__ie_onload");_x000D_
    script.onreadystatechange = function() {_x000D_
        if (this.readyState == "complete") {_x000D_
            sorttable.init(); // call the onload handler_x000D_
        }_x000D_
    };_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
  var _timer = setInterval(function() {_x000D_
    if (/loaded|complete/.test(document.readyState)) {_x000D_
      sorttable.init(); // call the onload handler_x000D_
    }_x000D_
  }, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
  if (element.addEventListener) {_x000D_
    element.addEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
    if (!element.events) element.events = {};_x000D_
    var handlers = element.events[type];_x000D_
    if (!handlers) {_x000D_
      handlers = element.events[type] = {};_x000D_
      if (element["on" + type]) {_x000D_
        handlers[0] = element["on" + type];_x000D_
      }_x000D_
    }_x000D_
    handlers[handler.$$guid] = handler;_x000D_
    element["on" + type] = handleEvent;_x000D_
  }_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
  if (element.removeEventListener) {_x000D_
    element.removeEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (element.events && element.events[type]) {_x000D_
      delete element.events[type][handler.$$guid];_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
  var returnValue = true;_x000D_
  event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
  var handlers = this.events[event.type];_x000D_
  for (var i in handlers) {_x000D_
    this.$$handleEvent = handlers[i];_x000D_
    if (this.$$handleEvent(event) === false) {_x000D_
      returnValue = false;_x000D_
    }_x000D_
  }_x000D_
  return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
  event.preventDefault = fixEvent.preventDefault;_x000D_
  event.stopPropagation = fixEvent.stopPropagation;_x000D_
  return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
  this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
  this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
  Array.forEach = function(array, block, context) {_x000D_
    for (var i = 0; i < array.length; i++) {_x000D_
      block.call(context, array[i], i, array);_x000D_
    }_x000D_
  };_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
  for (var key in object) {_x000D_
    if (typeof this.prototype[key] == "undefined") {_x000D_
      block.call(context, object[key], key, object);_x000D_
    }_x000D_
  }_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
  Array.forEach(string.split(""), function(chr, index) {_x000D_
    block.call(context, chr, index, string);_x000D_
  });_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
  if (object) {_x000D_
    var resolve = Object;_x000D_
    if (object instanceof Function) {_x000D_
      resolve = Function;_x000D_
    } else if (object.forEach instanceof Function) {_x000D_
      object.forEach(block, context);_x000D_
      return;_x000D_
    } else if (typeof object == "string") {_x000D_
      resolve = String;_x000D_
    } else if (typeof object.length == "number") {_x000D_
      resolve = Array;_x000D_
    }_x000D_
    resolve.forEach(object, block, context);_x000D_
  }_x000D_
}
_x000D_
table.sortable thead {_x000D_
  background-color: #eee;_x000D_
  color: #666666;_x000D_
  font-weight: bold;_x000D_
  cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>S.L.</th>_x000D_
      <th>name</th>_x000D_
      <th>Goal</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>Ronaldo</td>_x000D_
      <td>120</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2</td>_x000D_
      <td>Messi</td>_x000D_
      <td>66</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3</td>_x000D_
      <td>Ribery</td>_x000D_
      <td>10</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>Bale</td>_x000D_
      <td>22</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS is used here without any other JQuery Plugin.

Clear an input field with Reactjs?

I'm not really sure of the syntax {el => this.inputEntry = el}, but when clearing an input field you assign a ref like you mentioned.

<input type="text" ref="someName" />

Then in the onClick function after you've finished using the input value, just use...

this.refs.someName.value = '';

Edit

Actually the {el => this.inputEntry = el} is the same as this I believe. Maybe someone can correct me. The value for el must be getting passed in from somewhere, to act as the reference.

function (el) {
    this.inputEntry = el;
}

How to Convert JSON object to Custom C# object?

Since we all love one liners code

Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

if we have class then use below.

Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);

no class then use dynamic

var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);

Good font for code presentations?

I do a lot of such presentation and use Monaco for code and Chalkboard for text (within a template that, overall, has only small changes from the Blackboard one supplied with Keynote). Look at any of my presentations' PDFs (e.g. this one) and you can decide whether you like the effect.

Can't connect to Postgresql on port 5432

You have to edit postgresql.conf file and change line with 'listen_addresses'.

This file you can find in the /etc/postgresql/9.3/main directory.

Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:

listen_addresses = '*'

Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:

host    all         all         192.168.1.0/24        md5

Please, read comments in this file...

EDIT:

After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.

EDIT2: Highlited configuration files.

MySQL Error 1215: Cannot add foreign key constraint

I know i am VERY late to the party but i want to put it out here so that it is listed.

As well as all of the above advice for making sure that fields are identically defined, and table types also have the same collation, make sure that you don't make the rookie mistake of trying to link fields where data in the CHILD field is not already in the PARENT field. If you have data that is in the CHILD field that you have not already entered in to the PARENT field then that will cause this error. It's a shame that the error message is not a bit more helpful.

If you are unsure, then backup the table that has the Foreign Key, delete all the data and then try to create the Foreign Key. If successful then you what to do!

Good luck.

How to delete a certain row from mysql table with same column values?

You must add an id that auto-increment for each row, after that you can delet the row by its id. so your table will have an unique id for each row and the id_user, id_product ecc...

Ignoring directories in Git repositories on Windows

By default, Windows Explorer will display .gitignore when in fact the file name is .gitignore.txt.

Git will not use .gitignore.txt

And you can't rename the file to .gitignore, because Windows Explorer thinks it's a file of type gitignore without a name.

Non command line solution:

You can rename a file to ".gitignore.", and it will create ".gitignore"

Create dataframe from a matrix

You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]

  ind time values
1 C_0  0.0    0.1
2 C_0  0.5    0.2
3 C_0  1.0    0.3
4 C_1  0.0    0.3
5 C_1  0.5    0.4
6 C_1  1.0    0.5

Note that stack is generally more efficient than the reshape2 package.

invalid_grant trying to get oAuth token from google

I ran into this same problem despite specifying the "offline" access_type in my request as per bonkydog's answer. Long story short I found that the solution described here worked for me:

https://groups.google.com/forum/#!topic/google-analytics-data-export-api/4uNaJtquxCs

In essence, when you add an OAuth2 Client in your Google API's console Google will give you a "Client ID" and an "Email address" (assuming you select "webapp" as your client type). And despite Google's misleading naming conventions, they expect you to send the "Email address" as the value of the client_id parameter when you access their OAuth2 API's.

This applies when calling both of these URL's:

Note that the call to the first URL will succeed if you call it with your "Client ID" instead of your "Email address". However using the code returned from that request will not work when attempting to get a bearer token from the second URL. Instead you will get an 'Error 400' and an "invalid_grant" message.

How to change the date format of a DateTimePicker in vb.net

Try this code it works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
    MsgBox(CustomeDate.ToString)

    con.Open()

    dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)

    ds = New System.Data.DataSet
    dadap.Fill(ds)
    Dgview.DataSource = ds.Tables(0)
    con.Close()

Note : if u use dd for date representation it will return nothing while selecting 1 to 9 so use d for selection

'Date time format
'MMM     Three-letter month.
'ddd     Three-letter day of the week.
'd       Day of the month.
'HH      Two-digit hours on 24-hour scale.
'mm      Two-digit minutes.
'yyyy    Four-digit year.

The documentation contains a full list of the date formats.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Use the following method.

self.imageView_VedioContainer is the container view of your AVPlayer.

- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
    playerViewController = [[AVPlayerViewController alloc] init];

    playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
                                                 URLForResource:@"VID"
                                                         withExtension:@"3gp"]];
    [playerViewController.player play];
    playerViewController.showsPlaybackControls =YES;
    playerViewController.view.frame=self.imageView_VedioContainer.bounds;
    [playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line 
    [self.imageView_VedioContainer addSubview: playerViewController.view];
}

How many socket connections can a web server handle?

in case of the IPv4 protocol, the server with one IP address that listens on one port only can handle 2^32 IP addresses x 2^16 ports so 2^48 unique sockets. If you speak about a server as a physical machine, and you are able to utilize all 2^16 ports, then there could be maximum of 2^48 x 2^16 = 2^64 unique TCP/IP sockets for one IP address. Please note that some ports are reserved for the OS, so this number will be lower. To sum up:

1 IP and 1 port --> 2^48 sockets

1 IP and all ports --> 2^64 sockets

all unique IPv4 sockets in the universe --> 2^96 sockets

Should I put input elements inside a label element?

I usually go with the first two options. I've seen a scenario when the third option was used, when radio choices where embedded in labels and the css contained something like

label input {
    vertical-align: bottom;
}

in order to ensure proper vertical alignment for the radios.

"fatal: Not a git repository (or any of the parent directories)" from git status

In my case, the original repository was a bare one.

So, I had to type (in windows):

mkdir   dest
cd dest
git init
git remote add origin a\valid\yet\bare\repository
git pull origin master

To check if a repository is a bare one:

git rev-parse --is-bare-repository 

jquery change style of a div on click

If I understand correctly you want to change the CSS style of an element by clicking an item in a ul list. Am I right?

HTML:

<div class="results" style="background-color:Red;">
</div>

 <ul class="colors-list">
     <li>Red</li>
     <li>Blue</li>
     <li>#ffee99</li>
 </ul>

jquery

$('.colors-list li').click(function(e){
    var color = $(this).text();
    $('.results').css('background-color',color);
});

Note that jquery can use addClass, removeClass and toggleClass if you want to use classes rather than inline styling. This means that you can do something like that:

$('.results').addClass('selected');

And define the 'selected' styling in the CSS.

Working example: http://jsfiddle.net/uuJmP/

Why do I need 'b' to encode a string with Base64?

Short Answer

You need to push a bytes-like object (bytes, bytearray, etc) to the base64.b64encode() method. Here are two ways:

>>> import base64
>>> data = base64.b64encode(b'data to be encoded')
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'

Or with a variable:

>>> import base64
>>> string = 'data to be encoded'
>>> data = base64.b64encode(string.encode())
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'

Why?

In Python 3, str objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string and call the .encode() method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to.

Base-64 Encoding in Python 3

Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff.

base64 encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, '+', '/', and '=' (some encodings use different characters in place of '+' and '/'). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you're converting from is a power of 2 less than 64) in chunks from right to left.

In base64 encoding, the translation is done from left to right; those first 64 characters are why it is called base64 encoding. The 65th '=' symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk.

Example:

>>> data = b'test'
>>> for byte in data:
...     print(format(byte, '08b'), end=" ")
...
01110100 01100101 01110011 01110100
>>>

If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64):

base-2:  01 110100 011001 010111 001101 110100 (base-64 grouping shown)
base-10:                            1952805748
base-64:  B      0      Z      X      N      0

base64 encoding, however, will re-group this data thusly:

base-2:  011101  000110  010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk
base-10:     29       6      21     51     29      0
base-64:      d       G       V      z      d      A

So, 'B0ZXN0' is the base-64 version of our binary, mathematically speaking. However, base64 encoding has to do the encoding in the opposite direction (so the raw data is converted to 'dGVzdA') and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with '=' symbols. So, the base64 encoding of this data is 'dGVzdA==', with two '=' symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data.

Let's test this to see if I am being dishonest:

>>> encoded = base64.b64encode(data)
>>> print(encoded)
b'dGVzdA=='

Why use base64 encoding?

Let's say I have to send some data to someone via email, like this data:

>>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20'
>>> print(data.decode())
   
>>> print(data)
b'\x04msg\x08\x08\x08   '
>>>

There are two problems I planted:

  1. If I tried to send that email in Unix, the email would send as soon as the \x04 character was read, because that is ASCII for END-OF-TRANSMISSION (Ctrl-D), so the remaining data would be left out of the transmission.
  2. Also, while Python is smart enough to escape all of my evil control characters when I print the data directly, when that string is decoded as ASCII, you can see that the 'msg' is not there. That is because I used three BACKSPACE characters and three SPACE characters to erase the 'msg'. Thus, even if I didn't have the EOF character there the end user wouldn't be able to translate from the text on screen to the real, raw data.

This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email.

Make A List Item Clickable (HTML/CSS)

Here is a working solution - http://jsfiddle.net/STTaf/

I used simple jQuery:

$(function() {
    $('li').css('cursor', 'pointer')

    .click(function() {
        window.location = $('a', this).attr('href');
        return false;
    });
});

Local variable referenced before assignment?

Best solution: Don't use globals

>>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Create the perfect JPA entity

Entity interface

public interface Entity<I> extends Serializable {

/**
 * @return entity identity
 */
I getId();

/**
 * @return HashCode of entity identity
 */
int identityHashCode();

/**
 * @param other
 *            Other entity
 * @return true if identities of entities are equal
 */
boolean identityEquals(Entity<?> other);
}

Basic implementation for all Entities, simplifies Equals/Hashcode implementations:

public abstract class AbstractEntity<I> implements Entity<I> {

@Override
public final boolean identityEquals(Entity<?> other) {
    if (getId() == null) {
        return false;
    }
    return getId().equals(other.getId());
}

@Override
public final int identityHashCode() {
    return new HashCodeBuilder().append(this.getId()).toHashCode();
}

@Override
public final int hashCode() {
    return identityHashCode();
}

@Override
public final boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
        return false;
    }

    return identityEquals((Entity<?>) o);
}

@Override
public String toString() {
    return getClass().getSimpleName() + ": " + identity();
    // OR 
    // return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

Room Entity impl:

@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;

@Column(name = "number") 
private String number; //immutable

@Column(name = "capacity")
private Integer capacity;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable

Room() {
    // default constructor
}

public Room(Building building, String number) {
    // constructor with required field
    notNull(building, "Method called with null parameter (application)");
    notNull(number, "Method called with null parameter (name)");

    this.building = building;
    this.number = number;
}

public Integer getId(){
    return id;
}

public Building getBuilding() {
    return building;
}

public String getNumber() {
    return number;
}


public void setCapacity(Integer capacity) {
    this.capacity = capacity;
}

//no setters for number, building nor id
}

I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
    l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
    l.value+= 'log in\n';_x000D_
    l.focus();_x000D_
    l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
_x000D_
_x000D_

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
    l.value+= 'alert in\n';_x000D_
    alert('alert!');_x000D_
    l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
    l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
_x000D_
_x000D_

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

How do you merge two Git repositories?

https://github.com/hraban/tomono as another mention of a script-based solution.

I am not the author but used it and it does the job.

One positive aspect is that you get all the branches and all the history into the final repo. For my repos (no duplicate folders in repos - actually, they came out of tfs2git migration) there were no conflicts and everything ran automated.

It is mainly used (see name) to create monorepos.

For Windows users: git bash can execute the .sh file. It comes with the standard git installation.

Why javascript getTime() is not a function?

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

The activity must be exported or contain an intent-filter

it's because you are trying to launch your app from an activity that is not launcher activity. try run it from launcher activity or change your current activity category to launcher in android Manifest.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

String comparison using '==' vs. 'strcmp()'

strcmp will return different values based on the environment it is running(Linux/Windows)!

The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999

Please handle with care!!Thank you.

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

I am not sure it will help but you can try this.This worked for me

Start -> Visual Studio Installer -> Repair

after this enable the Microsoft Symbols Server under

TOOLS->Options->Debugging->Symbols

This will automatically set all the issues.

You can refer this link as well

https://social.msdn.microsoft.com/Forums/vstudio/en-US/6aa917e5-a51c-4399-9712-4b9c5d65fabf/ucrtbasedpdb-not-loaded-using-visual-studio?forum=visualstudiogeneral

checking for typeof error in JS

var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false

Only problem with this is

myError instanceof Object // true

An alternative to this would be to use the constructor property.

myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true

Although it should be noted that this match is very specific, for example:

myError.constructor === TypeError // false

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

How do I make a transparent border with CSS?

Yep, you can use border: 1px solid transparent

Another solution is to use outline on hover (and set the border to 0) which doesn't affect the document flow:

li{
    display:inline-block;
    padding:5px;
    border:0;
}
li:hover{
    outline:1px solid #FC0;
}

NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.

Java Spring - How to use classpath to specify a file location?

Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean

<bean class="test.Test1">
        <property name="path" value="classpath:/test/test1.xml" />
    </bean>

and you get it in your bean as Resource:

public void setPath(Resource path) throws IOException {
    File file = path.getFile();
    System.out.println(file);
    }

output

D:\workspace1\spring\target\test-classes\test\test1.xml

Now you can use it in new FileReader(file)

How to create unique keys for React elements?

Do not use this return `${ pre }_${ new Date().getTime()}`;. It's better to have the array index instead of that because, even though it's not ideal, that way you will at least get some consistency among the list components, with the new Date function you will get constant inconsistency. That means every new iteration of the function will lead to a new truly unique key.

The unique key doesn't mean that it needs to be globally unique, it means that it needs to be unique in the context of the component, so it doesn't run useless re-renders all the time. You won't feel the problem associated with new Date initially, but you will feel it, for example, if you need to get back to the already rendered list and React starts getting all confused because it doesn't know which component changed and which didn't, resulting in memory leaks, because, you guessed it, according to your Date key, every component changed.

Now to my answer. Let's say you are rendering a list of YouTube videos. Use the video id (arqTu9Ay4Ig) as a unique ID. That way, if that ID doesn't change, the component will stay the same, but if it does, React will recognize that it's a new Video and change it accordingly.

It doesn't have to be that strict, the little more relaxed variant is to use the title, like Erez Hochman already pointed out, or a combination of the attributes of the component (title plus category), so you can tell React to check if they have changed or not.

edited some unimportant stuff

jQuery: count number of rows in a table

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

Is an empty href valid?

While it may be completely valid HTML to not include an href, especially with an onclick handler, there are some things to consider: it will not be keyboard-focusable without having a tabindex value set. Furthermore, this will be inaccessible to screenreader software using Internet Explorer, as IE will report through the accessibility interfaces that any anchor element without an href attribute as not-focusable, regardless of whether the tabindex has been set.

So while the following may be completely valid:

<a class="arrow">Link content</a>

It's far better to explicitly add a null-effect href attribute

<a href="javascript:void(0);" class="arrow">Link content</a>

For full support of all users, if you're using the class with CSS to render an image, you should also include some text content, such as the title attribute to provide a textual description of what's going on.

<a href="javascript:void(0);" class="arrow" title="Go to linked content">Link content</a>

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

How do you add Boost libraries in CMakeLists.txt?

Adapting @LainIwakura's answer for modern CMake syntax with imported targets, this would be:

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS filesystem regex) 

if(Boost_FOUND)
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname Boost::filesystem Boost::regex)
endif()

Note that it is not necessary anymore to specify the include directories manually, since it is already taken care of through the imported targets Boost::filesystem and Boost::regex.
regex and filesystem can be replaced by any boost libraries you need.

Returning anonymous type in C#

You can return dynamic which will give you a runtime checked version of the anonymous type but only in .NET 4+

Table 'mysql.user' doesn't exist:ERROR

You can run the following query to check for the existance of the user table.

SELECT * FROM information_schema.TABLES
WHERE TABLE_NAME LIKE '%user%'

See if you can find a row with the following values in

mysql   user    BASE TABLE  MyISAM  

If you cant find this table look at the following link to rebuild the database How to recover/recreate mysql's default 'mysql' database

Strip Leading and Trailing Spaces From Java String

trim() is your choice, but if you want to use replace method -- which might be more flexiable, you can try the following:

String stripppedString = myString.replaceAll("(^ )|( $)", "");

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

x86 Assembly on a Mac

As stated before, don't use syscall. You can use standard C library calls though, but be aware that the stack MUST be 16 byte aligned per Apple's IA32 function call ABI.

If you don't align the stack, your program will crash in __dyld_misaligned_stack_error when you make a call into any of the libraries or frameworks.

The following snippet assembles and runs on my system:

; File: hello.asm
; Build: nasm -f macho hello.asm && gcc -o hello hello.o

SECTION .rodata
hello.msg db 'Hello, World!',0x0a,0x00

SECTION .text

extern _printf ; could also use _puts...
GLOBAL _main

; aligns esp to 16 bytes in preparation for calling a C library function
; arg is number of bytes to pad for function arguments, this should be a multiple of 16
; unless you are using push/pop to load args
%macro clib_prolog 1
    mov ebx, esp        ; remember current esp
    and esp, 0xFFFFFFF0 ; align to next 16 byte boundary (could be zero offset!)
    sub esp, 12         ; skip ahead 12 so we can store original esp
    push ebx            ; store esp (16 bytes aligned again)
    sub esp, %1         ; pad for arguments (make conditional?)
%endmacro

; arg must match most recent call to clib_prolog
%macro clib_epilog 1
    add esp, %1         ; remove arg padding
    pop ebx             ; get original esp
    mov esp, ebx        ; restore
%endmacro

_main:
    ; set up stack frame
    push ebp
    mov ebp, esp
    push ebx

    clib_prolog 16
    mov dword [esp], hello.msg
    call _printf
    ; can make more clib calls here...
    clib_epilog 16

    ; tear down stack frame
    pop ebx
    mov esp, ebp
    pop ebp
    mov eax, 0          ; set return code
    ret

Detecting installed programs via registry

You could use MSI API to enumerate everything installed by Windows Installer but that won't list all the software available on a machine. Without knowing more about what you need I think the concept of "installed" is a little vague. There are many ways to deploy software to a system ranging from big complicated installers to ZIP files and everything in between.

How to position the div popup dialog to the center of browser screen?

Note: This does not directly answer your question. This is deliberate.

A List Apart has an excellent CSS Positioning 101 article that is worth reading ... more than once. It has numerous examples that include, amongst others, your specific problem. I highly recommend it.

How to copy and paste worksheets between Excel workbooks?

I'm using this code, hope this helps!

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim destination_wb As Workbook
Set destination_wb = Workbooks.Open(DESTINATION_WORKBOOK_NAME)

worksheet_to_copy.Copy Before:=destination_wb.Worksheets(1)
destination_wb.Worksheets(1).Name = worksheet_to_copy.Name
'Add the sheets count to the name to avoid repeated worksheet names error
'& destination_wb.Worksheets.Count


'optional
destination_wb.Worksheets(1).UsedRange.Columns.AutoFit

'I use this to avoid macro errors in destination_wb
Call DeleteAllVBACode(destination_wb)

'Delete source worksheet
Application.DisplayAlerts = False
worksheet_to_copy.Delete
Application.DisplayAlerts = True

destination_wb.Save
destination_wb.Close

Application.EnableEvents = True
Application.ScreenUpdating = True

' From http://www.cpearson.com/Excel/vbe.aspx           

Public Sub DeleteAllVBACode(libro As Workbook)
    Dim VBProj As VBProject
    Dim VBComp As VBComponent
    Dim CodeMod As CodeModule

    Set VBProj = libro.VBProject

    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_Document Then
            Set CodeMod = VBComp.CodeModule
            With CodeMod
                .DeleteLines 1, .CountOfLines
            End With
        Else
            VBProj.VBComponents.Remove VBComp
        End If
    Next VBComp
End Sub

Can't install via pip because of egg_info error

In my case, I had to uninstall pip and reinstall it. So I could install my specific version.

sudo apt-get purge --auto-remove python-pip
sudo easy_install pip 

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

Here is an answer proposal:

http://www.greenvilleweb.us/how-to-web-design/problem-with-ie-9-caching-ajax-get-request/

The idea is to add a parameter to your ajax query containing for example the current date an time, so the browser will not be able to cache it.

Have a look on the link, it is well explained.

Can (domain name) subdomains have an underscore "_" in it?

Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.

Can't connect to docker from docker-compose

try this:

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Flutter Circle Design

You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.

Untrack files from git temporarily

To remove all Untrack files. Try this terminal command

 git clean -fdx

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

curl: (60) SSL certificate problem: unable to get local issuer certificate

this can help you for guzzle :

$client = new Client(env('API_HOST'));
$client->setSslVerification(false);

tested on guzzle/guzzle 3.*

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

./config --prefix=/usr --openssldir=/usr/local/openssl shared

Try this config line instead to overwrite the default. It installs to prefix /usr/local/ssl by default in your setup when you leave off the prefix. You probably have "/usr/local/ssl/bin/openssl" instead of overwriting /usr/bin/openssl. You can also use /usr/local for prefix instead, but you would need to adjust your path accordingly if that is not already on your path. Here is the INSTALL documentation:

  $ ./config
  $ make
  $ make test
  $ make install

 [If any of these steps fails, see section Installation in Detail below.]

This will build and install OpenSSL in the default location, which is (for
historical reasons) /usr/local/ssl. If you want to install it anywhere else,
run config like this:

  $ ./config --prefix=/usr/local --openssldir=/usr/local/openssl

https://github.com/openssl/openssl/blob/master/INSTALL http://heartbleed.com/

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Can't start hostednetwork

Symptoms
You install an application that uses Microsoft Virtual WiFi technology on a computer that is running Windows 7 or Windows Server 2008 R2. However, the application does not work after the computer restarts. Additionally, you receive an error message that resembles the following:

The hosted network couldn't be started. The group or resource is not in the correct state to perform the requested operation.

Cause
This issue occurs because the Virtual Wi-Fi filter driver does not create the Virtual Wi-Fi Adapter correctly when a PNP resource rebalance occurs during the startup process.

Notes
1.This issue may occur when a Plug and Play (PNP) resource rebalance occurs during the startup process. The PNP resource rebalance is usually triggered by a change to the hardware configuration.
2.If you open Device Manager when this issue occurs, you notice that the Virtual WiFi Adapter is not created.

If you can't restart your hostednetwork after rebooting the OS ,just Try this hotfix .It fixed my problem. Or try to figure it out by yourself according to the Symptoms and Cause mentioned at the start of my answer.

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

Authenticating in PHP using LDAP through Active Directory

You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:

  • You must validate input. An empty username/password would pass otherwise.
  • You should ensure the username/password is properly encoded when binding.
  • You should be encrypting the connection using TLS.
  • Using separate LDAP servers for redundancy in case one is down.
  • Getting an informative error message if authentication fails.

It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:

use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;

$domain = (new DomainConfiguration('example.com'))
    ->setUsername('username') # A separate AD service account used by your app
    ->setPassword('password')
    ->setServers(['dc1', 'dc2', 'dc3'])
    ->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);

if (!$ldap->authenticate($username, $password, $message)) {
    echo "Error: $message";
} else {
    // Do something...
}

The authenticate call above will:

  • Validate that neither the username or password is empty.
  • Ensure the username/password is properly encoded (UTF-8 by default)
  • Try an alternate LDAP server in case one is down.
  • Encrypt the authentication request using TLS.
  • Provide additional information if it failed (ie. locked/disabled account, etc)

There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.

How to test an Internet connection with bash?

For the fastest result, ping a DNS server:

ping -c1 "8.8.8.8" &>"/dev/null"

if [[ "${?}" -ne 0 ]]; then
    echo "offline"
elif [[ "${#args[@]}" -eq 0 ]]; then
    echo "online"
fi

Available as a standalone command: linkStatus

What is the difference between Amazon SNS and Amazon SQS?

SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by publishers to SNS.

SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.

You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).

Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.

SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (S3, hard disk on your host, database, etc.).

How to get the Enum Index value in C#

By default the underlying type of each element in the enum is integer.

enum Values
{
   A,
   B,
   C
}

You can also specify custom value for each item:

enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.

How to center an element horizontally and vertically

Another approach is to use table:

_x000D_
_x000D_
<div style="border:2px solid #8AC007; height:200px; width:200px;">_x000D_
  <table style="width:100%; height:100%">_x000D_
    <tr style="height:100%">_x000D_
      <td style="height:100%; text-align:center">hello, multiple lines here, this is super long, and that is awesome, dude</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to squash all git commits into one?

As of git 1.6.2, you can use git rebase --root -i.

For each commit except the first, change pick to squash.

Invoke(Delegate)

this.Invoke(delegate) make sure that you are calling the delegate the argument to this.Invoke() on main thread/created thread.

I can say a Thumb rule don't access your form controls except from main thread.

May be the following lines make sense for using Invoke()

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }

There are situations though you create a Threadpool thread(i.e worker thread) it will run on main thread. It won't create a new thread coz main thread is available for processing further instructions. So First investigate whether the current running thread is main thread using this.InvokeRequired if returns true the current code is running on worker thread so call this.Invoke(d, new object[] { text });

else directly update the UI control(Here you are guaranteed that you are running the code on main thread.)

android pick images from gallery

U can do it easier than this answers :

Uri Selected_Image_Uri = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
imageView.setImageURI(Selected_Image_Uri);

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

Image.open() cannot identify image file - Python?

In my case.. I already had "from PIL import Image" in my code.

The error occurred for me because the image file was still in use (locked) by a previous operation in my code. I had to add a small delay or attempt to open the file in append mode in a loop, until that did not fail. Once that did not fail, it meant the file was no longer in use and I could continue and let PIL open the file. Here are the functions I used to check if the file is in use and wait for it to be available.

def is_locked(filepath):
    locked = None
    file_object = None
    if os.path.exists(filepath):
        try:
            buffer_size = 8
            # Opening file in append mode and read the first 8 characters.
            file_object = open(filepath, 'a', buffer_size)
            if file_object:
                locked = False
        except IOError as message:
            locked = True
        finally:
            if file_object:
                file_object.close()
    return locked

def wait_for_file(filepath):
    wait_time = 1
    while is_locked(filepath):
        time.sleep(wait_time)

How to convert currentTimeMillis to a date in Java?

The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.

I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

How to convert UTC timestamp to device local time in android

Java:

int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
long now = System.currentTimeMillis() - offset;

Kotlin:

Int offset = TimeZone.getDefault()rawOffset + TimeZone.getDefault().dstSavings
Long now = System.currentTimeMillis() - offset

python time + timedelta equivalent

Workaround:

t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)

You can also omit the microseconds, if you don't need that much precision.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You can also add android:noHistory="true" to your Activity tag in AndroidManifest.xml.

<activity
            ...
            android:noHistory="true">
</activity>

Spring Boot yaml configuration for a list of strings

From the spring boot docs https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

YAML lists are represented as property keys with [index] dereferencers, for example this YAML:

my:
   servers:
       - dev.bar.com
       - foo.bar.com

Would be transformed into these properties:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) you need to have a property in the target bean of type java.util.List and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.

@ConfigurationProperties(prefix="ignore")
public class Filenames {

    private List<String> ignoredFilenames = new ArrayList<String>();

    public List<String> getFilenames() {
        return this.ignoredFilenames;
    }
}

How to get a div to resize its height to fit container?

Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.

One way to do the following without using JavaScript is via a technique called Faux-Columns.

It basically involves applying a background-image to the parent elements of the floated elements which makes you believe that the two elements are the same height.

More information available at:

A List Apart: Articles: Faux Columns

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Bootstrap modal not displaying

It's a good idea to place your modal after the tag, so you are sure no parent element style affects it - in my case modal was hidden because parent div was hidden.

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

How to measure height, width and distance of object using camera?

For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.

This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.

So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.

If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.

I have found some links using Google, they may help.

  1. http://forestjohnson.blogspot.com/2010/01/how-to-measure-size-of-object-using.html
  2. http://gigaom.com/mobile/how_to_measure_/
  3. http://www.iphonelife.com/blog/5/cameasure-use-your-camera-measure-size-or-distance

They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.

One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.

See these links as well:

  1. http://iopscience.iop.org/1742-6596/48/1/074/pdf/1742-6596_48_1_074.pdf
  2. http://www.optical-metrology-centre.com/Downloads/Papers/Photogrammetric%20Record%201994%20Automated%203-D%20measurement.pdf

How to use Git for Unity3D source control?

I thought that I might post a simpler .gitignore for anyone that is interested:

# Ignore Everything
/*

# Except for these:
!/.gitignore
!/Assets
!/Packages
!/ProjectSettings

Parse JSON String into a Particular Object Prototype in JavaScript

Olivers answers is very clear, but if you are looking for a solution in angular js, I have written a nice module called Angular-jsClass which does this ease, having objects defined in litaral notation is always bad when you are aiming to a big project but saying that developers face problem which exactly BMiner said, how to serialize a json to prototype or constructor notation objects

var jone = new Student();
jone.populate(jsonString); // populate Student class with Json string
console.log(jone.getName()); // Student Object is ready to use

https://github.com/imalhasaranga/Angular-JSClass

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

Getting reference to child component in parent component

You can use ViewChild

<child-tag #varName></child-tag>

@ViewChild('varName') someElement;

ngAfterViewInit() {
  someElement...
}

where varName is a template variable added to the element. Alternatively, you can query by component or directive type.

There are alternatives like ViewChildren, ContentChild, ContentChildren.

@ViewChildren can also be used in the constructor.

constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)

The advantage is that the result is available earlier.

See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.

Note: @Query() is the deprecated predecessor of @ContentChildren()

Update

Query is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145

Google Maps Android API v2 Authorization failure

Today I faced with this problem. I used Android Studio 2.1.3, windows 10. While debugging it works fine, but if I update to release mode it does not work. I cleared all proguard conditions, updated, but this was not solution.

The solution is related with project structure. The google_maps_api.xml file was different between app\src\debug\res and app\src\release\res. I did manual copy paste from debug to release folder.

Now it works.

How to get element by innerText

_x000D_
_x000D_
function findByTextContent(needle, haystack, precise) {_x000D_
  // needle: String, the string to be found within the elements._x000D_
  // haystack: String, a selector to be passed to document.querySelectorAll(),_x000D_
  //           NodeList, Array - to be iterated over within the function:_x000D_
  // precise: Boolean, true - searches for that precise string, surrounded by_x000D_
  //                          word-breaks,_x000D_
  //                   false - searches for the string occurring anywhere_x000D_
  var elems;_x000D_
_x000D_
  // no haystack we quit here, to avoid having to search_x000D_
  // the entire document:_x000D_
  if (!haystack) {_x000D_
    return false;_x000D_
  }_x000D_
  // if haystack is a string, we pass it to document.querySelectorAll(),_x000D_
  // and turn the results into an Array:_x000D_
  else if ('string' == typeof haystack) {_x000D_
    elems = [].slice.call(document.querySelectorAll(haystack), 0);_x000D_
  }_x000D_
  // if haystack has a length property, we convert it to an Array_x000D_
  // (if it's already an array, this is pointless, but not harmful):_x000D_
  else if (haystack.length) {_x000D_
    elems = [].slice.call(haystack, 0);_x000D_
  }_x000D_
_x000D_
  // work out whether we're looking at innerText (IE), or textContent _x000D_
  // (in most other browsers)_x000D_
  var textProp = 'textContent' in document ? 'textContent' : 'innerText',_x000D_
    // creating a regex depending on whether we want a precise match, or not:_x000D_
    reg = precise === true ? new RegExp('\\b' + needle + '\\b') : new RegExp(needle),_x000D_
    // iterating over the elems array:_x000D_
    found = elems.filter(function(el) {_x000D_
      // returning the elements in which the text is, or includes,_x000D_
      // the needle to be found:_x000D_
      return reg.test(el[textProp]);_x000D_
    });_x000D_
  return found.length ? found : false;;_x000D_
}_x000D_
_x000D_
_x000D_
findByTextContent('link', document.querySelectorAll('li'), false).forEach(function(elem) {_x000D_
  elem.style.fontSize = '2em';_x000D_
});_x000D_
_x000D_
findByTextContent('link3', 'a').forEach(function(elem) {_x000D_
  elem.style.color = '#f90';_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course, a somewhat simpler way still is:

_x000D_
_x000D_
var textProp = 'textContent' in document ? 'textContent' : 'innerText';_x000D_
_x000D_
// directly converting the found 'a' elements into an Array,_x000D_
// then iterating over that array with Array.prototype.forEach():_x000D_
[].slice.call(document.querySelectorAll('a'), 0).forEach(function(aEl) {_x000D_
  // if the text of the aEl Node contains the text 'link1':_x000D_
  if (aEl[textProp].indexOf('link1') > -1) {_x000D_
    // we update its style:_x000D_
    aEl.style.fontSize = '2em';_x000D_
    aEl.style.color = '#f90';_x000D_
  }_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

References:

How to move from one fragment to another fragment on click of an ImageView in Android?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}

Get path to execution directory of Windows Forms application

Check this out:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

Check for false

Like this:

if(borrar())
{
   // Do something
}

If borrar() returns true then do something (if it is not false).

Media Player called in state 0, error (-38,0)

  if(length>0)
        {
            mediaPlayer = new MediaPlayer();
            Log.d("length",""+length);
            try {
                mediaPlayer.setDataSource(getApplication(),Uri.parse(uri));
            } catch(IOException e) {
                e.printStackTrace();
            }
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.seekTo(length);
                    mediaPlayer.start();

                }
            });
            mediaPlayer.prepareAsync();

Draw on HTML5 Canvas using a mouse

Here's the most straightforward way to create a drawing application with canvas:

  1. Attach a mousedown, mousemove, and mouseup event listener to the canvas DOM
  2. on mousedown, get the mouse coordinates, and use the moveTo() method to position your drawing cursor and the beginPath() method to begin a new drawing path.
  3. on mousemove, continuously add a new point to the path with lineTo(), and color the last segment with stroke().
  4. on mouseup, set a flag to disable the drawing.

From there, you can add all kinds of other features like giving the user the ability to choose a line thickness, color, brush strokes, and even layers.

When increasing the size of VARCHAR column on a large table could there be any problems?

Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

Python unexpected EOF while parsing

Check the version of your Compiler.

  1. if you are dealing with Python2 then use -

n= raw_input("Enter your Input: ")

  1. if you are dealing with python3 use -

n= input("Enter your Input: ")

Node.js: printing to console without a trailing newline?

I got the following error when using strict mode:

Node error: "Octal literals are not allowed in strict mode."

The following solution works (source):

process.stdout.write("received: " + bytesReceived + "\x1B[0G");

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Angularjs loading screen on ajax request

Typescript and Angular Implementation

directive

((): void=> {
    "use strict";
    angular.module("app").directive("busyindicator", busyIndicator);
    function busyIndicator($http:ng.IHttpService): ng.IDirective {
        var directive = <ng.IDirective>{
            restrict: "A",
            link(scope: Scope.IBusyIndicatorScope) {
                scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
                scope.$watch(scope.anyRequestInProgress, x => {            
                    if (x) {
                        scope.canShow = true;
                    } else {
                        scope.canShow = false;
                    }
                });
            }
        };
        return directive;
    }
})();

Scope

   module App.Scope {
        export interface IBusyIndicatorScope extends angular.IScope {
            anyRequestInProgress: any;
            canShow: boolean;
        }
    }  

Template

<div id="activityspinner" ng-show="canShow" class="show" data-busyindicator>
</div>

CSS
#activityspinner
{
    display : none;
}
#activityspinner.show {
    display : block;
    position : fixed;
    z-index: 100;
    background-image : url('data:image/gif;base64,R0lGODlhNgA3APMAAPz8/GZmZqysrHV1dW1tbeXl5ZeXl+fn59nZ2ZCQkLa2tgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAANgA3AAAEzBDISau9OOvNu/9gKI5kaZ4lkhBEgqCnws6EApMITb93uOqsRC8EpA1Bxdnx8wMKl51ckXcsGFiGAkamsy0LA9pAe1EFqRbBYCAYXXUGk4DWJhZN4dlAlMSLRW80cSVzM3UgB3ksAwcnamwkB28GjVCWl5iZmpucnZ4cj4eWoRqFLKJHpgSoFIoEe5ausBeyl7UYqqw9uaVrukOkn8LDxMXGx8ibwY6+JLxydCO3JdMg1dJ/Is+E0SPLcs3Jnt/F28XXw+jC5uXh4u89EQAh+QQJCgAAACwAAAAANgA3AAAEzhDISau9OOvNu/9gKI5kaZ5oqhYGQRiFWhaD6w6xLLa2a+iiXg8YEtqIIF7vh/QcarbB4YJIuBKIpuTAM0wtCqNiJBgMBCaE0ZUFCXpoknWdCEFvpfURdCcM8noEIW82cSNzRnWDZoYjamttWhphQmOSHFVXkZecnZ6foKFujJdlZxqELo1AqQSrFH1/TbEZtLM9shetrzK7qKSSpryixMXGx8jJyifCKc1kcMzRIrYl1Xy4J9cfvibdIs/MwMue4cffxtvE6qLoxubk8ScRACH5BAkKAAAALAAAAAA2ADcAAATOEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwyZKxhqhgJJeSQVdraBNFSsVUVPHsEAzJrEtnJNSELXRN2bKcwjw19f0QG7PjA7B2EGfn+FhoeIiYoSCAk1CQiLFQpoChlUQwhuBJEWcXkpjm4JF3w9P5tvFqZsLKkEF58/omiksXiZm52SlGKWkhONj7vAxcbHyMkTmCjMcDygRNAjrCfVaqcm11zTJrIjzt64yojhxd/G28XqwOjG5uTxJhEAIfkECQoAAAAsAAAAADYANwAABM0QyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/i8qmCoGQoacT8FZ4AXbFopfTwEBhhnQ4w2j0GRkgQYiEOLPI6ZUkgHZwd6EweLBqSlq6ytricICTUJCKwKkgojgiMIlwS1VEYlspcJIZAkvjXHlcnKIZokxJLG0KAlvZfAebeMuUi7FbGz2z/Rq8jozavn7Nev8CsRACH5BAkKAAAALAAAAAA2ADcAAATLEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwzJNCmPzheUyJuKijVrZ2cTlrg1LwjcO5HFyeoJeyM9U++mfE6v2+/4PD6O5F/YWiqAGWdIhRiHP4kWg0ONGH4/kXqUlZaXmJlMBQY1BgVuUicFZ6AhjyOdPAQGQF0mqzauYbCxBFdqJao8rVeiGQgJNQkIFwdnB0MKsQrGqgbJPwi2BMV5wrYJetQ129x62LHaedO21nnLq82VwcPnIhEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/g8Po7kX9haKoAZZ0iFGIc/iRaDQ40Yfj+RepSVlpeYAAgJNQkIlgo8NQqUCKI2nzNSIpynBAkzaiCuNl9BIbQ1tl0hraewbrIfpq6pbqsioaKkFwUGNQYFSJudxhUFZ9KUz6IGlbTfrpXcPN6UB2cHlgfcBuqZKBEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7yJEopZA4CsKPDUKfxIIgjZ+P3EWe4gECYtqFo82P2cXlTWXQReOiJE5bFqHj4qiUhmBgoSFho59rrKztLVMBQY1BgWzBWe8UUsiuYIGTpMglSaYIcpfnSHEPMYzyB8HZwdrqSMHxAbath2MsqO0zLLorua05OLvJxEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhfohELYHQuGBDgIJXU0Q5CKqtOXsdP0otITHjfTtiW2lnE37StXUwFNaSScXaGZvm4r0jU1RWV1hhTIWJiouMjVcFBjUGBY4WBWw1A5RDT3sTkVQGnGYYaUOYPaVip3MXoDyiP3k3GAeoAwdRnRoHoAa5lcHCw8TFxscduyjKIrOeRKRAbSe3I9Um1yHOJ9sjzCbfyInhwt3E2cPo5dHF5OLvJREAOwAAAAAAAAAAAA==') 
    -ms-opacity : 0.4;
    opacity : 0.4;
    background-repeat : no-repeat;
    background-position : center;
    left : 0;
    bottom : 0;
    right : 0;
    top : 0;
}

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

Why can't I use Docker CMD multiple times to run multiple services?

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./my_wrapper_script.sh) or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Convert xlsx file to csv using batch

Alternative way of converting to csv. Use libreoffice:

libreoffice --headless --convert-to csv *

Please be aware that this will only convert the first worksheet of your Excel file.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How do I get interactive plots again in Spyder/IPython/matplotlib?

As said in the comments, the problem lies in your script. Actually, there are 2 problems:

  • There is a matplotlib error, I guess that you're passing an argument as None somewhere. Maybe due to the defaultdict ?
  • You call show() after each subplot. show() should be called once at the end of your script. The alternative is to use interactive mode, look for ion in matplotlib's documentation.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:

Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.

Regex for string contains?

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]

Make the image go behind the text and keep it in center using CSS

Well, put your image in the background of your website/container and put whatever you want on top of that.

Your container defined in HTML:

<div id="container">
   <input name="box" type="textbox" />
   <input name="box" type="textbox" />
   <input name="submit" type="submit" />
</div>

Your CSS would look like this:

#container {
    background-image:url(yourimage.jpg);
    background-position:center;
    width:700px;
    height:400px;
}

For this to work though, you must have height and width specified to certain values (i.e. no percentages). I could help you more specifically if you wanted, but I'd need more info.

Combining COUNT IF AND VLOOK UP EXCEL

Try this:

=IF(NOT(ISERROR(MATCH(A3,worksheet2!A:A,0))),COUNTIF(worksheet2!A:A,A3),"No Match Found")

pandas: best way to select all columns whose names start with X

My solution. It may be slower on performance:

a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()


   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How do you detect Credit card type based on number?

I use https://github.com/bendrucker/creditcards-types/ to detect the credit card type from number. One issue I ran into is discover test number 6011 1111 1111 1117

from https://www.cybersource.com/developers/other_resources/quick_references/test_cc_numbers/ we can see it is a discover number because it starts by 6011. But the result I get from the creditcards-types is "Maestro". I opened the issue to the author. He replied me very soon and provide this pdf doc https://www.discovernetwork.com/downloads/IPP_VAR_Compliance.pdf From the doc we can see clearly that 6011 1111 1111 1117 does not fall into the range of discover credit card.

Replace whitespaces with tabs in linux

You can also use astyle. I found it quite useful and it has several options too:

Tab and Bracket Options:
   If  no  indentation  option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4.  If no brackets option is set, the
   brackets will not be changed.

   --indent=spaces, --indent=spaces=#, -s, -s#
          Indent using # spaces per indent. Between 1 to 20.  Not specifying # will result in a default of 4 spaces per indent.

   --indent=tab, --indent=tab=#, -t, -t#
          Indent using tab characters, assuming that each tab is # spaces long.  Between 1 and 20. Not specifying # will result in a default assumption  of
          4 spaces per tab.`

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

To see all tables:

.tables

To see a particular table:

.schema [tablename]

When should I use a List vs a LinkedList

When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.

How to add leading zeros?

For a general solution that works regardless of how many digits are in data$anim, use the sprintf function. It works like this:

sprintf("%04d", 1)
# [1] "0001"
sprintf("%04d", 104)
# [1] "0104"
sprintf("%010d", 104)
# [1] "0000000104"

In your case, you probably want: data$anim <- sprintf("%06d", data$anim)

React JSX: selecting "selected" on selected <select> option

Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

SQL SERVER DATETIME FORMAT

Compatibility Supports Says that Under compatibility level 110, the default style for CAST and CONVERT operations on time and datetime2 data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.

That means by default datetime2 is CAST as varchar to 121 format. For ex; col1 and col2 formats (below) are same (other than the 0s at the end)

SELECT CONVERT(varchar, GETDATE(), 121) col1,
       CAST(convert(datetime2,GETDATE()) as varchar) col2,
       CAST(GETDATE() as varchar) col3

SQL FIDDLE DEMO

--Results
COL1                    | COL2                          | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000   | Feb 8 2013 9:53AM

FYI, if you use CONVERT instead of CAST you can use a third parameter to specify certain formats as listed here on MSDN

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

How to group by month from Date field using sql

Try the Following Code

SELECT  Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), 
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;

Python 2: AttributeError: 'list' object has no attribute 'strip'

What you want to do is -

strtemp = ";".join(l)

The first line adds a ; to the end of MySpace so that while splitting, it does not give out MySpaceApple This will join l into one string and then you can just-

l1 = strtemp.split(";")

This works because strtemp is a string which has .split()

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

Convert a List<T> into an ObservableCollection<T>

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

How to check whether an object has certain method/property?

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

How to get a variable name as a string in PHP?

This is the way I did it

function getVar(&$var) {
    $tmp = $var; // store the variable value
    $var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value
    $name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)
    $var = $tmp; // restore the variable old value
    return $name;
}

Usage

$city  = "San Francisco";
echo getVar($city); // city

Note: some PHP 7 versions will not work properly due to a bug in array_search with $GLOBALS, however all other versions will work.

See this https://3v4l.org/UMW7V

How to run .sql file in Oracle SQL developer tool to import database?

You need to Open the SQL Developer first and then click on File option and browse to the location where your .sql is placed. Once you are at the location where file is placed double click on it, this will get the file open in SQL Developer. Now select all of the content of file (CTRL + A) and press F9 key. Just make sure there is a commit statement at the end of the .sql script so that the changes are persisted in the database

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Auto increment in phpmyadmin

  1. In "Structure" tab of your table
  2. Click on the pencil of the variable you want auto_increment
  3. under "Extra" tab choose "auto_increment"
  4. then go to "Operations" tab of your table
  5. Under "Table options" -> auto_increment type -> 10000

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

CSS values using HTML5 data attribute

As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.

Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).

But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.

Correct way to pass multiple values for same parameter name in GET request

Indeed, there is no defined standard. To support that information, have a look at wikipedia, in the Query String chapter. There is the following comment:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field.[3][4]

Furthermore, when you take a look at the RFC 3986, in section 3.4 Query, there is no definition for parameters with multiple values.

Most applications use the first option you have shown: http://server/action?id=a&id=b. To support that information, take a look at this Stackoverflow link, and this MSDN link regarding ASP.NET applications, which use the same standard for parameters with multiple values.

However, since you are developing the APIs, I suggest you to do what is the easiest for you, since the caller of the API will not have much trouble creating the query string.

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

bootstrap initially collapsed element

If removing the in class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:

...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

How to split a string in Haskell?

In addition to the efficient and pre-built functions given in answers I'll add my own which are simply part of my repertory of Haskell functions I was writing to learn the language on my own time:

-- Correct but inefficient implementation
wordsBy :: String -> Char -> [String]
wordsBy s c = reverse (go s []) where
    go s' ws = case (dropWhile (\c' -> c' == c) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> c' /= c) rem)) ((takeWhile (\c' -> c' /= c) rem) : ws)

-- Breaks up by predicate function to allow for more complex conditions (\c -> c == ',' || c == ';')
wordsByF :: String -> (Char -> Bool) -> [String]
wordsByF s f = reverse (go s []) where
    go s' ws = case ((dropWhile (\c' -> f c')) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> (f c') == False)) rem) (((takeWhile (\c' -> (f c') == False)) rem) : ws)

The solutions are at least tail-recursive so they won't incur a stack overflow.

How to use enums in C++

You are looking for strongly typed enumerations, a feature available in the C++11 standard. It turns enumerations into classes with scope values.

Using your own code example, it is:

  enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
  Days day = Days::Saturday;

  if (day == Days::Saturday)  {
    cout << " Today is Saturday !" << endl;
  }
  //int day2 = Days::Sunday; // Error! invalid

Using :: as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.

If you are using GCC, enable C+11 with -std=c++11 or -std=gnu11 .

Be happy!

Checking if an object is a given type in Swift

If you just want to check the class without getting a warning because of the unused defined value (let someVariable ...), you can simply replace the let stuff with a boolean:

if (yourObject as? ClassToCompareWith) != nil {
   // do what you have to do
}
else {
   // do something else
}

Xcode proposed this when I used the let way and didn't use the defined value.

Measuring text height to be drawn on Canvas ( Android )

You could use the android.text.StaticLayout class to specify the bounds required and then call getHeight(). You can draw the text (contained in the layout) by calling its draw(Canvas) method.

What's the simplest way to print a Java array?

You could loop through the array, printing out each item, as you loop. For example:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

item 1
item 2
item 3

How to list files inside a folder with SQL Server

I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...

Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
    Dim FileNames As String()

    Try
    FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
    Catch
        FileNames = Nothing
    End Try

    Return FileNames

End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
    Val = CType(obj, String).ToString
End Sub

End Class

I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.

NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.

Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.

In SSMS:-

CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';

CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO

then call it

SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')

NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.

ALTER ASSEMBLY [CLRFilesInDirAssembly] 
WITH PERMISSION_SET = EXTERNAL_ACCESS 
GO

and wullah! that should work.

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

get the value of "onclick" with jQuery?

I'm not quite sure how to do this in jQuery... but this works:

var x = document.getElementById('google').attributes;
for (var i in x) {
 if (x[i].name == "onclick") alert(x[i].firstChild.data);
}

but like Harshath said it would be better if you used event listeners, as removing and adding this function back into the onclick event may be troublesome.

How can I make a countdown with NSTimer?

For use in Playground for fellow newbies, in Swift 5, Xcode 11:

Import UIKit

var secondsRemaining = 10
    
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
    if secondsRemaining > 0 {
        print ("\(secondsRemaining) seconds")
        secondsRemaining -= 1
    } else {
        Timer.invalidate()
    }
}

Adb install failure: INSTALL_CANCELED_BY_USER

Sometimes the application is bad generated: bad signed or bad aligned and report a mistake.

Check your jarsigner and zipaligned commands.

Determine which MySQL configuration file is being used

If you are on Linux, then start the 'mysqld' with strace, for eg strace ./mysqld.

Among all the other system calls, you will find something like:

stat64("/etc/my.cnf", 0xbfa3d7fc)       = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4227, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3

So, as you can see..it lists the .cnf files, that it attempts to use and finally uses.

Switch statement for string matching in JavaScript

Just use the location.host property

switch (location.host) {
    case "xxx.local":
        settings = ...
        break;
    case "xxx.dev.yyy.com":
        settings = ...
        break;
}

get and set in TypeScript

I think I probably get why is it so confusing. In your example, we wanted getters and setters for _name. But we achieve that by creating getters and setters for an unrelated class variable Name.

Consider this:

class Car{
    private tiresCount = 4;
    get yourCarTiresCount(){
        return this.tiresCount ;
    }
    set yourCarTiresCount(count) {
        alert('You shouldn't change car tire count')
    }
}

Above code does following:

  1. get and set create getter and setter for yourCarTiresCount (not for tiresCount).

The getter is :

function() {
    return this.tiresCount ;
}

and the setter is :

function(count) {
    alert('You shouldn't change car tire count');
}

Meaning, every time we do new Car().yourCarTiresCount, getter runs. And for every new Car().yourCarTiresCount('7') setter runs.

  1. Indirectly create getter, but not the setter, for private tireCount.

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Simplest way to detect a mobile device in PHP

Simply you can follow the link. its very simple and very easy to use. I am using this. Its working fine.

http://mobiledetect.net/

use like this

//include the file
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
 //do some code
}

// Any tablet device.
if( $detect->isTablet() ){
 //do some code
}

c# dictionary one key many values

 Dictionary<int, string[]> dictionaty  = new Dictionary<int, string[]>() {
            {1, new string[]{"a","b","c"} },
            {2, new string[]{"222","str"} }
        };

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

What's alternative to angular.copy in Angular

I needed this feature just form my app 'models' (raw backend data converted to objects). So I ended up using a combination of Object.create (create new object from specified prototype) and Object.assign (copy properties between objects). Need to handle the deep copy manually. I created a gist for this.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

The answer by Agalin is already great and I just want to explain it in a step by step format for a novice like myself:

  • find your Python version by python --version mine is 3.7.3 for example
  • the easiest way to check either you have 64 or 32 Python just open it in the terminal:

  • find the appropriate .whl file from here, for example mine is PyAudio-0.2.11-cp37-cp37m-win_amd64.whl, and download it.
  • go to the folder where it is downloaded for example cd C:\Users\foobar\Downloads
  • install the .whl file with pip for example in my case:
pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

None of the above worked for me but I came up with this and it worked:

function toggleChevron(el) {
  if ($(el).find('i').hasClass('icon-chevron-left'))
      $(el).find('.icon-chevron-left').removeClass("icon-chevron-left").addClass("icon-chevron-down");
  else 
      $(el).find('.icon-chevron-down').removeClass("icon-chevron-down").addClass("icon-chevron-left");
}

HTML implementation:

<div class="accordion" id="accordion-send">
  <div class="accordion-group">
    <div class="accordion-heading" onClick="toggleChevron(this)">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
        <i class="icon icon-chevron-right"></i> Send notice
      </a>
      ...

What is the best method to merge two PHP objects?

This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Once an Object is in array format you can use array_merge and convert back to Object if you need to.

abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}

Procedural way

function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}

All credit goes to: Jason Oakley

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

How does "FOR" work in cmd batch file?

None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:

echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set MAX_TRIES=100
set P=%PATH%
for /L %%a in (1, 1, %MAX_TRIES%) do (
  for /F "delims=;" %%g in ("!P!") do (
    echo %%g
    set P=!P:%%g;=!
    if "!P!" == "%%g" goto :eof
  )
)

Oh ! I hate batch file programming !!

Updated

Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution

echo off
setlocal enabledelayedexpansion
set NonBlankPath=%PATH: =#%
set TabbedPath=%NonBlankPath:;= %
for %%g in (%TabbedPath%) do (
  set GG=%%g
  echo !GG:#= !
)

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

You can use "smart BASIC" programming language. It is a genuine but very advanced BASIC language with all its power and simplicity. Using its free SDK, BASIC code can be easily published as a standalone App Store application. There are many apps in App Store, written in "smart BASIC" programming language.

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

As stated,

innodb_buffer_pool_size=50M

Following the convention on the other predefined variables, make sure there is no space either side of the equals sign.

Then run

sudo service mysqld stop
sudo service mysqld start

Note

Sometimes, e.g. on Ubuntu, the MySQL daemon is named mysql as opposed to mysqld

I find that running /etc/init.d/mysqld restart doesn't always work and you may get an error like

Stopping mysqld:                                           [FAILED]
Starting mysqld:                                           [  OK  ]

To see if the variable has been set, run show variables and see if the value has been updated.

How to get the url parameters using AngularJS

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:

var paramValue = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

How to check if string input is a number?

The method isnumeric() will do the job (Documentation for python3.x):

>>>a = '123'
>>>a.isnumeric()
True

But remember:

>>>a = '-1'
>>>a.isnumeric()
False

isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.

So negative numbers are not accepted.

Getting String Value from Json Object Android

If you can use JSONObject library, you could just

    JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
    String result = ja.getJSONObject(0).getString("NeededString");

How to store standard error in a variable

If you want to bypass the use of a temporary file you may be able to use process substitution. I haven't quite gotten it to work yet. This was my first attempt:

$ .useless.sh 2> >( ERROR=$(<) )
-bash: command substitution: line 42: syntax error near unexpected token `)'
-bash: command substitution: line 42: `<)'

Then I tried

$ ./useless.sh 2> >( ERROR=$( cat <() )  )
This Is Output
$ echo $ERROR   # $ERROR is empty

However

$ ./useless.sh 2> >( cat <() > asdf.txt )
This Is Output
$ cat asdf.txt
This Is Error

So the process substitution is doing generally the right thing... unfortunately, whenever I wrap STDIN inside >( ) with something in $() in an attempt to capture that to a variable, I lose the contents of $(). I think that this is because $() launches a sub process which no longer has access to the file descriptor in /dev/fd which is owned by the parent process.

Process substitution has bought me the ability to work with a data stream which is no longer in STDERR, unfortunately I don't seem to be able to manipulate it the way that I want.

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

How do you beta test an iphone app?

There's a relatively new service called HockeyApp, which seems to rival TestFlight, however they claim to give you access to unlimited users, but it does cost some $$ unlike TestFlight which has now been integrated directly into iTunes Connect.