Programs & Examples On #Digital downloads

Remove object from a list of objects in python

You can remove a string from an array like this:

array = ["Bob", "Same"]
array.remove("Bob")

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

How to request a random row in SQL?

Solutions like Jeremies:

SELECT * FROM table ORDER BY RAND() LIMIT 1

work, but they need a sequential scan of all the table (because the random value associated with each row needs to be calculated - so that the smallest one can be determined), which can be quite slow for even medium sized tables. My recommendation would be to use some kind of indexed numeric column (many tables have these as their primary keys), and then write something like:

SELECT * FROM table WHERE num_value >= RAND() * 
    ( SELECT MAX (num_value ) FROM table ) 
ORDER BY num_value LIMIT 1

This works in logarithmic time, regardless of the table size, if num_value is indexed. One caveat: this assumes that num_value is equally distributed in the range 0..MAX(num_value). If your dataset strongly deviates from this assumption, you will get skewed results (some rows will appear more often than others).

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

to run mysqld as root user from command line you need to add the switch/options --user=root

mariadb run as system root user

Multiple inputs with same name through POST in php

Change the names of your inputs:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

Then:

$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

CSS div element - how to show horizontal scroll bars only?

CSS3 has the overflow-x property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll policy and work your widths and heights not to mess them up.

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

    function updateURL(url_params) {
        if (history.pushState) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
        window.history.replaceState({path:newurl},'',newurl);
        }
    }

    function setActiveTab(tab) {
        $('.nav-tabs li').removeClass('active');
        $('.tab-content .tab-pane').removeClass('active');

        $('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
        $('#tab-' + tab).addClass('active');
    }

    // Set active tab
    $url_params = new URLSearchParams(window.location.search);


    // Get active tab and remember it
    $('a[data-toggle="tab"]')
        .on('click', function() {
        $href = $(this).attr('href')
        $active_tab = $href.replace('#tab-', '');

        $url_params.set('tab', $active_tab);
        updateURL($url_params.toString());
    });

    if ($url_params.has('tab')) {
        $tab = $url_params.get('tab');
        $tab = '#tab-' + $tab;
        $myTab = JSON.stringify($tab);
        $thisTab = $('.nav-tabs a[href=' + $myTab  +']');
        $('.nav-tabs a[href=' + $myTab  +']').tab('show');
    }

Oracle: how to INSERT if a row doesn't exist

CTE and only CTE :-)

just throw out extra stuff. Here is almost complete and verbose form for all cases of life. And you can use any concise form.

INSERT INTO reports r
  (r.id, r.name, r.key, r.param)

--

  -- Invoke this script from "WITH" to the end (";")
  -- to debug and see prepared values.
  WITH

  -- Some new data to add.
  newData AS(
          SELECT 'Name 1' name, 'key_new_1' key FROM DUAL
    UNION SELECT 'Name 2' NAME, 'key_new_2' key FROM DUAL
    UNION SELECT 'Name 3' NAME, 'key_new_3' key FROM DUAL
    ),
  -- Any single row for copying with each new row from "newData",
  -- if you will of course.
  copyData AS(
      SELECT r.*
      FROM reports r
      WHERE r.key = 'key_existing'
        -- ! Prevent more than one row to return.
        AND FALSE -- do something here for than!
    ),
  -- Last used ID from the "reports" table (it depends on your case).
  -- (not going to work with concurrent transactions)
  maxId AS (SELECT MAX(id) AS id FROM reports),

--

  -- Some construction of all data for insertion.
  SELECT maxId.id + ROWNUM, newData.name, newData.key, copyData.param
  FROM copyData
    -- matrix multiplication :)
    -- (or a recursion if you're imperative coder)
    CROSS JOIN newData
    CROSS JOIN maxId

--

  -- Let's prevent re-insertion.
  WHERE NOT EXISTS (
      SELECT 1 FROM reports rs
      WHERE rs.name IN(
        SELECT name FROM newData
      ));

I call it "IF NOT EXISTS" on steroids. So, this helps me and I mostly do so.

Access a global variable in a PHP function

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';

function menugen() {
    global $data; // <-- Add this line

    echo "[" . $data . "]";
}

menugen();

Otherwise you can access it as $GLOBALS['data']. See Variable scope.

Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.

How to extract the hostname portion of a URL in JavaScript

I know this is a bit late, but I made a clean little function with a little ES6 syntax

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

It could also be writen in ES5 like

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Hiding button using jQuery

It depends on the jQuery selector that you use. Since id should be unique within the DOM, the first one would be simple:

$('#Comanda').hide();

The second one might require something more, depending on the other elements and how to uniquely identify it. If the name of that particular input is unique, then this would work:

$('input[name="Vizualizeaza"]').hide();

what is the most efficient way of counting occurrences in pandas?

Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False (default is True)

An example:

>>> df['Embarked'].value_counts(dropna=False)
S      644
C      168
Q       77
NaN      2

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

Can I fade in a background image (CSS: background-image) with jQuery?

It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.

Update multiple rows with different values in a single SQL query

There's a couple of ways to accomplish this decently efficiently.

First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                               (id2, newsPosX2, newPosY2),
                               ......................... ,
                               (idN, newsPosXN, newPosYN))

UPDATE TableToUpdate SET posX = (SELECT px
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id),
                         posY = (SELECT py
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id)


WHERE id IN (SELECT id
             FROM Tmp)

(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

Google Maps API warning: NoApiKeys

A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.

But in the documentation you may read now : "All JavaScript API applications require authentication."

I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).

You better use a key when you want to be sure that your application will still work in 1 or 2 years.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

How to explicitly obtain post data in Spring MVC?

If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
 //do stuff with valueOne variable here
}

What's a "static method" in C#?

The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.

It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.

For a good explanation of how, when and where see MSDN

MVC Razor Hidden input and passing values

If you are using Razor, you cannot access the field directly, but you can manage its value.

The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.

Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.

Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.

The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.

The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.

Model

public class MyClassModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string MyPropertyForHidden { get; set; }
}

This is the controller aciton

public ActionResult MyPageView()
{
    MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
    // IList model = new List<MyClassModel>(); // or List, strongly-typed
    // ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag

    return View(model);
}

The view is below

//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    // Renders hidden field for your model property (strongly-typed)
    // The field rendered to server your model property (Address, Phone, etc.)
    Html.HiddenFor(model => Model.MyPropertyForHidden); 

    // For list you may use foreach on Model
    // foreach(var item in Model) or foreach(MyClassModel item in Model)
}

// ... Some Other Code ...

The view with ViewBag:

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    Html.Hidden(
        "HiddenName",
        ViewBag.MyHiddenInputValue,
        new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
    );
}

// ... Some Other Code ...

We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue"> also.

The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.

When is the init() function run?

Here is another example - https://play.golang.org/p/9P-LmSkUMKY

package main

import (
    "fmt"
)

func callOut() int {
    fmt.Println("Outside is beinge executed")
    return 1
}

var test = callOut()

func init() {
    fmt.Println("Init3 is being executed")
}

func init() {
    fmt.Println("Init is being executed")
}

func init() {
    fmt.Println("Init2 is being executed")
}

func main() {
    fmt.Println("Do your thing !")
}

Output of the above program

$ go run init/init.go
Outside is being executed
Init3 is being executed
Init is being executed
Init2 is being executed
Do your thing !

Error type 3 Error: Activity class {} does not exist

This happened to me using react-native run-android because my package name did not match my app ID. Just add --appId YOUR_APP_ID.

NuGet: 'X' already has a dependency defined for 'Y'

I was getting the issue 'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp' on the TeamCity build server. I changed the "Update Mode" of the Nuget Installer build step from solution file to packages.config and NuGet.exe to the latest version (I had 3.5.0) and it worked !!

Go to first line in a file in vim?

If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

position fixed is not working

This might be an old topic but in my case it was the layout value of css contain property of the parent element that was causing the issue. I am using a framework for hybrid mobile that use this contain property in most of their component.

For example:

.parentEl {
    contain: size style layout;
}
.parentEl .childEl {
    position: fixed;
    top: 0;
    left: 0;
}

Just remove the layout value of contain property and the fixed content should work!

.parentEl {
    contain: size style;
}

Invalid column name sql error

You should never write code that concatenates SQL and parameters as string - this opens up your code to SQL injection which is a really serious security problem.

Use bind params - for a nice howto see here...

How to Set OnClick attribute with value containing function in ie8?

You also can use:

element.addEventListener("click", function(){
    // call execute function here...
}, false);

How to define a preprocessor symbol in Xcode

