Programs & Examples On #Greenfoot

Greenfoot is an environment that makes it very easy to create 2D animations and games using Java.

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

Which method performs better: .Any() vs .Count() > 0?

It depends, how big is the data set and what are your performance requirements?

If it's nothing gigantic use the most readable form, which for myself is any, because it's shorter and readable rather than an equation.

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

On windows, use https://github.com/Zapotek/raw2vmdk to convert raw files created by dd or winhex to vmdk. raw2vmdk v0.1.3.2 has a bug - once the vmdk file is created, edit the vmdk file and fix the path to the raw file (in my case instead of D:\Temp\flash_16gb.raw (created by winhex) the generated path was D:Tempflash_16gb.raw). Then, open it in a vmware virtual machine version 6.5-7 (5.1 was refusing to attach the vmdk harddrive). howgh!

Using a SELECT statement within a WHERE clause

In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.

private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...

Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.

m_subscriptionsSql = GetTable<SubscriptionModel>();

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

Find character position and update file name

The string is a .NET string so you can use .NET methods. In your case:

$index = "The string".IndexOf(" ")

will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx

For your need try something like:

$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)

Or you could use regexps:

if ($s -Match '(_)(.*)(\.)[^.]*$') {  $matches[2] }

(has to be adjusted depending on exactly what you need).

Importing text file into excel sheet

you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How do I declare a two dimensional array?

Just declare? You don't have to. Just make sure variable exists:

$d = array();

Arrays are resized dynamically, and attempt to write anything to non-exsistant element creates it (and creates entire array if needed)

$d[1][2] = 3;

This is valid for any number of dimensions without prior declarations.

Laravel 5 – Clear Cache in Shared Hosting Server

Basically I want to clear the views cache.

There is now a command in Laravel 5.1 for that

php artisan view:clear

DIV height set as percentage of screen?

By using absolute positioning, you can make <body> or <form> or <div>, fit to your browser page. For example:

<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">

and then simply put a <div> inside it and use whatever percentage of either height or width you wish

<div id="divContainer" style="height: 100%;">

Fitting iframe inside a div

Would this CSS fix it?

iframe {
    display:block;
    width:100%;
}

From this example: http://jsfiddle.net/HNyJS/2/show/

How to add 20 minutes to a current date?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);

How to restart counting from 1 after erasing table in MS Access?

In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.

Remove a child with a specific attribute, in SimpleXML for PHP

Even though SimpleXML doesn't have a detailed way to remove elements, you can remove elements from SimpleXML by using PHP's unset(). The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:

$target = false;
$i = 0;
foreach ($xml->seg as $s) {
  if ($s['id']=='A12') { $target = $i; break; }
  $i++;
}
if ($target !== false) {
  unset($xml->seg[$target]);
}

You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (array_reverse($targets)), because removing an item naturally reduces the order number of the items that come after it.

Admittedly, it's a bit of a hackaround, but it seems to work fine.

SQL injection that gets around mysql_real_escape_string()

TL;DR

mysql_real_escape_string() will provide no protection whatsoever (and could furthermore munge your data) if:

  • MySQL's NO_BACKSLASH_ESCAPES SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); and

  • your SQL string literals are quoted using double-quote " characters.

This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).

This is another, (perhaps less?) obscure EDGE CASE!!!

In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:

The Attack

Starting off with a demonstration...

mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

This will return all records from the test table. A dissection:

  1. Selecting an SQL Mode

    mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
    

    As documented under String Literals:

    There are several ways to include quote characters within a string:

    • A “'” inside a string quoted with “'” may be written as “''”.

    • A “"” inside a string quoted with “"” may be written as “""”.

    • Precede the quote character by an escape character (“\”).

    • A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.

    If the server's SQL mode includes NO_BACKSLASH_ESCAPES, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.

  2. The Payload

    " OR 1=1 -- 
    

    The payload initiates this injection quite literally with the " character. No particular encoding. No special characters. No weird bytes.

  3. mysql_real_escape_string()

    $var = mysql_real_escape_string('" OR 1=1 -- ');
    

    Fortunately, mysql_real_escape_string() does check the SQL mode and adjust its behaviour accordingly. See libmysql.c:

    ulong STDCALL
    mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
                 ulong length)
    {
      if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
        return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
      return escape_string_for_mysql(mysql->charset, to, 0, from, length);
    }
    

    Thus a different underlying function, escape_quotes_for_mysql(), is invoked if the NO_BACKSLASH_ESCAPES SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.

    However, this function arbitrarily assumes that the string will be quoted using the single-quote ' character. See charset.c:

    /*
      Escape apostrophes by doubling them up
    
    // [ deletia 839-845 ]
    
      DESCRIPTION
        This escapes the contents of a string by doubling up any apostrophes that
        it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
        effect on the server.
    
    // [ deletia 852-858 ]
    */
    
    size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
                                   char *to, size_t to_length,
                                   const char *from, size_t length)
    {
    // [ deletia 865-892 ]
    
        if (*from == '\'')
        {
          if (to + 2 > to_end)
          {
            overflow= TRUE;
            break;
          }
          *to++= '\'';
          *to++= '\'';
        }
    

    So, it leaves double-quote " characters untouched (and doubles all single-quote ' characters) irrespective of the actual character that is used to quote the literal! In our case $var remains exactly the same as the argument that was provided to mysql_real_escape_string()—it's as though no escaping has taken place at all.

  4. The Query

    mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
    

    Something of a formality, the rendered query is:

    SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
    

As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

mysql_set_charset() cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string(), since that's just a different wrapper around this same function.

The problem, if not already obvious, is that the call to mysql_real_escape_string() cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).

The Ugly

It gets worse. NO_BACKSLASH_ESCAPES may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote> grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes().

Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.

The Saving Grace

So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql() will not be used, or its assumption about which quote characters require repeating will be correct.

For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES also enables ANSI_QUOTES mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).

In PDO, both its equivalent function PDO::quote() and its prepared statement emulator call upon mysql_handle_quoter()—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.

As of MySQL v5.7.6, this bug has been fixed. See change log:

Functionality Added or Changed

Safe Examples

Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):

mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES.

mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

...because we're quoting our string literal with single-quotes.

$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);

...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).

$var  = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

...because PDO's quote() function not only escapes the literal, but also quotes it (in single-quote ' characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.

$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

...because MySQLi prepared statements are safe.

Wrapping Up

Thus, if you:

  • use native prepared statements

OR

  • use MySQL v5.7.6 or later

OR

  • in addition to employing one of the solutions in ircmaxell's summary, use at least one of:

    • PDO;
    • single-quoted string literals; or
    • an explicitly set SQL mode that does not include NO_BACKSLASH_ESCAPES

...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).

Applications are expected to have a root view controller at the end of application launch

I ran into this in an iPad application targeting iOS 5.1 in Xcode 4.5.1. The app uses UITabBarController. I needed a new section within the tab bar controller, so I created a new view controller and xib. Once I added the new view controller to the tab bar controller, none of my on-screen controls worked anymore, and I got the "expected to have a root view controller" log.