For Xcode 9.4.1 and C++ project. Adding const char* Preprocessor Macros to both Debug and Release builds.

  1. Select your project

    select project

  2. Select Build Settings

    select build settings

  3. Search "Preprocessor Macros"

    search1 search2

  4. Open interactive list

    open interactive list

  5. Add your macros and don't forget to escape quotation

    add path

  6. Use in source code as common const char*

    ...
    #ifndef JSON_DEFINITIONS_FILE_PATH
    static constexpr auto JSON_DEFINITIONS_FILE_PATH = "definitions.json";
    #endif
    ...
    FILE *pFileIn = fopen(JSON_DEFINITIONS_FILE_PATH, "r");
    ...
    

Open images? Python

Open any file

import os
os.startfile(<filepath>)

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Where to put default parameter value in C++?

You may do in either (according to standard), but remember, if your code is seeing the declaration without default argument(s) before the definition that contains default argument, then compilation error can come.

For example, if you include header containing function declaration without default argument list, thus compiler will look for that prototype as it is unaware of your default argument values and hence prototype won't match.

If you are putting function with default argument in definition, then include that file but I won't suggest that.

Cron job every three days

0 0 * * * [ $(($((date +%-j- 1)) % 3)) == 0 ] && script

Get the day of the year from date, offset by 1 to start at 0, check if it is modulo three.

How to display Oracle schema size with SQL query?

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
    FROM DBA_SEGMENTS DS
    WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
    GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;

How do I remove repeated elements from ArrayList?

Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

Then, if you need to get back a List reference, you can use again the conversion constructor.

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

an htop-like tool to display disk activity in linux

nmon shows a nice display of disk activity per device. It is available for linux.

? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second???????????????????????????????????????????????????????????????
?DiskName Busy  Read WriteKB|0          |25         |50          |75       100|                                                      ?
?sda        0%    0.0  127.9|>                                                |                                                      ?
?sda1       1%    0.0  127.9|>                                                |                                                      ?
?sda2       0%    0.0    0.0|>                                                |                                                      ?
?sda5       0%    0.0    0.0|>                                                |                                                      ?
?sdb       61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdb1      61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdc       52%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdc1      53%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdd       56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sdd1      56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sde       57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sde1      57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sdf       53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?sdf1      53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?md0        0% 1726.0 2093.6|>disk busy not available                         |                                                      ?
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Remove credentials from Git

Using latest version of git for Windows on Windows 10 Professional and I had a similar issue whereby I have two different GitHub accounts and also a Bitbucket account so things got a bit confusing for VS2017, git extensions and git bash.

I first checked how git was handling my credentials with this command (run git bash with elevated commands or you get errors):

git config --list

I found the entry Credential Manager so I clicked on the START button > typed Credential Manager to and left-clicked on the credential manager yellow safe icon which launched the app. I then clicked on the Windows Credentials tabs and found the entry for my current git account which happened to be Bit-bucket so I deleted this account.

But this didn't do the trick so the next step was to unset the credentials and I did this from the repository directory on my laptop that contains the GitHub project I am trying to push to the remote. I typed the following command:

git config --system --unset credential.helper

Then I did a git push and I was prompted for a GitHub username which I entered (the correct one I needed) and then the associated password and everything got pushed correctly.

I am not sure how much of an issue this is going forward most people probably work off the one repository but I have to work across several and using different providers so may encounter this issue again.

Insert array into MySQL database with PHP

<?php
 function mysqli_insert_array($table, $data, $exclude = array()) {
    $con=  mysqli_connect("localhost", "root","","test");
     $fields = $values = array();
    if( !is_array($exclude) ) $exclude = array($exclude);
    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }
    $fields = implode(",", $fields);
    $values = implode(",", $values);
    if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysqli_insert_id($con),
                      "mysql_affected_rows" => mysqli_affected_rows($con),
                      "mysql_info" => mysqli_info($con)
                    );
    } else {
        return array( "mysql_error" => mysqli_error($con) );
    }
}

 $a['firstname']="abc";
 $a['last name']="xyz";
 $a['birthdate']="1993-09-12";
 $a['profilepic']="img.jpg";
 $a['gender']="male";
 $a['email']="[email protected]";
 $a['likechoclate']="Dm";
 $a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
    echo "Query Failed: " . $result['mysql_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}
?>

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I didn't have an issue with this until I tried to use the Location Services, at which point I had to put the apply plugin: 'com.google.gms.google-services' at the bottom of the file, rather than the top. The reason being that when you have it at the top there are collision issues, and by placing it at the bottom, you avoid those issue.

javax.servlet.ServletException cannot be resolved to a type in spring web app

Add the server(tomcat) from Right click on the Project and select the "Properties" go to "Project Factes" "Runtime tab" other wise "Target Runtime"

if it is maven pom.xml issue, try added this to the pom.xml

 <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
    <scope>provided</scope>
</dependency>

it will solve the issue.

How to check if input date is equal to today's date?

Try using moment.js

moment('dd/mm/yyyy').isSame(Date.now(), 'day');

You can replace 'day' string with 'year, month, minute' if you want.

IE8 support for CSS Media Query

css3-mediaqueries-js is probably what you are looking for: this script emulates media queries. However (from the script's site) it "doesn't work on @imported stylesheets (which you shouldn't use anyway for performance reasons). Also won't listen to the media attribute of the <link> and <style> elements".

In the same vein you have the simpler Respond.js, which enables only min-width and max-width media queries.

How to suppress Pandas Future warning ?

Found this on github...

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

import pandas

MVC 4 Razor adding input type date

If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.

@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script>

    $(document).ready(function(){

      $('.datepicker').datepicker();

     });

</script>

}

When to use Task.Delay, when to use Thread.Sleep?

Use Thread.Sleep when you want to block the current thread.

Use Task.Delay when you want a logical delay without blocking the current thread.

Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

Finding square root without using sqrt function?

Remove your nCount altogether (as there are some roots that this algorithm will take many iterations for).

double SqrtNumber(double num)
{
    double lower_bound=0; 
    double upper_bound=num;
    double temp=0;

    while(fabs(num - (temp * temp)) > SOME_SMALL_VALUE)
    {
           temp = (lower_bound+upper_bound)/2;
           if (temp*temp >= num)
           {
                   upper_bound = temp;
           }
           else
           {
                   lower_bound = temp;
           }
    }
    return temp;
 }

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

XML Serialize generic list of serializable objects

The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray attribute to it.

[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();

XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());

serializableList.Add(PersonList);

using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xmlSerializer.Serialize(streamWriter, serializableList);
}

The serializer will pick up on it being an array and serialize the list's items as child nodes.

How do you rename a MongoDB database?

No there isn't. See https://jira.mongodb.org/browse/SERVER-701

Unfortunately, this is not an simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:

  • the .ns file
  • every single numbered file for the collection
  • the namespace for every index
  • internal unique names of each collection and index
  • contents of system.namespaces and system.indexes (or their equivalents in the future)
  • other locations I may be missing

This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it's a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.

There would be absolutely no way to do this on a live system.

To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point it would be as slow as the current "copydb" command...

Get JSON data from external URL and display it in a div as plain text

If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

And you would call it like this:

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
  }
});

Convert XmlDocument to String

you can use xmlDoc.InnerXml property to get xml in string

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

Passing data to a jQuery UI Dialog

In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.

I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).

Copy file from source directory to binary directory using CMake

You may consider using configure_file with the COPYONLY option:

configure_file(<input> <output> COPYONLY)

Unlike file(COPY ...) it creates a file-level dependency between input and output, that is:

If the input file is modified the build system will re-run CMake to re-configure the file and generate the build system again.

WHERE vs HAVING

WHERE filters before data is grouped, and HAVING filters after data is grouped. This is an important distinction; rows that are eliminated by a WHERE clause will not be included in the group. This could change the calculated values which, in turn(=as a result) could affect which groups are filtered based on the use of those values in the HAVING clause.

And continues,

HAVING is so similar to WHERE that most DBMSs treat them as the same thing if no GROUP BY is specified. Nevertheless, you should make that distinction yourself. Use HAVING only in conjunction with GROUP BY clauses. Use WHERE for standard row-level filtering.

Excerpt From: Forta, Ben. “Sams Teach Yourself SQL in 10 Minutes (5th Edition) (Sams Teach Yourself...).”.

Is it possible to get all arguments of a function as single object inside that function?

Similar answer to Gunnar, with more complete example: You can even transparently return the whole thing:

function dumpArguments(...args) {
  for (var i = 0; i < args.length; i++)
    console.log(args[i]);
  return args;
}

dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });

Output:

foo
bar
true
42
["yes","no"]
{"banana":true}

https://codepen.io/fnocke/pen/mmoxOr?editors=0010

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

How to convert a Binary String to a base 10 integer in Java

This might work:

public int binaryToInteger(String binary) {
    char[] numbers = binary.toCharArray();
    int result = 0;
    for(int i=numbers.length - 1; i>=0; i--)
        if(numbers[i]=='1')
            result += Math.pow(2, (numbers.length-i - 1));
    return result;
}

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

What is the meaning of <> in mysql query?

In MySQL, <> means Not Equal To, just like !=.

mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Here are my 2 cents = 5 methods ;)

I like encapsulate these details and have AppCode tell me how to finish my sentences.

void dispatch_after_delay(float delayInSeconds, dispatch_queue_t queue, dispatch_block_t block) {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, queue, block);
}

void dispatch_after_delay_on_main_queue(float delayInSeconds, dispatch_block_t block) {
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_after_delay(delayInSeconds, queue, block);
}

void dispatch_async_on_high_priority_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

void dispatch_async_on_background_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
}

void dispatch_async_on_main_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_main_queue(), block);
}

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

Trim a string in C

Not the best way but it works

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

WCF Service, the type provided as the service attribute values…could not be found

Change the following line in your Eval.svc file from:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.Eval" %> 

to:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.EvalService" %>

Regex number between 1 and 100

Try it, This will work more efficiently.. 1. For number ranging 00 - 99.99 (decimal inclusive)

^([0-9]{1,2}){1}(\.[0-9]{1,2})?$ 

Working fiddle link

https://regex101.com/r/d1Kdw5/1/

2.For number ranging 1-100(inclusive) with no preceding 0.

(?:\b|-)([1-9]{1,2}[0]?|100)\b

Working Fiddle link

http://regex101.com/r/mN1iT5/6

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.

RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.

FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.

Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.

Convert a string to an enum in C#

Use Enum.TryParse<T>(String, T) (= .NET 4.0):

StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);

It can be simplified even further with C# 7.0's parameter type inlining:

Enum.TryParse("Active", out StatusEnum myStatus);

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I encountered the same bug and found the root reason is:

Use Application Context to inflate view.

Inflating with Activity Context fixed the bug.

How do I pass parameters to a jar file at the time of execution?

java [ options ] -jar file.jar [ argument ... ]

if you need to pass the log4j properties file use the below option

-Dlog4j.configurationFile=directory/file.xml


java -Dlog4j.configurationFile=directory/file.xml -jar <JAR FILE> [arguments ...]

rand() returns the same number each time the program is run

You need to change the seed.

int main() {

    srand(time(NULL));
    cout << (rand() % 101);
    return 0;
}

the srand seeding thing is true also for a c language code.


See also: http://xkcd.com/221/

Why not use Double or Float to represent currency?

Most answers have highlighted the reasons why one should not use doubles for money and currency calculations. And I totally agree with them.

It doesn't mean though that doubles can never be used for that purpose.

I have worked on a number of projects with very low gc requirements, and having BigDecimal objects was a big contributor to that overhead.

It's the lack of understanding about double representation and lack of experience in handling the accuracy and precision that brings about this wise suggestion.

You can make it work if you are able to handle the precision and accuracy requirements of your project, which has to be done based on what range of double values is one dealing with.

You can refer to guava's FuzzyCompare method to get more idea. The parameter tolerance is the key. We dealt with this problem for a securities trading application and we did an exhaustive research on what tolerances to use for different numerical values in different ranges.

Also, there might be situations when you're tempted to use Double wrappers as a map key with hash map being the implementation. It is very risky because Double.equals and hash code for example values "0.5" & "0.6 - 0.1" will cause a big mess.

START_STICKY and START_NOT_STICKY

KISS answer

Difference:

START_STICKY

the system will try to re-create your service after it is killed

START_NOT_STICKY

the system will not try to re-create your service after it is killed


Standard example:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

Create a button with rounded border

FlatButton(
          onPressed: null,
          child: Text('Button', style: TextStyle(
              color: Colors.blue
            )
          ),
          textColor: MyColor.white,
          shape: RoundedRectangleBorder(side: BorderSide(
            color: Colors.blue,
            width: 1,
            style: BorderStyle.solid
          ), borderRadius: BorderRadius.circular(50)),
        )

How to add 20 minutes to a current date?

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

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

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Simulate a button click in Jest

#1 Using Jest

This is how I use the Jest mock callback function to test the click event:

import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';

describe('Test Button component', () => {
  it('Test click event', () => {
    const mockCallBack = jest.fn();

    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
    button.find('button').simulate('click');
    expect(mockCallBack.mock.calls.length).toEqual(1);
  });
});

I am also using a module called enzyme. Enzyme is a testing utility that makes it easier to assert and select your React Components

#2 Using Sinon

Also, you can use another module called Sinon which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:

import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';

import Button from './Button';

describe('Test Button component', () => {
  it('simulates click events', () => {
    const mockCallBack = sinon.spy();
    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

    button.find('button').simulate('click');
    expect(mockCallBack).toHaveProperty('callCount', 1);
  });
});

#3 Using Your own Spy

Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that).

function MySpy() {
  this.calls = 0;
}

MySpy.prototype.fn = function () {
  return () => this.calls++;
}

it('Test Button component', () => {
  const mySpy = new MySpy();
  const mockCallBack = mySpy.fn();

  const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

  button.find('button').simulate('click');
  expect(mySpy.calls).toEqual(1);
});

How to fill in proxy information in cntlm config file?

Once you generated the file, and changed your password, you can run as below,

cntlm -H

Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following

cntlm -v

What are the applications of binary trees?

They can be used as a quick way to sort data. Insert data into a binary search tree at O(log(n)). Then traverse the tree in order to sort them.

C++ alignment when printing cout <<

The setw manipulator function will be of help here.

What is Scala's yield?

Yield is similar to for loop which has a buffer that we cannot see and for each increment, it keeps adding next item to the buffer. When the for loop finishes running, it would return the collection of all the yielded values. Yield can be used as simple arithmetic operators or even in combination with arrays. Here are two simple examples for your better understanding

scala>for (i <- 1 to 5) yield i * 3

res: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12, 15)

scala> val nums = Seq(1,2,3)
nums: Seq[Int] = List(1, 2, 3)

scala> val letters = Seq('a', 'b', 'c')
letters: Seq[Char] = List(a, b, c)

scala> val res = for {
     |     n <- nums
     |     c <- letters
     | } yield (n, c)

res: Seq[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))

Hope this helps!!

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

internal/modules/cjs/loader.js:582 throw err

What helped me was to place the .js file that I was working with in a new folder, drag and drop that folder into VS Code (to open the directory directly in VS Code), open the terminal in VS Code, and then simply type node <filename>.js (or in my case node index.js).

I had already installed node on my system, but for whatever reason, I was still getting the error that you've mentioned, even when I typed the direct path to the file i.e. node /desktop/index.js.

So, creating a new folder on my desktop, placing the .js file inside that folder, opening that folder within VS Code, and then typing node index.js in the terminal solved my issue.

How do I use HTML as the view engine in Express?

The answers at the other link will work, but to serve out HTML, there is no need to use a view engine at all, unless you want to set up funky routing. Instead, just use the static middleware:

app.use(express.static(__dirname + '/public'));

How to read .pem file to get private and public key

I think in your private key definition, You should replace:

X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);

with:

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);

Look your openssl command:

$openssl **pkcs8** -topk8 -inform PEM -outform PEM -in mykey.pem \ -out private_key.pem -nocrypt

And the java Exception:

Only PCKS8 codification 

How do you do relative time in Rails?

Since the most answer here suggests time_ago_in_words.

Instead of using :

<%= time_ago_in_words(comment.created_at) %>

In Rails, prefer:

<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
  <%= comment.created_at.to_s %>
</abbr>

along with a jQuery library http://timeago.yarp.com/, with code:

$("abbr.timeago").timeago();

Main advantage: caching

http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/

jQuery + client-side template = "Syntax error, unrecognized expression"

EugeneXa mentioned it in a comment, but it deserves to be an answer:

var template = $("#modal_template").html().trim();

This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

var markup = Mustache.render(template, data);
$(markup).appendTo(container);

Redirect Windows cmd stdout and stderr to a single file

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

I ran into this same issue but found out that there is a JSON encoder that can be used to move these objects between processes.

from pyVmomi.VmomiSupport import VmomiJSONEncoder

Use this to create your list:

jsonSerialized = json.dumps(pfVmomiObj, cls=VmomiJSONEncoder)

Then in the mapped function, use this to recover the object:

pfVmomiObj = json.loads(jsonSerialized)

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

I might suggest 2 things.

1) If your query takes a lot of time because it´s using several tables that might involve locks, a quite fast solution is to run your queries with the "NoLock" hint.

Simply add Select * from YourTable WITH (NOLOCK) in all your table references an that will prevent your query to block for concurrent transactions.

2) if you want to be sure that all of your queries runs in (let´s say) less than 5 seconds, then you could add what @talha proposed, that worked sweet for me