Somehow the top-level object in the new xib was UIWindow instead of UIView. When I dropped a UIView into the XIB, had the view outlet point to it, moved all the subviews into the new UIView, and removed the UIWindow instance, the problem was fixed.

How to change maven logging level to display only warning and errors?

Go to simplelogger.properties in ${MAVEN_HOME}/conf/logging/ and set the following properties:

org.slf4j.simpleLogger.defaultLogLevel=warn
org.slf4j.simpleLogger.log.Sisu=warn
org.slf4j.simpleLogger.warnLevelString=warn

And beware: warn, not warning

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

Convert UTC datetime string to local datetime

import datetime

def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
    """
    :param utc_str: UTC time string
    :param utc_format: format of UTC time string
    :param local_format: format of local time string
    :return: local time string
    """
    temp1 = datetime.datetime.strptime(utc_str, utc_format)
    temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
    local_time = temp2.astimezone()
    return local_time.strftime(local_format)

utc = '2018-10-17T00:00:00.111Z'
utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
local_fmt = '%Y-%m-%dT%H:%M:%S+08:00'
local_string = utc_str_to_local_str(utc, utc_fmt, local_fmt)
print(local_string)   # 2018-10-17T08:00:00+08:00

for example, my timezone is '+08:00'. input utc = 2018-10-17T00:00:00.111Z, then I will get output = 2018-10-17T08:00:00+08:00

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

INNER JOIN same table

Your query should work fine, but you have to use the alias parent to show the values of the parent table like this:

select 
  CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
  CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

Using C# to read/write Excel files (.xls/.xlsx)

If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.

There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.

How to filter (key, value) with ng-repeat in AngularJs?

Angular filters can only be applied to arrays and not objects, from angular's API -

"Selects a subset of items from array and returns it as a new array."

You have two options here:
1) move $scope.items to an array or -
2) pre-filter the ng-repeat items, like this:

<div ng-repeat="(k,v) in filterSecId(items)">
    {{k}} {{v.pos}}
</div>

And on the Controller:

$scope.filterSecId = function(items) {
    var result = {};
    angular.forEach(items, function(value, key) {
        if (!value.hasOwnProperty('secId')) {
            result[key] = value;
        }
    });
    return result;
}

jsfiddle: http://jsfiddle.net/bmleite/WA2BE/

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

How to negate specific word in regex?

A great way to do this is to use negative lookahead:

^(?!.*bar).*$

The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead [is any regex pattern].

Using Linq to get the last N elements of a collection?

If you don't mind dipping into Rx as part of the monad, you can use TakeLast:

IEnumerable<int> source = Enumerable.Range(1, 10000);

IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();

how to convert a string to a bool

I used the below code to convert a string to boolean.

Convert.ToBoolean(Convert.ToInt32(myString));

How to import and export components using React + ES6 + webpack?

Try defaulting the exports in your components:

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class MyNavbar extends React.Component {
    render(){
      return (
        <Navbar className="navbar-dark" fluid>
        ...
        </Navbar>
      );
    }
}

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

Prevent users from submitting a form by hitting Enter

In my case I had a couple of jQuery UI autocomplete fields and textareas in a form, so I definitely wanted them to accept Enter. So I removed the type="submit" input from a form and added an anchor <a href="" id="btn">Ok</a> instead. Then I styled it as a button and added the following code:

$( '#btn' ).click( function( event ){
    event.preventDefault();
    if ( validateData() ){
        $( 'form#frm' ).append( '<input type="submit" id="frm-submit" style="display:none;"></input>' );
        setTimeout( function(){ $( '#frm-submit' ).click(); }, 500 );
    }
    return false;
});

If a user fills all required fields, validateData() succeeds and the form submits.

Fastest way to iterate over all the chars in a String

The first one using str.charAt should be faster.

If you dig inside the source code of String class, we can see that charAt is implemented as follows:

public char charAt(int index) {
    if ((index < 0) || (index >= count)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index + offset];
}

Here, all it does is index an array and return the value.

Now, if we see the implementation of toCharArray, we will find the below:

public char[] toCharArray() {
    char result[] = new char[count];
    getChars(0, count, result, 0);
    return result;
}

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
    if (srcBegin < 0) {
        throw new StringIndexOutOfBoundsException(srcBegin);
    }
    if (srcEnd > count) {
        throw new StringIndexOutOfBoundsException(srcEnd);
    }
    if (srcBegin > srcEnd) {
        throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
    }
    System.arraycopy(value, offset + srcBegin, dst, dstBegin,
         srcEnd - srcBegin);
}

As you see, it is doing a System.arraycopy which is definitely going to be a tad slower than not doing it.

Split value from one field to two

In MySQL this is working this option:

SELECT Substring(nameandsurname, 1, Locate(' ', nameandsurname) - 1) AS 
       firstname, 
       Substring(nameandsurname, Locate(' ', nameandsurname) + 1)    AS lastname 
FROM   emp  

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Passing argument to alias in bash

Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:

function __t2d {                                                                
         if [ "$1x" != 'x' ]; then                                              
            date -d "@$1"                                                       
         fi                                                                     
} 

alias t2d='__t2d'                                                               

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

If you are looking to cobble together a quick utility with minimal effort, bash is good. For a wrapper round an application, bash is invaluable.

Anything that may have you coming back over and over to add improvements is probably (though not always) better suited to a language like Python as Bash code comprising over a 1000 lines gets very painful to maintain. Bash code is also irritating to debug when it gets long.......

Part of the problem with these kind of questions is, from my experience, that shell scripts are usually all custom tasks. There have been very few shell scripting tasks that I have come across where there is already a solution freely available.

@Autowired - No qualifying bean of type found for dependency

My guess is that here

<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

all annotations are first disabled by use-default-filters="false" and then only @Controller annotation enabled. Thus, your @Component annotation is not enabled.

To draw an Underline below the TextView in Android

In Kotlin you can create extension property:

inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:

textView.underline = true

Encrypt Password in Configuration Files?

Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.

If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.

Detecting the onload event of a window opened with window.open

The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.

One possibility could be to use the 'pageshow' -event instead, as described in:

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

How to convert binary string value to decimal

public static void main(String[] args) {

    java.util.Scanner scan = new java.util.Scanner(System.in);
    long decimalValue = 0;

    System.out.println("Please enter a positive binary number.(Only 1s and 0s)");

    //This reads the input as a String and splits each symbol into 
    //array list
    String element = scan.nextLine();
    String[] array = element.split("");

    //This assigns the length to integer arrys based on actual number of 
    //symbols entered
    int[] numberSplit = new int[array.length];
    int position = array.length - 1; //set beginning position to the end of array

    //This turns String array into Integer array
    for (int i = 0; i < array.length; i++) {
        numberSplit[i] = Integer.parseInt(array[i]);
    }
    //This loop goes from last to first position of an array making
    //calculation where power of 2 is the current loop instance number
    for (int i = 0; i < array.length; i++) {
        if (numberSplit[position] == 1) {
            decimalValue = decimalValue + (long) Math.pow(2, i);
        }
        position--;
    }
    System.out.println(decimalValue);
    main(null);

}

Oracle: SQL query that returns rows with only numeric values