Just add at the top of your execution

SET LOCK_TIMEOUT 5000;   --5 seconds.

And that will cause that your query takes less than 5 or fail. Then you should catch the exception and rollback if needed.

Hope it helps.

How to access PHP session variables from jQuery function in a .js file?

You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).

What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.

Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.

OR you can generate some JS in your PHP which returns/sets the variable, i.e.:

<? php
echo "<script type='text/javascript'>
    alert('".json_encode($_SESSION['msg'])."');
</script>";
?>

Http Basic Authentication in Java using HttpClient?

HttpBasicAuth works for me with smaller changes

  1. I use maven dependency

    <dependency>
        <groupId>net.iharder</groupId>
        <artifactId>base64</artifactId>
        <version>2.3.8</version>
    </dependency>
    
  2. Smaller change

    String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
    

php $_GET and undefined index

Error reporting will have not included notices on the previous server which is why you haven't seen the errors.

You should be checking whether the index s actually exists in the $_GET array before attempting to use it.

Something like this would be suffice:

if (isset($_GET['s'])) {
    if ($_GET['s'] == 'jwshxnsyllabus')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
    else if ($_GET['s'] == 'aquinas')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
    else if ($_GET['s'] == 'POP2')
        echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
    echo "<body>";
}

It may be beneficial (if you plan on adding more cases) to use a switch statement to make your code more readable.

switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
    case 'jwshxnsyllabus':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
        break;
    case 'aquinas':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
        break;
    case 'POP2':
        echo "<body onload=\"loadSyllabi('POP2')\">";
        break;
    default:
        echo "<body>";
        break;
}

EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s= meant to output no <body> tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>.

How to convert Rows to Columns in Oracle?

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns:

CREATE TABLE doc_tab (
  loan_number VARCHAR2(20),
  document_type VARCHAR2(20),
  document_id VARCHAR2(20)
);

INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');

COMMIT;

SELECT
    loan_number,
    MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
    MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
    MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;

Output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     

You can achieve the same using Oracle PIVOT clause, introduced in 11g:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);

SQLFiddle example with both solutions: SQLFiddle example

Read more about pivoting here: Pivot In Oracle by Tim Hall

What is the difference between HAVING and WHERE in SQL?

From here.

the SQL standard requires that HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions

as opposed to the WHERE clause which is applied to database rows

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I had the same issue installing MySQL docker image then trying to connect from WSL2 MySQL client.

As it was stated in the accepted answer that it should be a firewall issue, in my case this error was caused due to not allowing docker for windows to communicate to private network.

I changed the settings on "Firewall & network protection", "allow an app through firewall", "change settings" (need administrator rights) and allowed "Docker desktop backend" to connect to private network.

jQuery loop over JSON result from AJAX Success?

You can also use the getJSON function:

    $.getJSON('/your/script.php', function(data) {
        $.each(data, function(index) {
            alert(data[index].TEST1);
            alert(data[index].TEST2);
        });
    });

This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.

How to determine if .NET Core is installed

You can see which versions of the .NET Core SDK are currently installed with a terminal. Open a terminal and run the following command.

dotnet --list-sdks

Array of arrays (Python/NumPy)

a=np.array([[1,2,3],[4,5,6]])

a.tolist()

tolist method mentioned above will return the nested Python list

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), cast(fmdate as date), 101) from sery

Without cast I was not getting fmdate converted, so fmdate was a string.

Setting the correct encoding when piping stdout in Python

You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.

Tl;dr of the blog post:

import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))

gives you

utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ? ?

Reading column names alone in a csv file

How about

with open(csv_input_path + file, 'r') as ft:
    header = ft.readline() # read only first line; returns string
    header_list = header.split(',') # returns list

I am assuming your input file is CSV format. If using pandas, it takes more time if the file is big size because it loads the entire data as the dataset.

SyntaxError: Cannot use import statement outside a module

  1. I had the same problem when I started to used babel... But later, I had a solution... I haven't had the problem anymore so far... Currently, Node v12.14.1, "@babel/node": "^7.8.4", I use babel-node and nodemon to execute (node is fine as well..)
  2. package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js" !!note: server.js is my entry file, you can use yours.
  3. launch.json When you debug, you also need to config your launch.json file "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node" !!note: plus runtimeExecutable into the configuration.
  4. Of course, with babel-node, you also normally need and edit another file, such as babel.config.js/.babelrc file

Location for session files in Apache/PHP

The only surefire option to find the current session.save_path value is always to check with phpinfo() in exactly the environment where you want to find out the session storage directory.

Reason: there can be all sorts of things that change session.save_path, either by overriding the php.ini value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.

How can I see the current value of my $PATH variable on OS X?

By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

If you want to see what the path is, simply echo it:

echo $PATH

Create a new Ruby on Rails application using MySQL instead of SQLite

If you are using rails 3 or greater version

rails new your_project_name -d mysql

if you have earlier version

rails new -d mysql your_project_name

So before you create your project you need to find the rails version. that you can find by

rails -v

How do I check if string contains substring?

You can also check if the exact word is contained in a string. E.g.:

function containsWord(haystack, needle) {
    return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}

Usage:

containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false

This is how jQuery does its hasClass method.

How to add a progress bar to a shell script?

Some posts have showed how to display the command's progress. In order to calculate it, you'll need to see how much you've progressed. On BSD systems some commands, such as dd(1), accept a SIGINFO signal, and will report their progress. On Linux systems some commands will respond similarly to SIGUSR1. If this facility is available, you can pipe your input through dd to monitor the number of bytes processed.

Alternatively, you can use lsof to obtain the offset of the file's read pointer, and thereby calculate the progress. I've written a command, named pmonitor, that displays the progress of processing a specified process or file. With it you can do things, such as the following.

$ pmonitor -c gzip
/home/dds/data/mysql-2015-04-01.sql.gz 58.06%

An earlier version of Linux and FreeBSD shell scripts appears on my blog.

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

what is reverse() in Django

Existing answers did a great job at explaining the what of this reverse() function in Django.

However, I'd hoped that my answer shed a different light at the why: why use reverse() in place of other more straightforward, arguably more pythonic approaches in template-view binding, and what are some legitimate reasons for the popularity of this "redirect via reverse() pattern" in Django routing logic.

One key benefit is the reverse construction of a url, as others have mentioned. Just like how you would use {% url "profile" profile.id %} to generate the url from your app's url configuration file: e.g. path('<int:profile.id>/profile', views.profile, name="profile").

But as the OP have noted, the use of reverse() is also commonly combined with the use of HttpResponseRedirect. But why?

I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?

Consider the following views.py:

from django.http import HttpResponseRedirect
from django.urls import reverse

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected = question.choice_set.get(pk=request.POST['choice'])
    except KeyError:
        # handle exception
        pass
    else:
        selected.votes += 1
        selected.save()
        return HttpResponseRedirect(reverse('polls:polls-results',
                                    args=(question.id)
        ))

And our minimal urls.py:

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('<int:question_id>/results/', views.results, name='polls-results'),
    path('<int:question_id>/vote/', views.vote, name='polls-vote')
]

In the vote() function, the code in our else block uses reverse along with HttpResponseRedirect in the following pattern:

HttpResponseRedirect(reverse('polls:polls-results',
                                        args=(question.id)

This first and foremost, means we don't have to hardcode the URL (consistent with the DRY principle) but more crucially, reverse() provides an elegant way to construct URL strings by handling values unpacked from the arguments (args=(question.id) is handled by URLConfig). Supposed question has an attribute id which contains the value 5, the URL constructed from the reverse() would then be:

'/polls/5/results/'

In normal template-view binding code, we use HttpResponse() or render() as they typically involve less abstraction: one view function returning one template:

def index(request):
    return render(request, 'polls/index.html') 

But in many legitimate cases of redirection, we typically care about constructing the URL from a list of parameters. These include cases such as:

  • HTML form submission through POST request
  • User login post-validation
  • Reset password through JSON web tokens

Most of these involve some form of redirection, and a URL constructed through a set of parameters. Hope this adds to the already helpful thread of answers!

how to return index of a sorted list?

you can use numpy.argsort

or you can do:

test =  [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]

zip will rearange the list so that the first element is test and the second is the idxs.

Android AlertDialog Single Button

For code reuse, You can make it in a method like this

public static Dialog getDialog(Context context,String title, String message, DialogType typeButtons ) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title)
        .setMessage(message)
               .setCancelable(false);

        if (typeButtons == DialogType.SINGLE_BUTTON) {
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        //do things
                   }
               });
        }

        AlertDialog alert = builder.create();

        return alert;
    }

    public enum DialogType {
        SINGLE_BUTTON

    }

//Other code reuse issues like using interfaces for providing feedback will also be excellent.