If the only characters to consider are letters then you can do:

select X from myTable where upper(X) = lower(X)

But of course that won't filter out other characters, just letters.

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

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

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

Update:

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

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Partial Dependency (Databases)

If there is a Relation R(ABC)

-----------
|A | B | C |
-----------
|a | 1 | x |
|b | 1 | x |
|c | 1 | x |
|d | 2 | y |
|e | 2 | y |
|f | 3 | z |
|g | 3 | z |
 ----------
Given,
F1: A --> B 
F2: B --> C

The Primary Key and Candidate Key is: A

As the closure of A+ = {ABC} or R --- So only attribute A is sufficient to find Relation R.

DEF-1: From Some Definitions (unknown source) - A partial dependency is a dependency when prime attribute (i.e., an attribute that is a part(or proper subset) of Candidate Key) determines non-prime attribute (i.e., an attribute that is not the part (or subset) of Candidate Key).

Hence, A is a prime(P) attribute and B, C are non-prime(NP) attributes.

So, from the above DEF-1,

CONSIDERATION-1:: F1: A --> B (P determines NP) --- It must be Partial Dependency.

CONSIDERATION-2:: F2: B --> C (NP determines NP) --- Transitive Dependency.

What I understood from @philipxy answer (https://stackoverflow.com/a/25827210/6009502) is...

CONSIDERATION-1:: F1: A --> B; Should be fully functional dependency because B is completely dependent on A and If we Remove A then there is no proper subset of (for complete clarification consider L.H.S. as X NOT BY SINGLE ATTRIBUTE) that could determine B.

For Example: If I consider F1: X --> Y where X = {A} and Y = {B} then if we remove A from X; i.e., X - {A} = {}; and an empty set is not considered generally (or not at all) to define functional dependency. So, there is no proper subset of X that could hold the dependency F1: X --> Y; Hence, it is fully functional dependency.

F1: A --> B If we remove A then there is no attribute that could hold functional dependency F1. Hence, F1 is fully functional dependency not partial dependency.

If F1 were, F1: AC --> B;
and F2 were, F2: C --> B; 
then on the removal of A;
C --> B that means B is still dependent on C; 
we can say F1 is partial dependecy.

So, @philipxy answer contradicts DEF-1 and CONSIDERATION-1 that is true and crystal clear.

Hence, F1: A --> B is Fully Functional Dependency not partial dependency.

I have considered X to show left hand side of functional dependency because single attribute couldn't have a proper subset of attributes. Here, I am considering X as a set of attributes and in current scenario X is {A}

-- For the source of DEF-1, please search on google you may be able to hit similar definitions. (Consider that DEF-1 is incorrect or do not work in the above-mentioned example).

How can I perform a short delay in C# without using sleep?

If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.

How it works is that you mark the function in need of asynchronous operations, with the async keyword. This is just a hint to the compiler. Then you use the await keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async keyword as well and is usually named ending with Async, as in ImportFilesAsync.

What you need to do in your example is:

  1. Make sure your program has .Net Framework 4.5 as Target Framework
  2. Mark your function that needs to sleep with the async keyword (see example below)
  3. Add using System.Threading.Tasks; to your code.

Your code is now ready to use the Task.Delay method instead of the System.Threading.Thread.Sleep method (it is possible to use await on Task.Delay because Task.Delay is marked with async in its definition).

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "\r\nThread Sleeps!";
    await Task.Delay(3000);
    textBox1.Text += "\r\nThread awakens!";
}

Here you can read more about Task.Delay and Await.

"Operation must use an updateable query" error in MS Access

I got this same error and using a primary key did not make a difference. The issue was that the table is a linked Excel table. I know there are settings to change this but my IT department has locked this so we cant change it. Instead, I created a make table from the linked table and used that instead in my Update Query and it worked. Note, any queries in your query that are also linked to the same Excel linked table will cause the same error so you will need to change these as well so they are not directly linked to the Excel linked table. HTH

regular expression for DOT

...

[.]{1}

or

[.]{2}

?

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

jQuery pass more parameters into callback

$(document).on('click','[action=register]',function(){
    registerSocket(registerJSON(),registerDone,second($(this)));
});

function registerSocket(dataFn,doneFn,second){
                 $.ajax({
                       type:'POST',
                       url: "http://localhost:8080/store/public/register",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       data:dataFn
                 }).done ([doneFn,second])
                   .fail(function(err){
                            console.log("AJAX failed: " + JSON.stringify(err, null, 2));
                        });
}

function registerDone(data){
    console.log(JSON.stringify(data));
}
function second(element){
    console.log(element);
}

Secondary way :

function socketWithParam(url,dataFn,doneFn,param){
  $.ajax({
    type:'POST',
    url:url,
    contentType: "application/json; charset=utf-8",
    headers: { 'Authorization': 'Bearer '+localStorage.getItem('jwt')},
    data:dataFn
    }).done(function(data){
      doneFn(data,param);
    })
    .fail(function(err,status,xhr){
    console.log("AJAX failed: " + JSON.stringify(err, null, 2));
    });
}

$(document).on('click','[order-btn]',function(){
  socketWithParam(url,fakeDataFn(),orderDetailDone,secondParam);
});

function orderDetailDone(data,param){
  -- to do something --
}

Best way to check for IE less than 9 in JavaScript without library

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

Dynamically Add C# Properties at Runtime

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

    var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
    foreach (var property in properties) {
        dynamicObject.Add(property.Key,property.Value);
    }

How do I undo a checkout in git?

Try this first:

git checkout master

(If you're on a different branch than master, use the branch name there instead.)

If that doesn't work, try...

For a single file:

git checkout HEAD /path/to/file

For the entire repository working copy:

git reset --hard HEAD

And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:

git reflog
git reset --hard <sha from reflog>

HEAD is a name that always points to the latest commit in your current branch.

Environment variable to control java.io.tmpdir?

Use

$ java -XshowSettings
Property settings:
    java.home = /home/nisar/javadev/javasuncom/jdk1.7.0_17/jre
    java.io.tmpdir = /tmp

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

How to scanf only integer and repeat reading if the user enters non-numeric characters?

#include <stdio.h>
main()
{
    char str[100];
    int num;
    while(1) {
        printf("Enter a number: ");
        scanf("%[^0-9]%d",str,&num);
        printf("You entered the number %d\n",num);
    }
    return 0;
}

%[^0-9] in scanf() gobbles up all that is not between 0 and 9. Basically it cleans the input stream of non-digits and puts it in str. Well, the length of non-digit sequence is limited to 100. The following %d selects only integers in the input stream and places it in num.

Comparison of DES, Triple DES, AES, blowfish encryption for data

All of these schemes, except AES and Blowfish, have known vulnerabilities and should not be used.
However, Blowfish has been replaced by Twofish.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

Changing all files' extensions in a folder with one command on Windows

NOTE: not for Windows

Using ren-1.0 the correct form is:

"ren *.*" "#2.jpg"

From man ren

The replacement pattern is another filename with embedded wildcard indexes, each of which consists of the character # followed by a digit from 1 to 9. In the new name of a matching file, the wildcard indexes are replaced by the actual characters that matched the referenced wildcards in the original filename.

and

Note that the shell normally expands the wildcards * and ?, which in the case of ren is undesirable. Thus, in most cases it is necessary to enclose the search pattern in quotes.

How to include duplicate keys in HashMap?

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);
    }
    currentValue.add(newValue);
}