Google Geocoding API - REQUEST_DENIED

For those who are looking this page in 2017 or beyond, like me

Sensor is not required anymore, I tried and got the error:

SensorNotRequired

I just needed to activate my Google Maps Geocoding API, that seems to be necessary nowadays.

Hope it helps someone like me.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Server Client send/receive simple text

CLIENT

namespace SocketKlient

{
    class Program

    {
        static Socket Klient;
        static IPEndPoint endPoint;
        static void Main(string[] args)
        {
            Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string command;
            Console.WriteLine("Write IP address");
            command = Console.ReadLine();
            IPAddress Address;
            while(!IPAddress.TryParse(command, out Address)) 
            {
                Console.WriteLine("wrong IP format");
                command = Console.ReadLine();
            }
            Console.WriteLine("Write port");
            command = Console.ReadLine();

            int port;
            while (!int.TryParse(command, out port) && port > 0)
            {
                Console.WriteLine("Wrong port number");
                command = Console.ReadLine();
            }
            endPoint = new IPEndPoint(Address, port); 
            ConnectC(Address, port);
            while(Klient.Connected)
            {
                Console.ReadLine();
                Odesli();
            }
        }

        public static void ConnectC(IPAddress ip, int port)
        {
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            Console.WriteLine("Connecting...");
            try
            {
                Klient.Connect(endPoint);
                Console.WriteLine("Connected!");
            }
            catch
            {
                Console.WriteLine("Connection fail!");
                return; 
            }
            Task t = new Task(WaitForMessages); 
            t.Start(); 
        }

        public static void SendM()
        {
            string message = "Actualy date is " + DateTime.Now; 
            byte[] buffer = Encoding.UTF8.GetBytes(message);
            Console.WriteLine("Sending: " + message);
            Klient.Send(buffer);
        }

        public static void WaitForMessages()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[64]; 
                    Console.WriteLine("Waiting for answer");
                    Klient.Receive(buffer, 0, buffer.Length, 0); 

                    string message = Encoding.UTF8.GetString(buffer); 
                    Console.WriteLine("Answer: " + message); 
                }
            }
            catch
            {
                Console.WriteLine("Disconnected");
            }
        }
    }
}

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config/> <!-- is used to activate the annotation for beans -->
<context:component-scan base-package="x.y.MyClass" /> <!-- is for the Spring IOC container to look for the beans in the base package. -->

The other important point to note is that context:component-scan implicitly calls the context:annotation-config to activate the annotations on beans. Well if you don't want context:component-scan to implicitly activate annotations for you, you can go on setting the annotation-config element of the context:component-scan to false.

To summarize:

<context:annotation-config/> <!-- activates the annotations --> 
<context:component-scan base-package="x.y.MyClass" /> <!-- activates the annotations + register the beans by looking inside the base-package -->

Error parsing yaml file: mapping values are not allowed here

Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:

someKey: another key: Change to make today: work out more

should be

someKey: another key: "Change to make today: work out more"

Best way to define private methods for a class in Objective-C

If you wanted to avoid the @interface block at the top you could always put the private declarations in another file MyClassPrivate.h not ideal but its not cluttering up the implementation.

MyClass.h

interface MyClass : NSObject {
 @private
  BOOL publicIvar_;
  BOOL privateIvar_;
}

@property (nonatomic, assign) BOOL publicIvar;
//any other public methods. etc
@end

MyClassPrivate.h

@interface MyClass ()

@property (nonatomic, assign) BOOL privateIvar;
//any other private methods etc.
@end

MyClass.m

#import "MyClass.h"
#import "MyClassPrivate.h"
@implementation MyClass

@synthesize privateIvar = privateIvar_;
@synthesize publicIvar = publicIvar_;

@end

Read a text file using Node.js?

Usign fs with node.

var fs = require('fs');

try {  
    var data = fs.readFileSync('file.txt', 'utf8');
    console.log(data.toString());    
} catch(e) {
    console.log('Error:', e.stack);
}

Javascript geocoding from address to latitude and longitude numbers not working

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

You can use a VBScript script wrapped in a BAT file. This code works on a relative PATH.

There isn't any need for any third-party tools or dependencies. Just set SOURCEDIR and OUTPUTZIP.

Filename: ZipUp.bat

echo Set fso = CreateObject("Scripting.FileSystemObject") > _zipup.vbs
echo InputFolder = fso.GetAbsolutePathName(WScript.Arguments.Item(0)) >> _zipup.vbs
echo ZipFile = fso.GetAbsolutePathName(WScript.Arguments.Item(1)) >> _zipup.vbs

' Create empty ZIP file.
echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipup.vbs

echo Set objShell = CreateObject("Shell.Application") >> _zipup.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipup.vbs
echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipup.vbs

echo ' Keep script waiting until compression is done
echo Do Until objShell.NameSpace( ZipFile ).Items.Count = objShell.NameSpace( InputFolder ).Items.Count >> _zipup.vbs
echo     WScript.Sleep 200 >> _zipup.vbs
echo Loop >> _zipup.vbs

CScript  _zipup.vbs  %SOURCEDIR%  %OUTPUTZIP%

del _zipup.vbs

Example usage

SET SOURCEDIR=C:\Some\Path
SET OUTPUTZIP=C:\Archive.zip
CALL ZipUp

Alternatively, you can parametrize this file by replacing the line CScript _zipup.vbs %SOURCEDIR% %OUTPUTZIP% with CScript _zipup.vbs %1 %2, in which case it can be even more easily called from by simply calling CALL ZipUp C:\Source\Dir C:\Archive.zip.

jQuery or JavaScript auto click

$(document).ready(function(){ 
  $('#some-id').trigger('click'); 
});

did the trick.

How to prevent Right Click option using jquery

$(document).ready(function() {

    $(document)[0].oncontextmenu = function() { return false; }

    $(document).mousedown(function(e) {
        if( e.button == 2 ) {
            alert('Sorry, this functionality is disabled!');
            return false;
        } else {
            return true;
        }
    });
});

If you want to disable it only on image click the instead of $(document).mousedown use $("#yourimage").mousedown

How to use XMLReader in PHP?

Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.

I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?

The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {... - which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.

function parseMyXML ($xml) { //pass in an XML string
    $myXML = new XMLReader();
    $myXML->xml($xml);

    while ($myXML->read()) { //start reading.
        if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
            $tag = $myXML->name; //make $tag contain the name of the tag
            switch ($tag) {
                case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
                    $variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
                    break;

                case 'Tag2': //this tag contains child elements, of which we only want one.
                    while($myXML->read()) { //so we tell it to keep reading
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
                            $variable2 = $myXML->readInnerXML(); //...put it in $variable2. 
                            break;
                        }
                    }
                    break;

                case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
                    while($myXML->read()) {
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
                            $variable3 = $myXML->readInnerXML();
                            break;
                        } else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
                            $variable4 = $myXML->readInnerXML();
                            break;
                        }
                    }
                    break;

            }
        }
    }
$myXML->close();
}

How are parameters sent in an HTTP POST request?

First of all, let's differentiate between GET and POST

Get: It is the default HTTP request that is made to the server and is used to retrieve the data from the server and query string that comes after ? in a URI is used to retrieve a unique resource.

this is the format

GET /someweb.asp?data=value HTTP/1.0

here data=value is the query string value passed.

POST: It is used to send data to the server safely so anything that is needed, this is the format of a POST request

POST /somweb.aspHTTP/1.0
Host: localhost
Content-Type: application/x-www-form-urlencoded //you can put any format here
Content-Length: 11 //it depends
Name= somename

Why POST over GET?

In GET the value being sent to the servers are usually appended to the base URL in the query string,now there are 2 consequences of this

  • The GET requests are saved in browser history with the parameters. So your passwords remain un-encrypted in browser history. This was a real issue for Facebook back in the days.
  • Usually servers have a limit on how long a URI can be. If have too many parameters being sent you might receive 414 Error - URI too long

In case of post request your data from the fields are added to the body instead. Length of request params is calculated, and added to the header for content-length and no important data is directly appended to the URL.

You can use the Google Developer Tools' network section to see basic information about how requests are made to the servers.

and you can always add more values in your Request Headers like Cache-Control , Origin , Accept.

How to determine the current iPhone/device model?

I found that a lot all these answers use strings. I decided to change @HAS answer to use an enum:

public enum Devices: String {
    case IPodTouch5
    case IPodTouch6
    case IPhone4
    case IPhone4S
    case IPhone5
    case IPhone5C
    case IPhone5S
    case IPhone6
    case IPhone6Plus
    case IPhone6S
    case IPhone6SPlus
    case IPhone7
    case IPhone7Plus
    case IPhoneSE
    case IPad2
    case IPad3
    case IPad4
    case IPadAir
    case IPadAir2
    case IPadMini
    case IPadMini2
    case IPadMini3
    case IPadMini4
    case IPadPro
    case AppleTV
    case Simulator
    case Other
}