Easiest way to convert int to string in C++

Not that I know of, in pure C++. But a little modification of what you mentioned

string s = string(itoa(a));

should work, and it's pretty short.

Updates were rejected because the tip of your current branch is behind its remote counterpart

To make sure your local branch FixForBug is not ahead of the remote branch FixForBug pull and merge the changes before pushing.

git pull origin FixForBug
git push origin FixForBug

Defining custom attrs

Currently the best documentation is the source. You can take a look at it here (attrs.xml).

You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.

An <attr> element has two xml attributes name and format. name lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute. The format attribute can have different values depending on the 'type' of attribute you want.

  • reference - if it references another resource id (e.g, "@color/my_color", "@layout/my_layout")
  • color
  • boolean
  • dimension
  • float
  • integer
  • string
  • fraction
  • enum - normally implicitly defined
  • flag - normally implicitly defined

You can set the format to multiple types by using |, e.g., format="reference|color".

enum attributes can be defined as follows:

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag attributes are similar except the values need to be defined so they can be bit ored together:

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

In addition to attributes there is the <declare-styleable> element. This allows you to define attributes a custom view can use. You do this by specifying an <attr> element, if it was previously defined you do not specify the format. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name, as follows.

An example of a custom view <declare-styleable>:

<declare-styleable name="MyCustomView">
  <attr name="my_custom_attribute" />
  <attr name="android:gravity" />
</declare-styleable>

When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android". You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto".

Example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:whatever="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <org.example.mypackage.MyCustomView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>

Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);

  String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);

  //do something with str

  a.recycle();
}

The end. :)

Named capturing groups in JavaScript regex?

In ES6 you can use array destructuring to catch your groups:

let text = '27 months';
let regex = /(\d+)\s*(days?|months?|years?)/;
let [, count, unit] = regex.exec(text) || [];

// count === '27'
// unit === 'months'

Notice:

  • the first comma in the last let skips the first value of the resulting array, which is the whole matched string
  • the || [] after .exec() will prevent a destructuring error when there are no matches (because .exec() will return null)

Upgrade python without breaking yum

Put /opt/python2.7/bin in your PATH environment variable in front of /usr/bin...or just get used to typing python2.7.

Comments in Markdown

Also see Critic Markup, supported by an increasing number of Markdown tools.

http://criticmarkup.com/

Comment {>> <<}

Lorem ipsum dolor sit amet.{>>This is a comment<<}

Highlight+Comment {== ==}{>> <<}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. {==Vestibulum at orci magna. Phasellus augue justo, sodales eu pulvinar ac, vulputate eget nulla.==}{>>confusing<<} Mauris massa sem, tempor sed cursus et, semper tincidunt lacus.

Can we import XML file into another XML file?

You could use an external (parsed) general entity.

You declare the entity like this:

<!ENTITY otherFile SYSTEM "otherFile.xml">

Then you reference it like this:

&otherFile;

A complete example:

<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
  <foo>
    <bar>&otherFile;</bar>
  </foo>
</doc>

When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.

If the "otherFile.xml" contained: <baz>this is my content</baz>

Then the XML would be evaluated and "seen" by an XML parser as:

<?xml version="1.0" standalone="no" ?>
<doc>
  <foo>
    <bar><baz>this is my content</baz></bar>
  </foo>
</doc>

A few references that might be helpful:

Perl read line by line

you need to use ++$counter, not $++counter, hence the reason it isn't working..

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

How do I get the object if it exists, or None if it does not exist?

It's one of those annoying functions that you might not want to re-implement:

from annoying.functions import get_object_or_None
#...
user = get_object_or_None(Content, name="baby")

how to use substr() function in jquery?

Extract characters from a string:

var str = "Hello world!";
var res = str.substring(1,4);

The result of res will be:

ell

http://www.w3schools.com/jsref/jsref_substring.asp

$('.dep_buttons').mouseover(function(){
    $(this).text().substring(0,25);
    if($(this).text().length > 30) {
        $(this).stop().animate({height:"150px"},150);
    }
    $(".dep_buttons").mouseout(function(){
        $(this).stop().animate({height:"40px"},150);
    });
});

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

jquery ajax get responsetext from http url

First you have to download a JQuery plugin to allow Cross-domain requests. Download it here: https://github.com/padolsey/jQuery-Plugins/downloads

Import the file called query.xdomainsajax.js into your project and include it with this code:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

To get the html of an external web page in text form you can write this:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});

What is so bad about singletons?

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

How to get height of entire document with JavaScript?

Add References properly

In my case I was using a ASCX page and the aspx page that contains the ascx control is not using the references properly. I just pasted the following code and it worked :

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Using the ES2015 Spread operator:

[...Array(n)].map()

const res = [...Array(10)].map((_, i) => {
  return i * 10;
});

// as a one liner
const res = [...Array(10)].map((_, i) => i * 10);

Or if you don't need the result:

[...Array(10)].forEach((_, i) => {
  console.log(i);
});

// as a one liner
[...Array(10)].forEach((_, i) => console.log(i));

Or using the ES2015 Array.from operator:

Array.from(...)

const res = Array.from(Array(10)).map((_, i) => {
  return i * 10;
});

// as a one liner
const res = Array.from(Array(10)).map((_, i) => i * 10);

Note that if you just need a string repeated you can use String.prototype.repeat.

console.log("0".repeat(10))
// 0000000000

SSIS Convert Between Unicode and Non-Unicode Error

When creating table in SQL Server make your table columns NVARCHAR instead of VARCHAR.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Render HTML string as real HTML in a React component

I use 'react-html-parser'

yarn add react-html-parser
import ReactHtmlParser from 'react-html-parser'; 

<div> { ReactHtmlParser (html_string) } </div>

Source on npmjs.com

Lifting up @okram's comment for more visibility:

from its github description: Converts HTML strings directly into React components avoiding the need to use dangerouslySetInnerHTML from npmjs.com A utility for converting HTML strings into React components. Avoids the use of dangerouslySetInnerHTML and converts standard HTML elements, attributes and inline styles into their React equivalents.

Can RDP clients launch remote applications and not desktops

Yes, you can change the default shell from Explorer.exe to a specific application.

In Regedit, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. The current shell should be Explorer.exe. Change it to YourApp.exe. That will change the shell for all users who log on to the machine. If you only want to change it for a specific user, go to the same key in HKEY_CURRENT_USER instead.

Can Powershell Run Commands in Parallel?

If you're using latest cross platform powershell (which you should btw) https://github.com/powershell/powershell#get-powershell, you can add single & to run parallel scripts. (Use ; to run sequentially)

In my case I needed to run 2 npm scripts in parallel: npm run hotReload & npm run dev


You can also setup npm to use powershell for its scripts (by default it uses cmd on windows).