public extension UIDevice {

    public var modelName: Devices {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 , value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        switch identifier {
        case "iPod5,1":                                 return Devices.IPodTouch5
        case "iPod7,1":                                 return Devices.IPodTouch6
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return Devices.IPhone4
        case "iPhone4,1":                               return Devices.IPhone4S
        case "iPhone5,1", "iPhone5,2":                  return Devices.IPhone5
        case "iPhone5,3", "iPhone5,4":                  return Devices.IPhone5C
        case "iPhone6,1", "iPhone6,2":                  return Devices.IPhone5S
        case "iPhone7,2":                               return Devices.IPhone6
        case "iPhone7,1":                               return Devices.IPhone6Plus
        case "iPhone8,1":                               return Devices.IPhone6S
        case "iPhone8,2":                               return Devices.IPhone6SPlus
        case "iPhone9,1", "iPhone9,3":                  return Devices.IPhone7
        case "iPhone9,2", "iPhone9,4":                  return Devices.IPhone7Plus
        case "iPhone8,4":                               return Devices.IPhoneSE
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return Devices.IPad2
        case "iPad3,1", "iPad3,2", "iPad3,3":           return Devices.IPad3
        case "iPad3,4", "iPad3,5", "iPad3,6":           return Devices.IPad4
        case "iPad4,1", "iPad4,2", "iPad4,3":           return Devices.IPadAir
        case "iPad5,3", "iPad5,4":                      return Devices.IPadAir2
        case "iPad2,5", "iPad2,6", "iPad2,7":           return Devices.IPadMini
        case "iPad4,4", "iPad4,5", "iPad4,6":           return Devices.IPadMini2
        case "iPad4,7", "iPad4,8", "iPad4,9":           return Devices.IPadMini3
        case "iPad5,1", "iPad5,2":                      return Devices.IPadMini4
        case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return Devices.IPadPro
        case "AppleTV5,3":                              return Devices.AppleTV
        case "i386", "x86_64":                          return Devices.Simulator
        default:                                        return Devices.Other
        }
    }

}

Passing arguments to AsyncTask, and returning results

You can receive returning results like that: AsyncTask class

@Override
protected Boolean doInBackground(Void... params) {
    if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
        try {
            throw new SQLException("Database credentials missing");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return true;
}

receiving class:

_store.execute();
boolean result =_store.get();

Hoping it will help.

How to detect page zoom level in all modern browsers?

function supportFullCss3()
{
    var div = document.createElement("div");
    div.style.display = 'flex';
    var s1 = div.style.display == 'flex';
    var s2 = 'perspective' in div.style;

    return (s1 && s2);
};

function getZoomLevel()
{
    var screenPixelRatio = 0, zoomLevel = 0;

    if(window.devicePixelRatio && supportFullCss3())
        screenPixelRatio = window.devicePixelRatio;
    else if(window.screenX == '0')
        screenPixelRatio = (window.outerWidth - 8) / window.innerWidth;
    else
    {
        var scr = window.frames.screen;
        screenPixelRatio = scr.deviceXDPI / scr.systemXDPI;
    }

    //---------------------------------------
    if (screenPixelRatio <= .11){ //screenPixelRatio >= .01 &&
      zoomLevel = "-7";
    } else if (screenPixelRatio <= .25) {
      zoomLevel = "-6";
    }else if (screenPixelRatio <= .33) {
      zoomLevel = "-5.5";
    } else if (screenPixelRatio <= .40) {
      zoomLevel = "-5";
    } else if (screenPixelRatio <= .50) {
      zoomLevel = "-4";
    } else if (screenPixelRatio <= .67) {
      zoomLevel = "-3";
    } else if (screenPixelRatio <= .75) {
      zoomLevel = "-2";
    } else if (screenPixelRatio <= .85) {
      zoomLevel = "-1.5";
    } else if (screenPixelRatio <= .98) {
      zoomLevel = "-1";
    } else if (screenPixelRatio <= 1.03) {
      zoomLevel = "0";
    } else if (screenPixelRatio <= 1.12) {
      zoomLevel = "1";
    } else if (screenPixelRatio <= 1.2) {
      zoomLevel = "1.5";
    } else if (screenPixelRatio <= 1.3) {
      zoomLevel = "2";
    } else if (screenPixelRatio <= 1.4) {
      zoomLevel = "2.5";
    } else if (screenPixelRatio <= 1.5) {
      zoomLevel = "3";
    } else if (screenPixelRatio <= 1.6) {
      zoomLevel = "3.3";
    } else if (screenPixelRatio <= 1.7) {
      zoomLevel = "3.7";
    } else if (screenPixelRatio <= 1.8) {
      zoomLevel = "4";
    } else if (screenPixelRatio <= 1.9) {
      zoomLevel = "4.5";
    } else if (screenPixelRatio <= 2) {
      zoomLevel = "5";
    } else if (screenPixelRatio <= 2.1) {
      zoomLevel = "5.2";
    } else if (screenPixelRatio <= 2.2) {
      zoomLevel = "5.4";
    } else if (screenPixelRatio <= 2.3) {
      zoomLevel = "5.6";
    } else if (screenPixelRatio <= 2.4) {
      zoomLevel = "5.8";
    } else if (screenPixelRatio <= 2.5) {
      zoomLevel = "6";
    } else if (screenPixelRatio <= 2.6) {
      zoomLevel = "6.2";
    } else if (screenPixelRatio <= 2.7) {
      zoomLevel = "6.4";
    } else if (screenPixelRatio <= 2.8) {
      zoomLevel = "6.6";
    } else if (screenPixelRatio <= 2.9) {
      zoomLevel = "6.8";
    } else if (screenPixelRatio <= 3) {
      zoomLevel = "7";
    } else if (screenPixelRatio <= 3.1) {
      zoomLevel = "7.1";
    } else if (screenPixelRatio <= 3.2) {
      zoomLevel = "7.2";
    } else if (screenPixelRatio <= 3.3) {
      zoomLevel = "7.3";
    } else if (screenPixelRatio <= 3.4) {
      zoomLevel = "7.4";
    } else if (screenPixelRatio <= 3.5) {
      zoomLevel = "7.5";
    } else if (screenPixelRatio <= 3.6) {
      zoomLevel = "7.6";
    } else if (screenPixelRatio <= 3.7) {
      zoomLevel = "7.7";
    } else if (screenPixelRatio <= 3.8) {
      zoomLevel = "7.8";
    } else if (screenPixelRatio <= 3.9) {
      zoomLevel = "7.9";
    } else if (screenPixelRatio <= 4) {
      zoomLevel = "8";
    } else if (screenPixelRatio <= 4.1) {
      zoomLevel = "8.1";
    } else if (screenPixelRatio <= 4.2) {
      zoomLevel = "8.2";
    } else if (screenPixelRatio <= 4.3) {
      zoomLevel = "8.3";
    } else if (screenPixelRatio <= 4.4) {
      zoomLevel = "8.4";
    } else if (screenPixelRatio <= 4.5) {
      zoomLevel = "8.5";
    } else if (screenPixelRatio <= 4.6) {
      zoomLevel = "8.6";
    } else if (screenPixelRatio <= 4.7) {
      zoomLevel = "8.7";
    } else if (screenPixelRatio <= 4.8) {
      zoomLevel = "8.8";
    } else if (screenPixelRatio <= 4.9) {
      zoomLevel = "8.9";
    } else if (screenPixelRatio <= 5) {
      zoomLevel = "9";
    }else {
      zoomLevel = "unknown";
    }

    return zoomLevel;
};

Is there a MySQL option/feature to track history of changes to records?

Just my 2 cents. I would create a solution which records exactly what changed, very similar to transient's solution.

My ChangesTable would simple be:

DateTime | WhoChanged | TableName | Action | ID |FieldName | OldValue

1) When an entire row is changed in the main table, lots of entries will go into this table, BUT that is very unlikely, so not a big problem (people are usually only changing one thing) 2) OldVaue (and NewValue if you want) have to be some sort of epic "anytype" since it could be any data, there might be a way to do this with RAW types or just using JSON strings to convert in and out.

Minimum data usage, stores everything you need and can be used for all tables at once. I'm researching this myself right now, but this might end up being the way I go.

For Create and Delete, just the row ID, no fields needed. On delete a flag on the main table (active?) would be good.

Creating temporary files in Android

This is what I typically do:

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

How to Convert an int to a String?

Use String.valueOf():

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors

How do I check if a cookie exists?

ATTENTION! the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;

    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    } 

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, ''); 
}

CSS:Defining Styles for input elements inside a div