Run from project root folder: npm config set script-shell pwsh --userconfig ./.npmrc and then use single npm script command: npm run start

"start":"npm run hotReload & npm run dev"

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

How to generate a core dump in Linux on a segmentation fault?

Ubuntu 19.04

All other answers themselves didn't help me. But the following sum up did the job

Create ~/.config/apport/settings with the following content:

[main]
unpackaged=true

(This tells apport to also write core dumps for custom apps)

check: ulimit -c. If it outputs 0, fix it with

ulimit -c unlimited

Just for in case restart apport:

sudo systemctl restart apport

Crash files are now written in /var/crash/. But you cannot use them with gdb. To use them with gdb, use

apport-unpack <location_of_report> <target_directory>

Further information:

  • Some answers suggest changing core_pattern. Be aware, that that file might get overwritten by the apport service on restarting.
  • Simply stopping apport did not do the job
  • The ulimit -c value might get changed automatically while you're trying other answers of the web. Be sure to check it regularly during setting up your core dump creation.

References:

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      stack()
      {element=new int[10];
      top=-1;
      }
      void push(int item)
      {top++;
      if(top==9)
          System.out.println("Overflow");
      else
              {
               top++;
      element[top]=item;

      }

      void pop()
      {if(top==-1)
          System.out.println("Underflow");
      else  
      top--;
      }
      void display()
      {
          System.out.println("\nTop="+top+"\nElement="+element[top]);
      }

      public static void main(String args[])
      {
        stack s1=new stack();
        s1.push(10);
        s1.display();
        s1.push(20);
        s1.display();
        s1.push(30);
        s1.display();
        s1.pop();
        s1.display();
      }

  }

Output

Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

Can't change z-index with JQuery

because your jQuery code is wrong. Correctly would be:

var theParent = $(this).parent().get(0); 
$(theParent).css('z-index', 3000);

Python, how to read bytes from file and save it?

Here's how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.

in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()

out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()

We can do this more succinctly by using the with keyboard to handle closing the file.

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    out_file.write(in_file.read())

If you don't want to store the entire file in memory, you can transfer it in pieces.

piece_size = 4096 # 4 KiB

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    while True:
        piece = in_file.read(piece_size)

        if piece == "":
            break # end of file

        out_file.write(piece)

Does Django scale?

My experience with Django is minimal but I do remember in The Django Book they have a chapter where they interview people running some of the larger Django applications. Here is a link. I guess it could provide some insights.

It says curse.com is one of the largest Django applications with around 60-90 million page views in a month.

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

Stop node.js program from command line

For windows first search the PID with your port number

netstat -ano | findStr "portNumber"

After that, kill the task, make sure you are in root of your "c" drive enter image description here And the command will be taskkill /F /PID your pid

Command to collapse all sections of code?

CTL + M + A collapses all

works for me, whereas

CTL + M + O

does not

jQuery if statement to check visibility

try

if ($('#column-left form:visible').length > 0) { ...

What is the difference between MOV and LEA?

In NASM syntax:

mov eax, var       == lea eax, [var]   ; i.e. mov r32, imm32
lea eax, [var+16]  == mov eax, var+16
lea eax, [eax*4]   == shl eax, 2        ; but without setting flags

In MASM syntax, use OFFSET var to get a mov-immediate instead of a load.

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

How to modify list entries during for loop?

It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
    for i in range(my_strings.count(undesirable_string)):
        my_strings.remove(undesirable_string)

which changes my_strings to ['a', 'c', 'e']

Determine distance from the top of a div to top of window with javascript

Vanilla:

window.addEventListener('scroll', function(ev) {

   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;

   console.log(distanceToTop);
});

Open your browser console and scroll your page to see the distance.

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

Button background as transparent

Add this in your Xml - android:background="@android:color/transparent"

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Button"
            android:background="@android:color/transparent"
            android:textStyle="bold"/>

Redirect after Login on WordPress

To globally redirect after successful login, find this code in wp-login.php, under section.

   <form name="loginform" id="loginform" action="<?php echo esc_url( site_url( 'wp-login.php', 'login_post' ) ); ?>" method="post">

<input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />

and replace <?php echo esc_attr($redirect_to); ?> with your URL where you want to redirect. The URL must start with http:// and ends on /other wise page redirect to default location.

Do same thing form redirect after registration with in same file but under <form name="registerform"> section.

Batch: Remove file extension

I'm also a stranger to windows cmd, but try this:

echo %%~nf

How to use support FileProvider for sharing content to other apps?

As far as I can tell this will only work on newer versions of Android, so you will probably have to figure out a different way to do it. This solution works for me on 4.4, but not on 4.0 or 2.3.3, so this will not be a useful way to go about sharing content for an app that's meant to run on any Android device.

In manifest.xml:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mydomain.myapp.SharingActivity"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Take careful note of how you specify the authorities. You must specify the activity from which you will create the URI and launch the share intent, in this case the activity is called SharingActivity. This requirement is not obvious from Google's docs!

file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="just_a_name" path=""/>
</paths>

Be careful how you specify the path. The above defaults to the root of your private internal storage.

In SharingActivity.java:

Uri contentUri = FileProvider.getUriForFile(getActivity(),
"com.mydomain.myapp.SharingActivity", myFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share with"));

In this example we are sharing a JPEG image.

Finally it is probably a good idea to assure yourself that you have saved the file properly and that you can access it with something like this:

File myFile = getActivity().getFileStreamPath("mySavedImage.jpeg");
if(myFile != null){
    Log.d(TAG, "File found, file description: "+myFile.toString());
}else{
    Log.w(TAG, "File not found!");
}

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

How to convert latitude or longitude to meters?

Given you're looking for a simple formula, this is probably the simplest way to do it, assuming that the Earth is a sphere with a circumference of 40075 km.

Length in meters of 1° of latitude = always 111.32 km

Length in meters of 1° of longitude = 40075 km * cos( latitude ) / 360

Int to byte array

Update for 2020 - BinaryPrimitives should now be preferred over BitConverter. It provides endian-specific APIs, and is less allocatey.


byte[] bytes = BitConverter.GetBytes(i);

although note also that you might want to check BitConverter.IsLittleEndian to see which way around that is going to appear!

Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>> / <<), or by using unsafe code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

How to set width of a div in percent in JavaScript?

The question is what do you want the div's height/width to be a percent of?

By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.

So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:

obj.style.width = '50%';

Search for a string in all tables, rows and columns of a DB

/*
This procedure is for finding any string or date in all tables
if search string is date, its format should be yyyy-MM-dd
eg. 2011-07-05
*/

-- ================================================
-- Exec SearchInTables 'f6f56934-a5d4-4967-80a1-1a2223b9c7b1'

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Joshy,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE SearchInTables
@myValue nvarchar(1000)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
        DECLARE @searchsql nvarchar(max)
        DECLARE @table_name nvarchar(1000)
        DECLARE @Schema_name nvarchar(1000)
        DECLARE @ParmDefinition nvarchar(500)
        DECLARE @XMLIn nvarchar(max)
        SET @ParmDefinition = N'@XMLOut varchar(max) OUTPUT'

        SELECT A.name,b.name 
        FROM sys.tables A 
            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
        WHERE A.name like 'tbl_Tax_Sections' 

        DECLARE tables_cur CURSOR FOR 
                            SELECT A.name,b.name FOM sys.tables A 
                            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
                            WHERE A.type = 'U'  
        OPEN tables_cur  
        FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 
            WHILE (@@FETCH_STATUS = 0) 
            BEGIN
                SET @searchsql ='SELECT @XMLOut=(SELECT PATINDEX(''%'+ @myValue+ '%'''
                SET @searchsql =@searchsql  + ', (SELECT * FROM '+@Schema_name+'.'+@table_name+' FOR XML AUTO) ))'
                --print @searchsql 
                EXEC sp_executesql @searchsql, @ParmDefinition, @XMLOut=@XMLIn OUTPUT
                --print @XMLIn 

                IF @XMLIn <> 0 PRINT @Schema_name+'.'+@table_name

                FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 

            END
        CLOSE tables_cur 
        DEALLOCATE tables_cur 
    RETURN
END
GO

How do I get this javascript to run every second?

Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

var t=setInterval(runFunction,1000);

And to stop it, you can run:

clearInterval(t);

Application Installation Failed in Android Studio

I had the same issue in MIUI. Enabling OEM unlocking worked for me without disabling MIUI optimization.

Below is a screenshot of my Redmi 3s prime developer options setting:

screenshot of my Redmi 3s prime developer options setting

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

Accessing Google Spreadsheets with C# using Google Data API

According to the .NET user guide:

Download the .NET client library:

Add these using statements:

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;

Authenticate:

SpreadsheetsService myService = new SpreadsheetsService("exampleCo-exampleApp-1");
myService.setUserCredentials("[email protected]", "mypassword");

Get a list of spreadsheets:

SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = myService.Query(query);

Console.WriteLine("Your spreadsheets: ");
foreach (SpreadsheetEntry entry in feed.Entries)
{
    Console.WriteLine(entry.Title.Text);
}

Given a SpreadsheetEntry you've already retrieved, you can get a list of all worksheets in this spreadsheet as follows:

AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);

WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
WorksheetFeed feed = service.Query(query);

foreach (WorksheetEntry worksheet in feed.Entries)
{
    Console.WriteLine(worksheet.Title.Text);
}

And get a cell based feed:

AtomLink cellFeedLink = worksheetentry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);

CellQuery query = new CellQuery(cellFeedLink.HRef.ToString());
CellFeed feed = service.Query(query);

Console.WriteLine("Cells in this worksheet:");
foreach (CellEntry curCell in feed.Entries)
{
    Console.WriteLine("Row {0}, column {1}: {2}", curCell.Cell.Row,
        curCell.Cell.Column, curCell.Cell.Value);
}

Shadow Effect for a Text in Android?

Perhaps you'd consider using android:shadowColor, android:shadowDx, android:shadowDy, android:shadowRadius; alternatively setShadowLayer() ?

How can I remove a style added with .css() function?

Try

document.body.style=''

_x000D_
_x000D_
$("body").css("background-color", 'red');

function clean() {
  document.body.style=''
}
_x000D_
body { background-color: yellow; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="clean()">Remove style</button>
_x000D_
_x000D_
_x000D_

How to use variables in SQL statement in Python?

http://www.amk.ca/python/writing/DB-API.html

Be careful when you simply append values of variables to your statements: Imagine a user naming himself ';DROP TABLE Users;' -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:

cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )

JavaScript loop through json array?

your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"

{"item":[
{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
}]}

your java script is simply

var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
    var curitem = json.item[x];
}

How does "cat << EOF" work in bash?

A little extension to the above answers. The trailing > directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >> that appends, adding your new content to the end of the file, as in:

cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert   /var/sharedFolder/sometin/vsdc/cert nfs
EOF

This extends your fstab without you having to worry about accidentally modifying any of its contents.

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

How to show google.com in an iframe?

IT IS NOT IMPOSSIBLE.
Use a reverse proxy server to handle the Different-Origin-Problem. I used to using Nginx with proxy_pass to change the url of page. you can have a try.

Another way is to write a simple proxy page runs on server by yourself, just request from Google and output the result to the client.

How can git be installed on CENTOS 5.5?

If you are using CentOS the built in yum repositories don't seem to have git included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git will then be as follows:

# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm

# Install the latest version of git
yum install --enablerepo=webtatic git-all

To work around Missing Dependency: perl(Git) errors:

yum install --enablerepo=webtatic --disableexcludes=main  git-all

Stretch and scale a CSS image in the background - with CSS only

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

Error: free(): invalid next size (fast):

If you are trying to allocate space for an array of pointers, such as

char** my_array_of_strings;  // or some array of pointers such as int** or even void**

then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers. The size of a pointer is the same of your word size.

So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)

To avoid overflowing your allocated memory for n elements of 8 bytes:

my_array_of_strings = (char**) malloc( n * 8 );  // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 );  // for 32-bit systems

This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)

I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error. And it is a bad one, when you overflow allocated memory, many security issues lie in wait.

JUnit: how to avoid "no runnable methods" in test utils classes

To prevent JUnit from instantiating your test base class just make it

public abstract class MyTestBaseClass { ... whatever... }

(@Ignore reports it as ignored which I reserve for temporarily ignored tests.)

Java: Best way to iterate through a Collection (here ArrayList)

Here is an example

Query query = em.createQuery("from Student");
             java.util.List list = query.getResultList();
             for (int i = 0; i < list.size(); i++) 
             {

                 student = (Student) list.get(i);
                 System.out.println(student.id  + "  " + student.age + " " + student.name + " " + student.prenom);

             }

How do write IF ELSE statement in a MySQL query

You're looking for case:

case when action = 2 and state = 0 then 1 else 0 end as state

MySQL has an if syntax (if(action=2 and state=0, 1, 0)), but case is more universal.

Note that the as state there is just aliasing the column. I'm assuming this is in the column list of your SQL query.

How can I split a text file using PowerShell?

Same as all the answers here, but using StreamReader/StreamWriter to split on new lines (line by line, instead of trying to read the whole file into memory at once). This approach can split big files in the fastest way I know of.

Note: I do very little error checking, so I can't guarantee it'll work smoothly for your case. It did for mine (1.7 GB TXT file of 4 million lines split in 100,000 lines per file in 95 seconds).

#split test
$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
$filename = "C:\Users\Vincent\Desktop\test.txt"
$rootName = "C:\Users\Vincent\Desktop\result"
$ext = ".txt"

$linesperFile = 100000#100k
$filecount = 1
$reader = $null
try{
    $reader = [io.file]::OpenText($filename)
    try{
        "Creating file number $filecount"
        $writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
        $filecount++
        $linecount = 0

        while($reader.EndOfStream -ne $true) {
            "Reading $linesperFile"
            while( ($linecount -lt $linesperFile) -and ($reader.EndOfStream -ne $true)){
                $writer.WriteLine($reader.ReadLine());
                $linecount++
            }

            if($reader.EndOfStream -ne $true) {
                "Closing file"
                $writer.Dispose();

                "Creating file number $filecount"
                $writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
                $filecount++
                $linecount = 0
            }
        }
    } finally {
        $writer.Dispose();
    }
} finally {
    $reader.Dispose();
}
$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"