Like this.

.divContainer input[type="text"] {
  width:150px;
}
.divContainer input[type="radio"] {
  width:20px;
}

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try as follows it works for me

select * from nm_admission where trunc(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');

OR

select * from nm_admission where trunc(entry_timestamp) = '09-SEP-2018';

You can also try using to_char but remember to_char is too expensive

select * from nm_admission where to_char(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');

The TRUNC(17-SEP-2018 08:30:11) will give 17-SEP-2018 00:00:00 as a result, you can compare the only date portion independently and time portion will skip.

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

PHP CURL DELETE request

switch ($method) {
    case "GET":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        break;
    case "POST":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
    case "DELETE":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
        break;
}

python: How do I know what type of exception occurred?

try: someFunction() except Exception, exc:

#this is how you get the type
excType = exc.__class__.__name__

#here we are printing out information about the Exception
print 'exception type', excType
print 'exception msg', str(exc)

#It's easy to reraise an exception with more information added to it
msg = 'there was a problem with someFunction'
raise Exception(msg + 'because of %s: %s' % (excType, exc))

How to install iPhone application in iPhone Simulator

This worked for me on iOS 5.0 simulator.

  1. Run the app on the simulator.

  2. Go to the path where you can see something like this:

    /Users/arshad/Library/Application\ Support/iPhone\ Simulator/5.0/Applications/34BC3FDC-7398-42D4-9114-D5FEFC737512/…
    
  3. Copy all the package contents including the app, lib, temp and Documents.

  4. Clear all the applications installed on the simulator so that it is easier to see what is happening.

  5. Run a pre-existing app you have on your simulator.

  6. Look for the same package content for that application as in step 3 and delete all.

  7. Paste the package contents that you have previously copied.

  8. Close the simulator and start it again. The new app icon of the intended app will replace the old one.

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

How to write a file or data to an S3 object using boto3

boto3 also has a method for uploading a file directly:

s3 = boto3.resource('s3')    
s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')

http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file

How to display an activity indicator with text on iOS 8 with Swift?

For Swift 5

Indicator with label inside WKWebview

var strLabel = UILabel()
   let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    let loadingTextLabel = UILabel()
   
    @IBOutlet var indicator: UIActivityIndicatorView!
    @IBOutlet var webView: WKWebView!
    
    var refController:UIRefreshControl = UIRefreshControl()
    
    
    override func viewDidLoad() {
        webView = WKWebView(frame: CGRect.zero)
        webView.navigationDelegate = self
        webView.uiDelegate = self as? WKUIDelegate
        
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
       
        
        webView.allowsBackForwardNavigationGestures = true
        
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
        setBackground()
        
    }
    

    
    func setBackground() {
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    }
    
    func showActivityIndicator(show: Bool) {
        if show {
            
            
            strLabel = UILabel(frame: CGRect(x: 55, y: 0, width: 400, height: 66))
            strLabel.text = "Please Wait. Checking Internet Connection..."
            strLabel.font = UIFont(name: "Avenir Light", size: 12)
            
           
            strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
           
            effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 300, height: 66)
            effectView.layer.cornerRadius = 15
            effectView.layer.masksToBounds = true
            indicator = UIActivityIndicatorView(style: .white)
            indicator.frame = CGRect(x: 0, y: 0, width: 66, height: 66)
            indicator.startAnimating()
            effectView.contentView.addSubview(indicator)
            effectView.contentView.addSubview(strLabel)
            indicator.transform = CGAffineTransform(scaleX: 1.4, y: 1.4);
            effectView.center = webView.center
            view.addSubview(effectView)
            
            
        } else {
            strLabel.removeFromSuperview()
             effectView.removeFromSuperview()
            indicator.removeFromSuperview()
            indicator.stopAnimating()
        }
    }

Here is my screenshort

QString to char* conversion

Maybe

my_qstring.toStdString().c_str();

or safer, as Federico points out:

std::string str = my_qstring.toStdString();
const char* p = str.c_str();

It's far from optimal, but will do the work.

Facebook Architecture

"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"

I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.

Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.

If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.

Word-wrap in an HTML table

A solution which work with Google Chrome and Firefox (not tested with Internet Explorer) is to set display: table-cell as a block element.

Datatables: Cannot read property 'mData' of undefined

In addition to inconsistent and numbers, a missing item inside datatable scripts columns part can cause this too. Correcting that fixed my datatables search bar.

I'm talking about this part;

"columns": [
  null,
  .
  .
  .
  null
           ],

I struggled with this error till I was pointed that this part had one less "null" than my total thead count.

Loop in Jade (currently known as "Pug") template engine

Using node I have a collection of stuff @stuff and access it like this:

- each stuff in stuffs
  p
    = stuff.sentence

Add Expires headers

The easiest way to add these headers is a .htaccess file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.

Note that some hosting providers will not let you use .htaccess files, so check their terms if it doesn't seem to work.

The HTML5Boilerplate project has an excellent .htaccess file that covers the necessary settings. See the relevant part of the file at their Github repository

These are the important bits

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);
}

You can see an explanation of how it works here.

Scripting Language vs Programming Language

Apart from the difference that Scripting language is Interpreted and Programming language is Compiled, there is another difference as below, which I guess has been missed..

A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control.

Whereas a Programming Language generally is used to code the system from Scratch.

src ECMA

PHPExcel Make first row bold

You can try

$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);

If Python is interpreted, what are .pyc files?

Python (at least the most common implementation of it) follows a pattern of compiling the original source to byte codes, then interpreting the byte codes on a virtual machine. This means (again, the most common implementation) is neither a pure interpreter nor a pure compiler.

The other side of this is, however, that the compilation process is mostly hidden -- the .pyc files are basically treated like a cache; they speed things up, but you normally don't have to be aware of them at all. It automatically invalidates and re-loads them (re-compiles the source code) when necessary based on file time/date stamps.

About the only time I've seen a problem with this was when a compiled bytecode file somehow got a timestamp well into the future, which meant it always looked newer than the source file. Since it looked newer, the source file was never recompiled, so no matter what changes you made, they were ignored...

How to insert the current timestamp into MySQL database using a PHP insert query

This format is used to get current timestamp and stored in mysql

$date = date("Y-m-d H:i:s"); 

$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'"; 

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

it happened for me when I deleted the jdk and installed new one somehow the project kept seeing the old one as invalid but couldn't change, so right click on your module -> Open Module Settings -> and choose Compile Sdk Version.

Which are more performant, CTE or temporary tables?

CTE has its uses - when data in the CTE is small and there is strong readability improvement as with the case in recursive tables. However, its performance is certainly no better than table variables and when one is dealing with very large tables, temporary tables significantly outperform CTE. This is because you cannot define indices on a CTE and when you have large amount of data that requires joining with another table (CTE is simply like a macro). If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables.

Lombok is not generating getter and setter

just adding the dependency of Lombok is not enough. You'll have to install the plugin of Lombok too.

You can get your Lombok jar file in by navigating through (Only if you have added the dependency in any of the POM.)

m2\repository\org\projectlombok\lombok\1.18.12\lombok-1.18.12

Also, if Lombok could not find the IDE, manually specify the .exe of your IDE and click install.

Restart your IDE.

That's it.

If you face any problem,

Below is a beautiful and short video about how to install the plugin of Lombok.

Just to save your time, you can start from 1:40.

https://www.youtube.com/watch?v=5K6NNX-GGDI

If it still doesn't work,

Verify that lombok.jar is there in your sts.ini file (sts config file, present in sts folder.)

-javaagent:lombok.jar

Do an Alt+F5. This will update your maven.

Close your IDE and again start it.

How to change port number for apache in WAMP

In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf and change the port:

[apache]
apachePortUsed = "8080"

Then exit and relaunch wamp.

CardView not showing Shadow in Android L

check hardwareAccelerated in manifest make it true , making it false removes shadows , when false shadow appears in xml preview but not in phone .

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

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

jQuery set radio button

The chosen answer works in this case.

But the question was about finding the element based on radiogroup and dynamic id, and the answer can also leave the displayed radio button unaffected.

This line does selects exactly what was asked for while showing the change on screen as well.

$('input:radio[name=cols][id='+ newcol +']').click();

Failed to load the JNI shared Library (JDK)

You can solve that problem as many other replicated. You need that Eclipse and the JDK be 32-bits or both on 64-bits. The architecture of the OS doesn't matter while the others remains on the same type of arquitecture.

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html

<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
    width:100%;
}
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
    width: 250px;
    height:300px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;
}
</style>
</head>
<body>

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <!-- more boxes here -->
    </div>
</div>
</body>
</html>

How to style UITextview to like Rounded Rect text field?

How about just:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 280, 32)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:textField];

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

Upon being asked what you intend to do with the bytes, you responded:

I'm going to encrypt it. I can encrypt it without converting but I'd still like to know why encoding comes to play here. Just give me the bytes is what I say.

Regardless of whether you intend to send this encrypted data over the network, load it back into memory later, or steam it to another process, you are clearly intending to decrypt it at some point. In that case, the answer is that you're defining a communication protocol. A communication protocol should not be defined in terms of implementation details of your programming language and its associated runtime. There are several reasons for this:

  • You may need to communicate with a process implemented in a different language or runtime. (This might include a server running on another machine or sending the string to a JavaScript browser client, for example.)
  • The program may be re-implemented in a different language or runtime in the future.
  • The .NET implementation might change the internal representation of strings. You may think this sounds farfetched, but this actually happened in Java 9 to reduce memory usage. There's no reason .NET couldn't follow suit. Skeet suggests that UTF-16 probably isn't optimal today give the rise of the emoji and other blocks of Unicode needing more than 2 bytes to represent as well, increasing the likelihood that the internal representation could change in the future.

For communicating (either with a completely disparate process or with the same program in the future), you need to define your protocol strictly to minimize the difficulty of working with it or accidentally creating bugs. Depending on .NET's internal representation is not a strict, clear, or even guaranteed to be consistent definition. A standard encoding is a strict definition that will not fail you in the future.

In other words, you can't satisfy your requirement for consistency without specifying an encoding.

You may certainly choose to use UTF-16 directly if you find that your process performs significantly better since .NET uses it internally or for any other reason, but you need to choose that encoding explicitly and perform those conversions explicitly in your code rather than depending on .NET's internal implementation.

So choose an encoding and use it:

using System.Text;

// ...

Encoding.Unicode.GetBytes("abc"); # UTF-16 little endian
Encoding.UTF8.GetBytes("abc")

As you can see, it's also actually less code to just use the built in encoding objects than to implement your own reader/writer methods.

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

How can I use querySelector on to pick an input element by name?

These examples seem a bit inefficient. Try this if you want to act upon the value:

<input id="cta" type="email" placeholder="Enter Email...">
<button onclick="return joinMailingList()">Join</button>

<script>
    const joinMailingList = () => {
        const email = document.querySelector('#cta').value
        console.log(email)
    }
</script>

You will encounter issue if you use this keyword with fat arrow (=>). If you need to do that, go old school:

<script>
    function joinMailingList() {
        const email = document.querySelector('#cta').value
        console.log(email)
    }
</script>

If you are working with password inputs, you should use type="password" so it will display ****** while the user is typing, and it is also more semantic.

Using OpenGl with C#?

OpenTK is an improvement over the Tao API, as it uses idiomatic C# style with overloading, strongly-typed enums, exceptions, and standard .NET types:

GL.Begin(BeginMode.Points);
GL.Color3(Color.Yellow);
GL.Vertex3(Vector3.Up);

as opposed to Tao which merely mirrors the C API:

Gl.glBegin(Gl.GL_POINTS);   // double "gl" prefix
Gl.glColor3ub(255, 255, 0); // have to pass RGB values as separate args
Gl.glVertex3f(0, 1, 0);     // explicit "f" qualifier

This makes for harder porting but is incredibly nice to use.

As a bonus it provides font rendering, texture loading, input handling, audio, math...

Update 18th January 2016: Today the OpenTK maintainer has stepped away from the project, leaving its future uncertain. The forums are filled with spam. The maintainer recommends moving to MonoGame or SDL2#.

Update 30th June 2020: OpenTK has had new maintainers for a while now and has an active discord community. So the previous recommendation of using another library isn't necessarily true.

ADB Driver and Windows 8.1

There is lots of stuff on this topic, each slightly different. Like many users I spent hours trying them and got nowhere. In the end, this is what worked for me - I.e. installed the driver on windows 8.1

In my extras/google/usb_driver is a file android_winusb.inf

I double clicked on this and it "ran" and installed the driver.

I can't explain why this worked.

How to read pickle file?

I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):

https://pickleviewer.com/

iPad Multitasking support requires these orientations

I am using Xamarin and there is no available option in the UI to specify "Requires full screen". I, therefore, had to follow @Michael Wang's answer with a slight modification. Here goes:

Open the info.plist file in a text editor and add the lines:

<key>UIRequiresFullScreen</key>
<true/>

I tried setting the value to "YES" but it didn't work, which was kind of expected.

In case you are wondering, I placed the above lines below the UISupportedInterfaceOrientations section

<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>

Hope this helps someone. Credit to Michael.

Center Div inside another (100% width) div

The below style to the inner div will center it.

margin: 0 auto;

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form
{


public Form1()
    {
        InitializeComponent();
    }

  private void button1_Click(object sender, EventArgs e)
    {
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);
    }
 }

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between React Native and React?

A little late to the party, but here's a more comprehensive answer with examples:

React

React is a component based UI library that uses a "shadow DOM" to efficiently update the DOM with what has changed instead of rebuilding the entire DOM tree for every change. It was initially built for web apps, but now can be used for mobile & 3D/vr as well.

Components between React and React Native cannot be interchanged because React Native maps to native mobile UI elements but business logic and non-render related code can be re-used.

ReactDOM

Was initially included with the React library but was split out once React was being used for other platforms than just web. It serves as the entry point to the DOM and is used in union with React.

Example:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    state = {
        data: [],
    }

    componentDidMount() {
        const data = API.getData(); // fetch some data
        this.setState({ data })
    }

    clearData = () => {
        this.setState({
            data: [],
        });
    }

    render() {
        return (
            <div>
                {this.state.data.map((data) => (
                    <p key={data.id}>{data.label}</p>
                ))}
                <button onClick={this.clearData}>
                    Clear list
                </button>
            </div>
        );
    }

}

ReactDOM.render(App, document.getElementById('app'));

React Native

React Native is a cross-platform mobile framework that uses React and communicates between Javascript and it's native counterpart via a "bridge". Due to this, a lot of UI structuring has to be different when using React Native. For example: when building a list, you will run into major performance issues if you try to use map to build out the list instead of React Native's FlatList. React Native can be used to build out IOS/Android mobile apps, as well as for smart watches and TV's.

Expo

Expo is the go-to when starting a new React Native app.

Expo is a framework and a platform for universal React applications. It is a set of tools and services built around React Native and native platforms that help you develop, build, deploy, and quickly iterate on iOS, Android, and web apps

Note: When using Expo, you can only use the Native Api's they provide. All additional libraries you include will need to be pure javascript or you will need to eject expo.

Same example using React Native:

import React, { Component } from 'react';
import { Flatlist, View, Text, StyleSheet } from 'react-native';

export default class App extends Component {
    state = {
        data: [],
    }

    componentDidMount() {
        const data = API.getData(); // fetch some data
        this.setState({ data })
    }

    clearData = () => {
        this.setState({
            data: [],
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={({ item }) => <Text key={item.id}>{item.label}</Text>}
                />
                <Button title="Clear list" onPress={this.clearData}></Button>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});

Differences:

  • Notice that everything outside of render can remain the same, this is why business logic/lifecycle logic code can be re-used across React and React Native
  • In React Native all components need to be imported from react-native or another UI library
  • Using certain API's that map to native components are usually going to be more performant than trying to handle everything on the javascript side. ex. mapping components to build a list vs using flatlist
  • Subtle differences: things like onClick turn into onPress, React Native uses stylesheets to define styles in a more performant way, and React Native uses flexbox as the default layout structure to keep things responsive.
  • Since there is no traditional "DOM" in React Native, only pure javascript libraries can be used across both React and React Native

React360

It's also worth mentioning that React can also be used to develop 3D/VR applications. The component structure is very similar to React Native. https://facebook.github.io/react-360/

How to run a single test with Mocha?

Depending on your usage pattern, you might just like to use only. We use the TDD style; it looks like this:

test.only('Date part of valid Partition Key', function (done) {
    //...
}

Only this test will run from all the files/suites.

How do you cast a List of supertypes to a List of subtypes?

casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:

List<? extends TestA> myList = new ArrayList<TestA>();

You still have type checking to do when you are using the objects in the list.

How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

how to get last insert id after insert query in codeigniter active record

A transaction isn't needed here, this should suffice:

function add_post($post_data) {
    $this->db->insert('posts',$post_data);
    return $this->db->insert_id();
}

MongoDB SELECT COUNT GROUP BY

Additionally if you need to restrict the grouping you can use:

db.events.aggregate( 
    {$match: {province: "ON"}},
    {$group: {_id: "$date", number: {$sum: 1}}}  
)

How can I concatenate a string within a loop in JSTL/JSP?

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

How to remove a column from an existing table?

Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.

If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.

Another option is to find all referencing columns and remove them as well if they are not needed any longer.

In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here