Output splitting a 1.7 GB file:

...
Creating file number 45
Reading 100000
Closing file
Creating file number 46
Reading 100000
Closing file
Creating file number 47
Reading 100000
Closing file
Creating file number 48
Reading 100000
Split complete in  95.6308289 seconds

Bootstrap modal appearing under background

I was fixed this by adding style below to DIV tag

style="background-color: rgba(0, 0, 0, 0.5);"

And add custom css

.modal-backdrop {position: relative;}

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

How to select from subquery using Laravel Query Builder?

In addition to @delmadord's answer and your comments:

Currently there is no method to create subquery in FROM clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:

$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
    ->count();

Mind that you need to merge bindings in correct order. If you have other bound clauses, you must put them after mergeBindings:

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )

    // ->where(..) wrong

    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder

    // ->where(..) correct

    ->count();

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

Convert String to equivalent Enum value

Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

What is JavaScript garbage collection?

"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application."

All JavaScript engines have their own garbage collectors, and they may differ. Most time you do not have to deal with them because they just do what they supposed to do.

Writing better code mostly depends of how good do you know programming principles, language and particular implementation.

Can I have onScrollListener for a ScrollView?

Every instance of View calls getViewTreeObserver(). Now when holding an instance of ViewTreeObserver, you can add an OnScrollChangedListener() to it using the method addOnScrollChangedListener().

You can see more information about this class here.

It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY() or getScrollX() from within the listener though.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        int scrollY = rootScrollView.getScrollY(); // For ScrollView
        int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
        // DO SOMETHING WITH THE SCROLL COORDINATES
    }
});

How to round double to nearest whole number and then convert to a float?

For what is worth:

the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer

+-------+--------+
| input | output |
+-------+--------+
|     1 |      0 |
|     2 |      0 |
|     3 |      5 |
|     4 |      5 |
|     5 |      5 |
|     6 |      5 |
|     7 |      5 |
|     8 |     10 |
|     9 |     10 |
+-------+--------+

private int roundClosest(final int i, final int k) {
    int deic = (i % k);
    if (deic <= (k / 2.0)) {
        return (int) (Math.floor(i / (double) k) * k);
    } else {
        return (int) (Math.ceil(i / (double) k) * k);
    }
}

Console.WriteLine and generic List

Also you can do join:

var qwe = new List<int> {5, 2, 3, 8};
Console.WriteLine(string.Join("\t", qwe));

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

How can you flush a write using a file descriptor?

fflush() only flushes the buffering added by the stdio fopen() layer, as managed by the FILE * object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE * layer, using fileno() and a raw write(), are also not buffered in a way that fflush() would flush.

As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl(), then open() the file yourself directly, without using fopen<() and friends from stdio.

Put search icon near textbox using bootstrap

Here are three different ways to do it:

screenshot

Here's a working Demo in Fiddle Of All Three

Validation:

You can use native bootstrap validation states (No Custom CSS!):

<div class="form-group has-feedback">
    <label class="control-label" for="inputSuccess2">Name</label>
    <input type="text" class="form-control" id="inputSuccess2"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>

For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box

Input Group:

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box

Unstyled Input Group:

You can still use .input-group for positioning but just override the default styling to make the two elements appear separate.

Use a normal input group but add the class input-group-unstyled:

<div class="input-group input-group-unstyled">
    <input type="text" class="form-control" />
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Then change the styling with the following css:

.input-group.input-group-unstyled input.form-control {
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;
}

Also, these solutions work for any input size

Why does Google prepend while(1); to their JSON responses?

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.

There are multiple countermeasures:

Making sure the JSON never executes

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

Things like for(;;); have been seen at Facebook for instance, with the same results.

Making sure the JSON is not valid JavaScript

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

Always return JSON with an Object on the outside

This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.

Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.

A valid JSON object, when not enclosed by anything, is not valid in JavaScript:

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :

This is however valid JSON:

JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.

Comparison of above methods

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.

Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.

Generate UML Class Diagram from Java Project

I´d say MoDisco is by far the most powerful one (though probably not the easiest one to work with).

MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

Reading file using fscanf() in C

fscanf will treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I see a couple of issues.

First:

ser.read() is only going to return 1 byte at a time.

If you specify a count

ser.read(5)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

That will continue to read characters until an EOL is received.

Second:

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

Get rid of the

for line in ser.read():

and just say:

line = ser.readline()

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

unable to start mongodb local server

if you are running mongo for first time you might wanna set the path first

mongod --dbpath <path to the directory>

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

Xcode - ld: library not found for -lPods

I had the same problem

pod install and pod update on command line resolve my problem

CSS/HTML: What is the correct way to make text italic?

Use <em> if you need some words/characters in italic in content without other styles. It also helps make content semantic.

text-style is better suited for multiple styles and no semantic need.

Sorting object property by values

For completeness sake, this function returns sorted array of object properties:

function sortObject(obj) {
    var arr = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            arr.push({
                'key': prop,
                'value': obj[prop]
            });
        }
    }
    arr.sort(function(a, b) { return a.value - b.value; });
    //arr.sort(function(a, b) { a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); //use this to sort as strings
    return arr; // returns array
}

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var arr = sortObject(list);
console.log(arr); // [{key:"bar", value:15}, {key:"me", value:75}, {key:"you", value:100}, {key:"foo", value:116}]

Jsfiddle with the code above is here. This solution is based on this article.

Updated fiddle for sorting strings is here. You can remove both additional .toLowerCase() conversions from it for case sensitive string comparation.

Matplotlib/pyplot: How to enforce axis range?

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

How to get active user's UserDetails

You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.

@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
   String userName = auth.getName(); 
   return <ReturnType>;
}

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.

-moz-background-position: -9999px -9999px!important;

This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.

PHP - Fatal error: Unsupported operand types

$total_ratings is an array, which you can't use for a division.

From above:

$total_ratings = mysqli_fetch_array($result);

PHP fwrite new line

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

Limit to 2 decimal places with a simple pipe

Well now will be different after angular 5:

{{ number | currency :'GBP':'symbol':'1.2-2' }}

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If we don't know anything about those numbers, we are limited by the following constraints:

  • we need to load all numbers before we can sort them them,
  • the set of numbers is not compressible.

If these assumptions hold, there is no way to carry out your task, as you will need at least 26,575,425 bits of storage (3,321,929 bytes).

What can you tell us about your data ?

How to determine the last Row used in VBA including blank spaces in between

Better:

if cells(i,1)="" then 
nextEmpty=i: 
exit for

How to use Utilities.sleep() function

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

Android ClassNotFoundException: Didn't find class on path

java.lang.RuntimeException: Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication: java.lang.ClassNotFoundException: Didn't find class "com.android.tools.fd.runtime.BootstrapApplication" on path: /data/app.apk(in android 4.3, 4.1)

Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication: java.lang.ClassNotFoundException: com.android.tools.fd.runtime.BootstrapApplication(in below lollipop iam facing like this error)

To disable Instant Run, it will work fine follow the below steps to disable instant run in android studio 1. Go to File Settings--> Build,Execution,Deployment -->Instant Run ---> uncheck "Enable instant run"

How to iterate over the file in python

with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
    for line in inf:
        line = line.strip()
        if line:
            try:
                outf.write(str(int(line, 16)))
                outf.write('\n')
            except ValueError:
                print("Could not parse '{0}'".format(line))

python pandas remove duplicate columns

Fast and easy way to drop the duplicated columns by their values:

df = df.T.drop_duplicates().T

More info: Pandas DataFrame drop_duplicates manual .

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

With thymeleaf you may add:

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

Are arrays passed by value or passed by reference in Java?

Everything in Java is passed by value .

In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .

Take a look at this interesting article for further information ...

SQL how to make null values come last when sorting ascending

order by coalesce(date-time-field,large date in future)

Is it possible to style a mouseover on an image map using CSS?

You could use Canvas

in HTML, simply add a canva

<canvas id="locations" width="400" height="300" style="border:1px solid #d3d3d3;">
Your browser can't read canvas</canvas>

And in Javascript (only an example, that will draw a rectangle on the picture)

var c = document.getElementById("locations");
var ctx = c.getContext("2d");
var img = new Image(); 
img.src = '{main_photo}';
img.onload = function() {    // after the pic is loaded
    ctx.drawImage(this,0,0); // add the picture
    ctx.beginPath();         // start the rectangle
    ctx.moveTo(50,50);
    ctx.lineTo(200,50);
    ctx.lineTo(200,200);
    ctx.lineTo(50,200);
    ctx.lineTo(50,50);

    ctx.strokeStyle = "sienna"; // set color
    ctx.stroke();               // apply color
    ctx.lineWidth = 5;
    // ctx.closePath();
};

Just disable scroll not hide it?

You can hide the body's scrollbar with overflow: hidden and set a margin at the same time so that the content doesn't jump:

let marginRightPx = 0;
if(window.getComputedStyle) {
    let bodyStyle = window.getComputedStyle(document.body);
    if(bodyStyle) {
        marginRightPx = parseInt(bodyStyle.marginRight, 10);
    }
}

let scrollbarWidthPx = window.innerWidth - document.body.clientWidth;
Object.assign(document.body.style, {
    overflow: 'hidden',
    marginRight: `${marginRightPx + scrollbarWidthPx}px`
});

And then you can add a disabled scrollbar to the page to fill in the gap:

_x000D_
_x000D_
textarea {_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  width: 11px;_x000D_
  outline: none;_x000D_
  resize: none;_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  border: 0;_x000D_
}
_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

I did exactly this for my own lightbox implementation. Seems to be working well so far.

Add class to <html> with Javascript?

document.documentElement.classList.add('myCssClass');

classList is supported since ie10: https://caniuse.com/#search=classlist

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

how to delete all cookies of my website in php

You should be aware of various tracking tools like Google Analytics also use cookies on your domain and you don't want to delete them, if you want to have correct data in GA.

The only solution I could get working was to set the existing cookies to null. I couldn't delete the cookies from the client.

So for logging a user out I use the following:

setcookie("username", null, time()+$this->seconds, "/", $this->domain, 0);
setcookie("password", null, time()+$this->seconds, "/", $this->domain, 0);

Of course this doesn't delete ALL cookies.

How to validate phone number in laravel 5.2?

You can try out this phone validator package. Laravel Phone

Update

I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

Adding additional data to select options using jQuery

To store another value in select options:

$("#select").append('<option value="4">another</option>')

Python strptime() and timezones?

Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)

See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

Is the ternary operator faster than an "if" condition in Java

Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null is supplied for a parameter value.

For example:

public void myMethod(int par1, String optionalPar2) {

    String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
            .trim()
            .toUpperCase(getDefaultLocale());
}

In the above example, passing null as the String parameter value gets you a default string value instead of a NullPointerException. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.

Moreover, this pattern enables you to make the String parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:

public void myMethod(int par1) {
    return myMethod(par1, null);
}

How to find which version of TensorFlow is installed in my system?

On Latest TensorFlow release 1.14.0

tf.VERSION

is deprecated, instead of this use

tf.version.VERSION

ERROR:

WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

Links in <select> dropdown options

This is an old question, I know but for 2019 peeps:

Like above if you just want to change the URL you can do this:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

But if you want it to act like an a tag and so you can do "./page", "#bottom" or "?a=567" use window.location.replace()

<select onChange="window.location.redirect(this.value)">
    <option value="..">back</option>
    <option value="./list">list</option>
    <option value="#bottom">bottom</option>
</select>

When to encode space to plus (+) or %20?

http://www.example.com/some/path/to/resource?param1=value1

The part before the question mark must use % encoding (so %20 for space), after the question mark you can use either %20 or + for a space. If you need an actual + after the question mark use %2B.

How to make an Asynchronous Method return a value?

Probably the simplest way to do it is to create a delegate and then BeginInvoke, followed by a wait at some time in the future, and an EndInvoke.

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

public SomeMethod()
{
    var fooCaller = new Func<bool>(Foo);
    // Call the method asynchronously
    var asyncResult = fooCaller.BeginInvoke(null, null);

    // Potentially do other work while the asynchronous method is executing.

    // Finally, wait for result
    asyncResult.AsyncWaitHandle.WaitOne();
    bool fooResult = fooCaller.EndInvoke(asyncResult);

    Console.WriteLine("Foo returned {0}", fooResult);
}

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

What is causing "Unable to allocate memory for pool" in PHP?

Looking at the internets there can be various of causes. In my case leaving everything default except...

apc.shm_size = 64M

...cleared the countless warnings that I was getting earlier.

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

CSS fill remaining width

You can realize this layout using CSS table-cells.

Modify your HTML slightly as follows:

<div id="header">
    <div class="container">
        <div class="logoBar">
            <img src="http://placehold.it/50x40" />
        </div>
        <div id="searchBar">
            <input type="text" />
        </div>
        <div class="button orange" id="myAccount">My Account</div>
        <div class="button red" id="basket">Basket (2)</div>
    </div>
</div>

Just remove the wrapper element around the two .button elements.

Apply the following CSS:

#header {
    background-color: #323C3E;
    width:100%;
}
.container {
    display: table;
    width: 100%;
}
.logoBar, #searchBar, .button {
    display: table-cell;
    vertical-align: middle;
    width: auto;
}
.logoBar img {
    display: block;
}
#searchBar {
    background-color: #FFF2BC;
    width: 90%;
    padding: 0 50px 0 10px;
}

#searchBar input {
    width: 100%;
}

.button {
    white-space: nowrap;
    padding:22px;
}

Apply display: table to .container and give it 100% width.

For .logoBar, #searchBar, .button, apply display: table-cell.

For the #searchBar, set the width to 90%, which force all the other elements to compute a shrink-to-fit width and the search bar will expand to fill in the rest of the space.

Use text-align and vertical-align in the table cells as needed.

See demo at: http://jsfiddle.net/audetwebdesign/zWXQt/