Programs & Examples On #Wcf authentication

Most efficient method to groupby on an array of objects

Posting because even though this question is 7 years old, I have yet to see an answer that satisfies the original criteria:

I don’t want them “split up” but “merged”, more like the SQL group by method.

I originally came to this post because I wanted to find a method of reducing an array of objects (i.e., the data structure created when you read from a csv, for example) and aggregate by given indices to produce the same data structure. The return value I was looking for was another array of objects, not a nested object or map like I've seen proposed here.

The following function takes a dataset (array of objects), a list of indices (array), and a reducer function, and returns the result of applying the reducer function on the indices as an array of objects.

function agg(data, indices, reducer) {

  // helper to create unique index as an array
  function getUniqueIndexHash(row, indices) {
    return indices.reduce((acc, curr) => acc + row[curr], "");
  }

  // reduce data to single object, whose values will be each of the new rows
  // structure is an object whose values are arrays
  // [{}] -> {{}}
  // no operation performed, simply grouping
  let groupedObj = data.reduce((acc, curr) => {
    let currIndex = getUniqueIndexHash(curr, indices);

    // if key does not exist, create array with current row
    if (!Object.keys(acc).includes(currIndex)) {
      acc = {...acc, [currIndex]: [curr]}
    // otherwise, extend the array at currIndex
    } else {
      acc = {...acc, [currIndex]: acc[currIndex].concat(curr)};
    }

    return acc;
  }, {})

  // reduce the array into a single object by applying the reducer
  let reduced = Object.values(groupedObj).map(arr => {
    // for each sub-array, reduce into single object using the reducer function
    let reduceValues = arr.reduce(reducer, {});

    // reducer returns simply the aggregates - add in the indices here
    // each of the objects in "arr" has the same indices, so we take the first
    let indexObj = indices.reduce((acc, curr) => {
      acc = {...acc, [curr]: arr[0][curr]};
      return acc;
    }, {});

    reduceValues = {...indexObj, ...reduceValues};


    return reduceValues;
  });


  return reduced;
}

I'll create a reducer that returns count(*) and sum(Value):

reducer = (acc, curr) => {
  acc.count = 1 + (acc.count || 0);
  acc.value = +curr.Value + (acc.value|| 0);
  return acc;
}

finally, applying the agg function with our reducer to the original dataset yields an array of objects with the appropriate aggregations applied:

agg(tasks, ["Phase"], reducer);
// yields:
Array(2) [
  0: Object {Phase: "Phase 1", count: 4, value: 50}
  1: Object {Phase: "Phase 2", count: 4, value: 130}
]

agg(tasks, ["Phase", "Step"], reducer);
// yields:
Array(4) [
  0: Object {Phase: "Phase 1", Step: "Step 1", count: 2, value: 15}
  1: Object {Phase: "Phase 1", Step: "Step 2", count: 2, value: 35}
  2: Object {Phase: "Phase 2", Step: "Step 1", count: 2, value: 55}
  3: Object {Phase: "Phase 2", Step: "Step 2", count: 2, value: 75}
]

Printing result of mysql query from variable

This will print out the query:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());
print $query;

This will print out the results:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($dave)){
    foreach($row as $cname => $cvalue){
        print "$cname: $cvalue\t";
    }
    print "\r\n";
}

Get the date (a day before current time) in Bash

date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
2009:11:9

Interface or an Abstract Class: which one to use?

From a phylosophic point of view :

  • An abstract class represents an "is a" relationship. Lets say I have fruits, well I would have a Fruit abstract class that shares common responsabilities and common behavior.

  • An interface represents a "should do" relationship. An interface, in my opinion (which is the opinion of a junior dev), should be named by an action, or something close to an action, (Sorry, can't find the word, I'm not an english native speaker) lets say IEatable. You know it can be eaten, but you don't know what you eat.

From a coding point of view :

  • If your objects have duplicated code, it is an indication that they have common behavior, which means you might need an abstract class to reuse the code, which you cannot do with an interface.

  • Another difference is that an object can implement as many interfaces as you need, but you can only have one abstract class because of the "diamond problem" (check out here to know why! http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem)

I probably forget some points, but I hope it can clarify things.

PS : The "is a"/"should do" is brought by Vivek Vermani's answer, I didn't mean to steal his answer, just to reuse the terms because I liked them!

Check if an array contains any element of another array in JavaScript

If you're not opposed to using a libray, http://underscorejs.org/ has an intersection method, which can simplify this:

var _ = require('underscore');

var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'mango'];
var fruit3 = [ 'mango', 'lemon', 'pineapple'];
var fruit4 = [ 'orange', 'lemon', 'grapes'];

console.log(_.intersection(target, fruit2)); //returns [apple, orange]
console.log(_.intersection(target, fruit3)); //returns []
console.log(_.intersection(target, fruit4)); //returns [orange]

The intersection function will return a new array with the items that it matched and if not matches it returns empty array.

Difference of keywords 'typename' and 'class' in templates?

For naming template parameters, typename and class are equivalent. §14.1.2:

There is no semantic difference between class and typename in a template-parameter.

typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type. §14.6.2:

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

Example:

typename some_template<T>::some_type

Without typename the compiler can't tell in general whether you are referring to a type or not.

Rails params explained?

The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the url. For example, if a user's browser requested

http://www.example.com/?foo=1&boo=octopus

then params[:foo] would be "1" and params[:boo] would be "octopus".

In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes inside. For example, if the user's browser requested

http://www.example.com/?vote[item_id]=1&vote[user_id]=2

then params[:vote] would be a hash, params[:vote][:item_id] would be "1" and params[:vote][:user_id] would be "2".

The Ruby on Rails params are the equivalent of the $_REQUEST array in PHP.

SQLException : String or binary data would be truncated

Generally it is that you are inserting a value that is greater than the maximum allowed value. Ex, data column can only hold up to 200 characters, but you are inserting 201-character string

Can an int be null in Java?

No. Only object references can be null, not primitives.

Extract subset of key-value pairs from Python dictionary object?

solution

from operator import itemgetter
from typing import List, Dict, Union


def subdict(d: Union[Dict, List], columns: List[str]) -> Union[Dict, List[Dict]]:
    """Return a dict or list of dicts with subset of 
    columns from the d argument.
    """
    getter = itemgetter(*columns)

    if isinstance(d, list):
        result = []
        for subset in map(getter, d):
            record = dict(zip(columns, subset))
            result.append(record)
        return result
    elif isinstance(d, dict):
        return dict(zip(columns, getter(d)))

    raise ValueError('Unsupported type for `d`')

examples of use

# pure dict

d = dict(a=1, b=2, c=3)
print(subdict(d, ['a', 'c']))

>>> In [5]: {'a': 1, 'c': 3}
# list of dicts

d = [
    dict(a=1, b=2, c=3),
    dict(a=2, b=4, c=6),
    dict(a=4, b=8, c=12),
]

print(subdict(d, ['a', 'c']))

>>> In [5]: [{'a': 1, 'c': 3}, {'a': 2, 'c': 6}, {'a': 4, 'c': 12}]

HTTP POST with URL query parameters -- good idea or not?

Everyone is right: stick with POST for non-idempotent requests.

What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!

It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)

Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:

Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]

Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.

In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)

Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.

Add directives from directive in AngularJS

A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.

Something like...

link: function(scope, elem, attr){
    var wrapper = angular.element('<div tooltip></div>');
    elem.before(wrapper);
    $compile(wrapper)(scope);
    wrapper.append(elem);
}

This solution has the advantage that it keeps things simple by not recompiling the original element.

This wouldn't work if any of the added directive's require any of the original element's directives or if the original element has absolute positioning.

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

Loop through all the resources in a .resx file

Simple read loop use this code

var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}

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

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

jQuery remove options from select

When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)

$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

How to add a new schema to sql server 2008?

In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button

How to get parameters from a URL string?

you can use below code to get email address after ? in the URL

_x000D_
_x000D_
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
    echo $_GET['email'];_x000D_
}
_x000D_
_x000D_
_x000D_

Is there a standardized method to swap two variables in Python?

Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays

BarCode Image Generator in Java

iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.

This page has the details on creating barcodes. Here is an example from that site:

BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);

The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.

Android EditText for password with android:hint

Here is your answer:

There are different category for inputType so I used for pssword is textPaswword

<EditText
    android:inputType="textPassword"
    android:id="@+id/passwor"
    android:textColorHint="#ffffff"
    android:layout_marginRight="15dp"
    android:layout_marginLeft="15dp"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:hint="********"
    />

How to shut down the computer from C#

Works starting with windows XP, not available in win 2000 or lower:

This is the quickest way to do it:

Process.Start("shutdown","/s /t 0");

Otherwise use P/Invoke or WMI like others have said.

Edit: how to avoid creating a window

var psi = new ProcessStartInfo("shutdown","/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

The import javax.servlet can't be resolved

Add to pom.xml

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

How to implement onBackPressed() in Fragments?

If you use EventBus, it is probably a far more simpler solution :

In your Fragment :

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    EventBus.getDefault().register(this);
}

@Override
public void onDetach() {
    super.onDetach();
    EventBus.getDefault().unregister(this);
}


// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
    getSupportFragmentManager().popBackStack();
}

and in your Activity class you can define :

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
    super.onBackPressed();
}

@Override
public void onBackPressed() {
    EventBus.getDefault().post(new BackPressedMessage(true));
}

BackPressedMessage.java is just a POJO object

This is super clean and there is no interface/implementation hassle.

How to apply CSS to iframe?

I think the easiest way is to add another div, in the same place as the iframe, then

make its z-index bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none on your own div, so the iframe would be working in case you need to click on it ;)

I hope It will help someone ;)

Is there a way to pass javascript variables in url?

Do you mean include javascript variable values in the query string of the URL?

Yes:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;

Uncaught SyntaxError: Unexpected token :

This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}

Hopefully that will help someone in the future.

how does unix handle full path name with space and arguments?

You can either quote it like your Windows example above, or escape the spaces with backslashes:

 "/foo folder with space/foo" --help
 /foo\ folder\ with\ space/foo --help

ORA-01036: illegal variable name/number when running query through C#

I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .

Create html documentation for C# code

Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.

Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).

How to create an array of object literals in a loop?

This is what Array#map are good at

var arr = oFullResponse.results.map(obj => ({
    key: obj.label,
    sortable: true,
    resizeable: true
}))

How to convert data.frame column from Factor to numeric

This is FAQ 7.10. Others have shown how to apply this to a single column in a data frame, or to multiple columns in a data frame. But this is really treating the symptom, not curing the cause.

A better approach is to use the colClasses argument to read.table and related functions to tell R that the column should be numeric so that it never creates a factor and creates numeric. This will put in NA for any values that do not convert to numeric.

Another better option is to figure out why R does not recognize the column as numeric (usually a non numeric character somewhere in that column) and fix the original data so that it is read in properly without needing to create NAs.

Best is a combination of the last 2, make sure the data is correct before reading it in and specify colClasses so R does not need to guess (this can speed up reading as well).

How to copy selected lines to clipboard in vim

SHIFTV puts you in select lines mode. Then "*y yanks the currently selected lines to the * register which is the clipboard. There are quite a few different registers, for different purposes. See the section on selection and drop registers for details on the differences between * and + registers on Windows and Linux.

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

Copy/Paste from Excel to a web page

You don't lose the delimiters, the cells are separated by tabs (\t) and rows by newlines (\n) which might not be visible in the form. Try it yourself: copy content from Excel to Notepad, and you'll see your cells nicely lined up. It's easy then to split the fields by tabs and replace them with something else, this way you can build even a table from them. Here's a example using jQuery:

var data = $('input[name=excel_data]').val();
var rows = data.split("\n");

var table = $('<table />');

for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);

So in essence, this script creates an HTML table from pasted Excel data.

What does the 'standalone' directive mean in XML?

The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.

As an example, consider the humble <img> tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img> tags must be EMPTY and possess src and alt attributes. When a browser is going through an XHTML 1.0 document and finds an <img> tag, it should notice that the DTD requires src and alt attributes and add them if they are not present. It will also self-close the <img> tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone declaration to tell the parser to ignore these rules.

Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.

Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.

How to deal with SettingWithCopyWarning in Pandas

In general the point of the SettingWithCopyWarning is to show users (and especially new users) that they may be operating on a copy and not the original as they think. There are false positives (IOW if you know what you are doing it could be ok). One possibility is simply to turn off the (by default warn) warning as @Garrett suggest.

Here is another option:

In [1]: df = DataFrame(np.random.randn(5, 2), columns=list('AB'))

In [2]: dfa = df.ix[:, [1, 0]]

In [3]: dfa.is_copy
Out[3]: True

In [4]: dfa['A'] /= 2
/usr/local/bin/ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  #!/usr/local/bin/python

You can set the is_copy flag to False, which will effectively turn off the check, for that object:

In [5]: dfa.is_copy = False

In [6]: dfa['A'] /= 2

If you explicitly copy then no further warning will happen:

In [7]: dfa = df.ix[:, [1, 0]].copy()

In [8]: dfa['A'] /= 2

The code the OP is showing above, while legitimate, and probably something I do as well, is technically a case for this warning, and not a false positive. Another way to not have the warning would be to do the selection operation via reindex, e.g.

quote_df = quote_df.reindex(columns=['STK', ...])

Or,

quote_df = quote_df.reindex(['STK', ...], axis=1)  # v.0.21

Dynamically Add Variable Name Value Pairs to JSON Object

when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

screenshot

Update select2 data without rebuilding the control

For Select2 4.X

var instance = $('#select2Container').data('select2');
var searchVal = instance.dropdown.$search.val();
instance.trigger('query', {term:searchVal});

How to redirect output of an entire shell script within the script itself?

Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.

Send stdout to a file

exec > file

with stderr

exec > file                                                                      
exec 2>&1

append both stdout and stderr to file

exec >> file
exec 2>&1

As Jonathan Leffler mentioned in his comment:

exec has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec.

if A vs if A is not None:

if x: #x is treated True except for all empty data types [],{},(),'',0 False, and None

so it is not same as

if x is not None # which works only on None

Select multiple columns using Entity Framework

Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username } part) to a PInfo object.

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();

This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.

If your PInfo object has the right properties, it can be like this :

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new PInfo 
                 { 
                      ServerName = x.ServerName, 
                      ProcessID = x.ProcessID, 
                      UserName = x.Username 
                 }).ToList();

Assuming that PInfo has at least those three properties.

Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

How can I get the current PowerShell executing file?

I would argue that there is a better method, by setting the scope of the variable $MyInvocation.MyCommand.Path:

ex> $script:MyInvocation.MyCommand.Name

This method works in all circumstances of invocation:

EX: Somescript.ps1

function printme () {
    "In function:"
    ( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
    ( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
    ( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
}
"Main:"
( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
" "
printme
exit

OUTPUT:

PS> powershell C:\temp\test.ps1
Main:
MyInvocation.ScriptName:
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: test.ps1

In function:
MyInvocation.ScriptName: C:\temp\test.ps1
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: printme

Notice how the above accepted answer does NOT return a value when called from Main. Also, note that the above accepted answer returns the full path when the question requested the script name only. The scoped variable works in all places.

Also, if you did want the full path, then you would just call:

$script:MyInvocation.MyCommand.Path

Git merge errors

git commit -m "Merged master fixed conflict."

Running an outside program (executable) in Python?

Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.

So you might try:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:

function funs = makefuns
  funs.fun1=@fun1;
  funs.fun2=@fun2;
end

function y=fun1(x)
  y=x;
end

function z=fun2
  z=1;
end

And here is how it could be used:

>> myfuns = makefuns;
>> myfuns.fun1(5)    
ans =
     5
>> myfuns.fun2()     
ans =
     1

How to Determine the Screen Height and Width in Flutter

We have noticed that using the MediaQuery class can be a bit cumbersome, and it’s also missing a couple of key pieces of information.

Here We have a small Screen helper class, that we use across all our new projects:

class Screen {
  static double get _ppi => (Platform.isAndroid || Platform.isIOS)? 150 : 96;
  static bool isLandscape(BuildContext c) => MediaQuery.of(c).orientation == Orientation.landscape;
  //PIXELS
  static Size size(BuildContext c) => MediaQuery.of(c).size;
  static double width(BuildContext c) => size(c).width;
  static double height(BuildContext c) => size(c).height;
  static double diagonal(BuildContext c) {
    Size s = size(c);
    return sqrt((s.width * s.width) + (s.height * s.height));
  }
  //INCHES
  static Size inches(BuildContext c) {
    Size pxSize = size(c);
    return Size(pxSize.width / _ppi, pxSize.height/ _ppi);
  }
  static double widthInches(BuildContext c) => inches(c).width;
  static double heightInches(BuildContext c) => inches(c).height;
  static double diagonalInches(BuildContext c) => diagonal(c) / _ppi;
}

To use

bool isLandscape = Screen.isLandscape(context)
bool isLargePhone = Screen.diagonal(context) > 720;
bool isTablet = Screen.diagonalInches(context) >= 7;
bool isNarrow = Screen.widthInches(context) < 3.5;

To More, See: https://blog.gskinner.com/archives/2020/03/flutter-simplify-platform-detection-responsive-sizing.html

How do I output coloured text to a Linux terminal?

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

How to stop event propagation with inline onclick attribute?

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you can do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

How do you properly use namespaces in C++?

Don't listen to every people telling you that namespaces are just name-spaces.

They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:

namespace ns {

class A
{
};

void print(A a)
{
}

}

If you wanted to print an A object, the code would be this one:

ns::A a;
print(a);

Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.

Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.

namespace ns {

class A
{
};

}

void print(A a)
{
}

And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.

Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.

And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.

If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter

Close Android Application

I don't think you can do it in one line of code. Try opening your activities with startActivityForResult. As the result you can pass something like a CLOSE_FLAG, which will inform your parent activity that its child activity has finished.

That said, you should probably read this answer.

Convert string date to timestamp in Python

Seems to be quite efficient:

import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()

1.61 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

How to remove a character at the end of each line in unix

An awk code based on RS.

awk '1' RS=',\n' file

or:

awk 'BEGIN{RS=",\n"}1' file

This last example will be valid for any char before newline:

awk '1' RS='.\n' file

Note: dot . matches any character except line breaks.

Explanation

awk allows us to use different record (line) regex separators, we just need to include the comma before the line break (or dot for any char) in the one used for the input, the RS.

Note: what that 1 means?

Short answer, It's just a shortcut to avoid using the print statement. In awk when a condition gets matched the default action is to print the input line, example:

$ echo "test" |awk '1'
test

That's because 1 will be always true, so this expression is equivalent to:

$ echo "test"|awk '1==1'
test
$ echo "test"|awk '{if (1==1){print}}'
test

Documentation

Check Record Splitting with Standard awk and Output Separators.

MySQL SELECT AS combine two columns into one

In case of NULL columns it is better to use IF clause like this which combine the two functions of : CONCAT and COALESCE and uses special chars between the columns in result like space or '_'

SELECT FirstName , LastName , 
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,''))) 
AS Contact_Phone FROM   TABLE1

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();
    }

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

What are best practices that you use when writing Objective-C and Cocoa?

All these comments are great, but I'm really surprised nobody mentioned Google's Objective-C Style Guide that was published a while back. I think they have done a very thorough job.

removeEventListener on anonymous functions in JavaScript

I believe that is the point of an anonymous function, it lacks a name or a way to reference it.

If I were you I would just create a named function, or put it in a variable so you have a reference to it.

var t = {};
var handler = function(e) {
    t.scroll = function(x, y) {
        window.scrollBy(x, y);
    };
    t.scrollTo = function(x, y) {
        window.scrollTo(x, y);
    };
};
window.document.addEventListener("keydown", handler);

You can then remove it by

window.document.removeEventListener("keydown", handler);   

org.apache.jasper.JasperException: Unable to compile class for JSP:

include your Member Class to your jsp :

<%@ page import="pageNumber.*, java.util.*, java.io.*,yourMemberPackage.Member" %>

"NOT IN" clause in LINQ to Entities

If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).

   var exceptionList = new List<string> { "exception1", "exception2" };

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Where(e => !exceptionList.Contains(e.Name));

If you're excluding based on another database query using Except might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)

   var exceptionList = myEntities.MyOtherEntity
                                 .Select(e => e.Name);

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Except(exceptionList);

This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).

Return JSON response from Flask view

if its a dict, flask can return it directly (Version 1.0.2)

def summary():
    d = make_summary()
    return d, 200

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

Printing everything except the first field with awk

Assigning $1 works but it will leave a leading space: awk '{first = $1; $1 = ""; print $0, first; }'

You can also find the number of columns in NF and use that in a loop.

How to find whether a ResultSet is empty or not in Java?

Calculates the size of the java.sql.ResultSet:

int size = 0;
if (rs != null) {
    rs.beforeFirst();
    rs.last();
    size = rs.getRow();
}

(Source)

How do I create a crontab through a script

It is an approach to incrementally add the cron job:

  ssh USER_NAME@$PRODUCT_IP nohup "echo '*/2 * * * * ping -c2 PRODUCT_NAME.com >> /var/www/html/test.html' | crontab -u USER_NAME -"

Default port for SQL Server

SQL Server default port is 1434.

To allow remote access I had to release those ports on my firewall:

Protocol  |   Port
---------------------
UDP       |   1050
TCP       |   1050
TCP       |   1433
UDP       |   1434

jQuery AJAX form data serialize using PHP

Your problem is in your php file. When you use jquery serialize() method you are sending a string, so you can not treat it like an array. Make a var_dump($_post) and you will see what I am talking about.

SQL to Entity Framework Count Group-By

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

Can I use a min-height for table, tr or td?

if you set style="height:100px;" on a td if the td has content that grows the cell more than that, it will do so no need for min height on a td.

PHP - check if variable is undefined

An another way is simply :

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Will return :

"Yes 3"

The best way is to use isset(), otherwise you can have an error like "undefined $test".

You can do it like this :

if( isset($test) && ($test!==null) )

You'll not have any error because the first condition isn't accepted.

How do I show/hide a UIBarButtonItem?

There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

How to remove an HTML element using Javascript?

That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

For Windows 10, from the Android Studio terminal:

keytool -exportcert -alias androiddebugkey -keystore %USER_PROFILE%"/.android/debug.keystore -list -v

Note: For the debug.keystore, the password is "android". The debug keystore is typically located at "%USER_PROFILE%"/.android/debug.keystore.

..The underlying connection was closed: An unexpected error occurred on a receive

Setting the HttpWebRequest.KeepAlive to false didn't work for me.

Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Notice that there are other SecurityProtocolTypes: SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11

So if the Tls12 doesn't work for you, try the three remaining options.

Also notice that you can set multiple protocols. This is preferable on most cases.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b

SQL Joins Vs SQL Subqueries (Performance)?

Performance is based on the amount of data you are executing on...

If it is less data around 20k. JOIN works better.

If the data is more like 100k+ then IN works better.

If you do not need the data from the other table, IN is good, But it is alwys better to go for EXISTS.

All these criterias I tested and the tables have proper indexes.

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

Catching errors in Angular HttpClient

You probably want to have something like this:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

It highly depends also how do you use your service but this is the basic case.

How many times a substring occurs

j = 0
    while i < len(string):
        sub_string_out = string[i:len(sub_string)+j]
        if sub_string == sub_string_out:
            count += 1
        i += 1
        j += 1
    return count

Remove special symbols and extra spaces and replace with underscore using the replace method

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

Vim and Ctags tips and tricks

I use vim in macos, and the original ctags doesn't work well, so I download newest and configure make make install it. I install ctgas in /usr/local/bin/ctags(to keep original one)

"taglist
let Tlist_Ctags_Cmd = "/usr/local/bin/ctags"
let Tlist_WinWidth = 50
map <leader>ta :TlistToggle<cr>
map <leader>bta :!/usr/local/bin/ctags -R .<CR>
set tags=tags;/
map <M-j> <C-]>
map <M-k> <C-T>

How do you use the ? : (conditional) operator in JavaScript?

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

Here is an example of code that could be shortened with the conditional operator:

var userType;
if (userIsYoungerThan18) {
  userType = "Minor";
} else {
  userType = "Adult";
}

if (userIsYoungerThan21) {
  serveDrink("Grape Juice");
} else {
  serveDrink("Wine");
}

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

Activity has leaked window that was originally added

This could help.

if (! isFinishing()) {

    dialog.show();

    }

Git: How to check if a local repo is up to date?

If you use

git fetch --dry-run -v <link/to/remote/git/repo>

you'll get feedback about whether it is up-to-date. So basically, you just need to add the "verbose" option to the answer given before.

Calculating arithmetic mean (one type of average) in Python

Use statistics.mean:

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.

Build tree array from flat array in javascript

ES6 Map version :

getTreeData = (items) => {
  if (items && items.length > 0) {
    const data = [];
    const map = {};
    items.map((item) => {
      const id = item.id; // custom id selector !!!
      if (!map.hasOwnProperty(id)) {
        // in case of duplicates
        map[id] = {
          ...item,
          children: [],
        };
      }
    });
    for (const id in map) {
      if (map.hasOwnProperty(id)) {
        let mappedElem = [];
        mappedElem = map[id];
        /// parentId : use custom id selector for parent
        if (
          mappedElem.parentId &&
          typeof map[mappedElem.parentId] !== "undefined"
        ) {
          map[mappedElem.parentId].children.push(mappedElem);
        } else {
          data.push(mappedElem);
        }
      }
    }
    return data;
  }
  return [];
};

/// use like this :

const treeData = getTreeData(flatList);

How to suppress warnings globally in an R Script

You could use

options(warn=-1)

But note that turning off warning messages globally might not be a good idea.

To turn warnings back on, use

options(warn=0)

(or whatever your default is for warn, see this answer)

Apply style to only first level of td tags

I wanted to set the width of the first column of the table, and I found this worked (in FF7) - the first column is 50px wide:

#MyTable>thead>tr>th:first-child { width:50px;}

where my markup was

<table id="MyTable">
 <thead>
  <tr>
   <th scope="col">Col1</th>
   <th scope="col">Col2</th>
  </tr>
 </thead>
 <tbody>
   ...
 </tbody>
</table>

How to check if string input is a number?

If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:

def isnumber(x):
    import numpy
    try:
        return type(numpy.float(x)) == float
    except ValueError:
        return False

cannot convert data (type interface {}) to type string: need type assertion

According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.

In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.

If you were unsure if it was a string or not, you could test using the two return syntax.

str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:

if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

How to convert a String to Bytearray

I know the question is almost 4 years old, but this is what worked smoothly with me:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes;_x000D_
};_x000D_
_x000D_
Array.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.toString().split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

or, if you want to work with strings only, and no Array, you can use:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes.toString();_x000D_
};_x000D_
_x000D_
String.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

Why does "npm install" rewrite package-lock.json?

It appears this issue is fixed in npm v5.4.2

https://github.com/npm/npm/issues/17979

(Scroll down to the last comment in the thread)

Update

Actually fixed in 5.6.0. There was a cross platform bug in 5.4.2 that was causing the issue to still occur.

https://github.com/npm/npm/issues/18712

Update 2

See my answer here: https://stackoverflow.com/a/53680257/1611058

npm ci is the command you should be using when installing existing projects now.

How to get english language word database?

There's no such thing as a "complete" list. Different people have different ways of measuring -- for example, they might include slang, neologisms, multi-word phrases, offensive terms, foreign words, verb conjugations, and so on. Some people have even counted a million words! So you'll have to decide what you want in a word list.

Ignore Duplicates and Create New List of Unique Values in Excel

I have a list of color names in range A2:A8, in column B I want to extract a distinct list of color names.

Follow the below given steps:

  • Select the Cell B2; write the formula to retrieve the unique values from a list.
  • =IF(COUNTIF(A$2:A2,A2)=1,A2,””)
  • Press Enter on your keyboard.
  • The function will return the name of the first color.
  • To return the value for the rest of cells, copy the same formula down. To copy formula in range B3:B8, copy the formula in cell B2 by pressing the key CTRL+C on your keyboard and paste in the range B3:B8 by pressing the key CTRL+V.
  • Here you can see the output where we have the unique list of color names.

Efficiently getting all divisors of a given number

//Try this,it can find divisors of verrrrrrrrrry big numbers (pretty efficiently :-))
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<conio.h>

using namespace std;

vector<double> D;

void divs(double N);
double mod(double &n1, double &n2);
void push(double N);
void show();

int main()
{
    double N; 
    cout << "\n Enter number: "; cin >> N;

    divs(N); // find and push divisors to D

    cout << "\n Divisors of "<<N<<": "; show(); // show contents of D (all divisors of N)

_getch(); // used visual studio, if it isn't supported replace it by "getch();"
return(0);
}

void divs(double N)
{
    for (double i = 1; i <= sqrt(N); ++i)
    {
        if (!mod(N, i)) { push(i); if(i*i!=N) push(N / i); }
    }
}

double mod(double &n1, double &n2)
{
    return(((n1/n2)-floor(n1/n2))*n2);
}

void push(double N)
{
    double s = 1, e = D.size(), m = floor((s + e) / 2);
    while (s <= e)
    {   
        if (N==D[m-1]) { return; }
        else if (N > D[m-1]) { s = m + 1; }
        else { e = m - 1; }
        m = floor((s + e) / 2);
    }
    D.insert(D.begin() + m, N);
}

void show()
{
    for (double i = 0; i < D.size(); ++i) cout << D[i] << " ";
}

Make 2 functions run at the same time

The thread module does work simultaneously unlike multiprocess, but the timing is a bit off. The code below prints a "1" and a "2". These are called by different functions respectively. I did notice that when printed to the console, they would have slightly different timings.

from threading import Thread

def one():
    while(1 == num):
        print("1")
        time.sleep(2)
    
def two():
    while(1 == num):
        print("2")
        time.sleep(2)


p1 = Thread(target = one)
p2 = Thread(target = two)

p1.start()
p2.start()

Output: (Note the space is for the wait in between printing)

1
2

2
1

12
   
21

12
   
1
2

Not sure if there is a way to correct this, or if it matters at all. Just something I noticed.

How to set value to form control in Reactive Forms in Angular

In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).

setValue:

  • Initialize Model Structure in Constructor:

    this.newForm = this.formBuilder.group({  
       firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
       lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
    });
    
  • If you want to update all fields of form:

    this.newForm.setValue({
       firstName: 'abc',
       lastName: 'def'
    });
    
  • If you want to update specific field of form:

    this.newForm.controls.firstName.setValue('abc');
    

Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.

patchValue:

  • If you want to update some/ specific fields of form:

    this.newForm.patchValue({
       firstName: 'abc'
    });
    

Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

C# - Winforms - Global Variables

One way,

Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.

Access them by

Properties.Settings.Default.MySetting = "hello world";

Could not connect to React Native development server on Android

For me all done as mentioned above still it was not working then I followed below steps and working like charm

Go Window security => Select Firewall and network protection => Turn off private networkenter image description here

Is there an easy way to return a string repeated X number of times?

If you only intend to repeat the same character you can use the string constructor that accepts a char and the number of times to repeat it new String(char c, int count).

For example, to repeat a dash five times:

string result = new String('-', 5);
Output: -----

HTTP Error 404 when running Tomcat from Eclipse

I had this or a similar problem after installing Tomcat.

The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.

What do the different readystates in XMLHttpRequest mean, and how can I use them?

The full list of readyState values is:

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

(from https://www.w3schools.com/js/js_ajax_http_response.asp)

In practice you almost never use any of them except for 4.

Some XMLHttpRequest implementations may let you see partially received responses in responseText when readyState==3, but this isn't universally supported and shouldn't be relied upon.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

To have a good follow-up about all this, Twitter - one of the pioneers of hashbang URL's and single-page-interface - admitted that the hashbang system was slow in the long run and that they have actually started reversing the decision and returning to old-school links.

Article about this is here.

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

How do we use runOnUiThread in Android?

Below is corrected Snippet of runThread Function.

private void runThread() {

    new Thread() {
        public void run() {
            while (i++ < 1000) {
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            btn.setText("#" + i);
                        }
                    });
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

Python math module

pow is built into the language(not part of the math library). The problem is that you haven't imported math.

Try this:

import math
math.sqrt(4)

How to make in CSS an overlay over an image?

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

_x000D_
_x000D_
.image-container {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: none;_x000D_
    color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
    display: block;_x000D_
    background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    width: 100%;_x000D_
    box-sizing: border-box;_x000D_
    padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
    color: #DDD;_x000D_
    font-size: 48px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin: -30px 0 0 -19px;_x000D_
    height: 50px;_x000D_
    width: 45px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
    color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
    <img src="http://lorempixel.com/300/180" />_x000D_
    <div class="after">_x000D_
        <span class="content">This is some content. It can be long and span several lines.</span>_x000D_
        <span class="zoom">_x000D_
            <i class="fa fa-search"></i>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS opacity only to background color, not the text on it?

The easiest solution is to create 3 divs. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

1.Set the following Environment Property on your active Shell. - open bash terminal and type in:

  $ export LD_BIND_NOW=1
  1. Re-Run the Jar or Java File

Note: for superuser in bash type su and press enter

Swift: declare an empty dictionary

var emptyDictionary = [String: String]()

­

var populatedDictionary = ["key1": "value1", "key2": "value2"]

Note: if you are going to change the contents of the dictionary over time then declare it as a var (variable). You can declare an empty dictionary as a let (constant) but it is pointless if you have the intention of changing its contents over time, since constant can't be changed after it has been initialized.


Old answer:

Creating an empty dictionary of type <String, String> would look as follows:

var emptyDictionary = Dictionary<String, String>()

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

Can an Option in a Select tag carry multiple values?

its possible to have multiple values in a select option as shown below.

<select id="ddlEmployee" class="form-control">
    <option value="">-- Select --</option>
    <option value="1" data-city="Washington" data-doj="20-06-2011">John</option>
    <option value="2" data-city="California" data-doj="10-05-2015">Clif</option>
    <option value="3" data-city="Delhi" data-doj="01-01-2008">Alexander</option>
</select>

you can get selected value on change event using jquery as shown below.

$("#ddlEmployee").change(function () {
     alert($(this).find(':selected').data('city'));
});

You can find more details in this LINK

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

in .mjs files we for now don't have __dirname

hence

res.sendFile('index.html', { root: '.' })

MySQL root password change

  1. On Mac open system preferences> MySQL.
  2. In the configuration section of MySQL check for initialize database.
  3. change the password in the prompt. initialize Database

How to communicate between iframe and the parent site?

This library supports HTML5 postMessage and legacy browsers with resize+hash https://github.com/ternarylabs/porthole

Edit: Now in 2014, IE6/7 usage is quite low, IE8 and above all support postMessage so I now suggest to just use that.

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

how to extract only the year from the date in sql server 2008?

SQL Server Script

declare @iDate datetime
set @iDate=GETDATE()

print year(@iDate) -- for Year

print month(@iDate) -- for Month

print day(@iDate) -- for Day

Alert handling in Selenium WebDriver (selenium 2) with Java

Alert alert = driver.switchTo().alert();

alert.accept();

You can also decline the alert box:


Alert alert = driver.switchTo().alert();

alert().dismiss();

Validate email address textbox using JavaScript

Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript :

An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters.

  1. Uppercase (A-Z) and lowercase (a-z) English letters.
  2. Digits (0-9).
  3. Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  4. Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.

The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.

Example of valid email id

[email protected]

[email protected]

[email protected]

Example of invalid email id

mysite.ourearth.com [@ is not present]

[email protected] [ tld (Top Level domain) can not start with dot "." ]

@you.me.net [ No character before @ ]

[email protected] [ ".b" is not a valid tld ]

[email protected] [ tld can not start with dot "." ]

[email protected] [ an email should not be start with "." ]

mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]

[email protected] [double dots are not allowed]

JavaScript code to validate an email id

function ValidateEmail(mail) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) {
            return (true)
        }
        alert("You have entered an invalid email address!")
        return (false)
    }

How to bind event listener for rendered elements in Angular 2?

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

If the DLL and the .NET projects are in the same solution and you want to compile and run both every time, you can right click the properties of the .NET project, Build events, then add something like the following to Post-build event command line:

copy $(SolutionDir)Debug\MyOwn.dll .

It's basically a DOS line, and you can tweak based on where your DLL is being built to.

How to parse a JSON object to a TypeScript Object

If you use a TypeScript interface instead of a class, things are simpler:

export interface Employee {
    typeOfEmployee_id: number;
    department_id: number;
    permissions_id: number;
    maxWorkHours: number;
    employee_id: number;
    firstname: string;
    lastname: string;
    username: string;
    birthdate: Date;
    lastUpdate: Date;
}

let jsonObj: any = JSON.parse(employeeString); // string to generic object first
let employee: Employee = <Employee>jsonObj;

If you want a class, however, simple casting won't work. For example:

class Foo {
    name: string;
    public pump() { }
}

let jsonObj: any = JSON.parse('{ "name":"hello" }');
let fObj: Foo = <Foo>jsonObj;
fObj.pump(); // crash, method is undefined!

For a class, you'll have to write a constructor which accepts a JSON string/object and then iterate through the properties to assign each member manually, like this:

class Foo {
    name: string;

    constructor(jsonStr: string) {
        let jsonObj: any = JSON.parse(jsonStr);
        for (let prop in jsonObj) {
            this[prop] = jsonObj[prop];
        }
    }
}

let fObj: Foo = new Foo(theJsonString);

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

Running Selenium Webdriver with a proxy in Python

How about something like this

PROXY = "149.215.113.110:70"

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}

# you have to use remote, otherwise you'll have to code it yourself in python to 
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)

You can read more about it here.

MySQL - DATE_ADD month interval

BETWEEN ... AND

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0.

The important part here is EQUAL to max., which 1st of July is.

What does int argc, char *argv[] mean?

Both of

int main(int argc, char *argv[]);
int main();

are legal definitions of the entry point for a C or C++ program. Stroustrup: C++ Style and Technique FAQ details some of the variations that are possible or legal for your main function.

matching query does not exist Error in Django

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see you're storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

Making sure at least one checkbox is checked

Check this.

You can't access form inputs via their name. Use document.getElements methods instead.

How do you detect Credit card type based on number?

The first numbers of the credit card can be used to approximate the vendor:

  • Visa: 49,44 or 47
  • Visa electron: 42, 45, 48, 49
  • MasterCard: 51
  • Amex:34
  • Diners: 30, 36, 38
  • JCB: 35

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Seriously, the top answer is not working for me. tried cxf.version 2.4.1 and 3.0.10. and generate absolute path with wsdlLocation every times.

My solution is to use the wsdl2java command in the apache-cxf-3.0.10\bin\ with -wsdlLocation classpath:wsdl/QueryService.wsdl.

Detail:

    wsdl2java -encoding utf-8 -p com.jeiao.boss.testQueryService -impl -wsdlLocation classpath:wsdl/testQueryService.wsdl http://127.0.0.1:9999/platf/testQueryService?wsdl

Check whether a table contains rows or not sql server 2005

Like Other said you can use something like that:

IF NOT EXISTS (SELECT 1 FROM Table)
  BEGIN 
    --Do Something
  END 
ELSE
  BEGIN
    --Do Another Thing
  END

rotate image with css

Give the parent a style of overflow: hidden. If it is overlapping sibling elements, you will have to put it inside of a container with a fixed height/width and give that a style of overflow: hidden.

What is ToString("N0") format?

Here is a good start maybe

Double.ToString()

Have a look in the examples for a number of different formating options Double.ToString(string)

How to obtain the number of CPUs/cores in Linux from the command line?

The most portable solution I have found is the getconf command:

getconf _NPROCESSORS_ONLN

This works on both Linux and Mac OS X. Another benefit of this over some of the other approaches is that getconf has been around for a long time. Some of the older Linux machines I have to do development on don't have the nproc or lscpu commands available, but they have getconf.

Editor's note: While the getconf utility is POSIX-mandated, the specific _NPROCESSORS_ONLN and _NPROCESSORS_CONF values are not. That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _.

How to use a dot "." to access members of dictionary?

A solution kind of delicate

class DotDict(dict):

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, key):

        def typer(candidate):
            if isinstance(candidate, dict):
                return DotDict(candidate)

            if isinstance(candidate, str):  # iterable but no need to iter
                return candidate

            try:  # other iterable are processed as list
                return [typer(item) for item in candidate]
            except TypeError:
                return candidate

            return candidate

        return typer(dict.get(self, key))

WPF MVVM: How to close a window

We have the name property in the .xaml definition:

x:Name="WindowsForm"

Then we have the button:

<Button Command="{Binding CloseCommand}" 
CommandParameter="{Binding ElementName=WindowsForm}" />

Then in the ViewModel:

public DelegateCommand <Object>  CloseCommand { get; private set; }

Constructor for that view model:
this.CloseCommand = new DelegateCommand<object>(this.CloseAction);

Then at last, the action method:

private void CloseAction (object obj)
{
  Window Win = obj as Window;
  Win.Close();

}

I used this code to close a pop-up window from an application..

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

How do I auto-resize an image to fit a 'div' container?

As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):

img {
    max-height: 75vh;
}

How to solve "Fatal error: Class 'MySQLi' not found"?

Sounds like you just need to install MySQLi.

If you think you've done that and still have a problem, please post your operating system and anything else that might help diagnose it further.

Pure CSS animation visibility with delay

You are correct in thinking that display is not animatable. It won't work, and you shouldn't bother including it in keyframe animations.

visibility is technically animatable, but in a round about way. You need to hold the property for as long as needed, then snap to the new value. visibility doesn't tween between keyframes, it just steps harshly.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  99% {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

If you want to fade, you use opacity. If you include a delay, you'll need visibility as well, to stop the user from interacting with the element while it's not visible.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  0% {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

Both examples use animation-fill-mode, which can hold an element's visual state after an animation ends.

Append an object to a list in R in amortized constant time, O(1)?

I have made a small comparison of methods mentioned here.

n = 1e+4
library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj} 

microbenchmark(times = 5,  
        env_with_list_ = {
            listptr <- new.env(parent=globalenv())
            listptr$list <- NULL
            for(i in 1:n) {envAppendList(listptr, i)}
            listptr$list
        },
        c_ = {
            a <- list(0)
            for(i in 1:n) {a = c(a, list(i))}
        },
        list_ = {
            a <- list(0)
            for(i in 1:n) {a <- list(a, list(i))}
        },
        by_index = {
            a <- list(0)
            for(i in 1:n) {a[length(a) + 1] <- i}
            a
        },
        append_ = { 
            a <- list(0)    
            for(i in 1:n) {a <- append(a, i)} 
            a
        },
        env_as_container_ = {
            listptr <- new.env(parent=globalenv())
            for(i in 1:n) {lPtrAppend(listptr, i, i)} 
            listptr
        }   
)

Results:

Unit: milliseconds
              expr       min        lq       mean    median        uq       max neval cld
    env_with_list_  188.9023  198.7560  224.57632  223.2520  229.3854  282.5859     5  a 
                c_ 1275.3424 1869.1064 2022.20984 2191.7745 2283.1199 2491.7060     5   b
             list_   17.4916   18.1142   22.56752   19.8546   20.8191   36.5581     5  a 
          by_index  445.2970  479.9670  540.20398  576.9037  591.2366  607.6156     5  a 
           append_ 1140.8975 1316.3031 1794.10472 1620.1212 1855.3602 3037.8416     5   b
 env_as_container_  355.9655  360.1738  399.69186  376.8588  391.7945  513.6667     5  a 

Converting datetime.date to UTC timestamp in Python

the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

if you actually have the year, month and day you don't need to create the date:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

DO NOTHING. Just Update Android Studio. Resolve my problem! Work perfectly.

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

Use of "this" keyword in C++

It's programmer preference. Personally, I love using this since it explicitly marks the object members. Of course the _ does the same thing (only when you follow the convention)

Replace Div Content onclick

A Third Answer

Sorry, maybe I have it correct this time...

jsFiddle Demo

var savedBox1, savedBox2, state1=0, state2=0;

jQuery(document).ready(function() {
    jQuery(".rec1").click(function() {
        if (state1==0){
            savedBox1 = jQuery('#rec-box').html();
            jQuery('#rec-box').html(jQuery(this).next().html()); 
            state1 = 1;
        }else{
            jQuery('#rec-box').html(savedBox1); 
            state1 = 0;
        }
    });

    jQuery(".rec2").click(function() {
        if (state1==0){
            savedBox2 = jQuery('#rec-box2').html();
            jQuery('#rec-box2').html(jQuery(this).next().html()); 
            state2 = 1;
        }else{
            jQuery('#rec-box2').html(savedBox2); 
            state2 = 0;
        }
    });
});

How to use JavaScript source maps (.map files)?

The map file maps the unminified file to the minified file. If you make changes in the unminified file, the changes will be automatically reflected to the minified version of the file.

Difference between DTO, VO, POJO, JavaBeans?

DTO vs VO

DTO - Data transfer objects are just data containers which are used to transport data between layers and tiers.

  • It mainly contains attributes. You can even use public attributes without getters and setters.
  • Data transfer objects do not contain any business logic.

Analogy:
Simple Registration form with attributes username, password and email id.

  • When this form is submitted in RegistrationServlet file you will get all the attributes from view layer to business layer where you pass the attributes to java beans and then to the DAO or the persistence layer.
  • DTO's helps in transporting the attributes from view layer to business layer and finally to the persistence layer.

DTO was mainly used to get data transported across the network efficiently, it may be even from JVM to another JVM.

DTOs are often java.io.Serializable - in order to transfer data across JVM.

VO - A Value Object [1][2] represents itself a fixed set of data and is similar to a Java enum. A Value Object's identity is based on their state rather than on their object identity and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.

POJO vs JavaBeans

[1] The Java-Beanness of a POJO is that its private attributes are all accessed via public getters and setters that conform to the JavaBeans conventions. e.g.

    private String foo;
    public String getFoo(){...}
    public void setFoo(String foo){...}; 

[2] JavaBeans must implement Serializable and have a no-argument constructor, whereas in POJO does not have these restrictions.

CSS animation delay in repeating

for a border flash: actually very simple: replace from to to 99% black and e.g 1% the shift to blue you can even make it shorter, animation time set to e.g 5sec.

@keyframes myborder {
  0% {border-color: black;}
  99% {border-color:black;}
  100% {border-color: blue;}
 }

How to do the Recursive SELECT query in MySQL?

Building off of Master DJon

Here is simplified function which provides the added utility of returning depth (in case you want to use logic to include the parent task or search at a specific depth)

DELIMITER $$
FUNCTION `childDepth`(pParentId INT, pId INT) RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
DECLARE depth,curId int;
SET depth = 0;
SET curId = pId;

WHILE curId IS not null AND curId <> pParentId DO
    SELECT ParentId from test where id=curId limit 1 into curId;
    SET depth = depth + 1;
END WHILE;

IF curId IS NULL THEN
    set depth = -1;
END IF;

RETURN depth;
END$$

Usage:

select * from test where childDepth(1, id) <> -1;

Why would you use String.Equals over ==?

There's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. It seems like the use is pretty much the same.

Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant."

What is “2's Complement”?

It is a clever means of encoding negative integers in such a way that approximately half of the combination of bits of a data type are reserved for negative integers, and the addition of most of the negative integers with their corresponding positive integers results in a carry overflow that leaves the result to be binary zero.

So, in 2's complement if one is 0x0001 then -1 is 0x1111, because that will result in a combined sum of 0x0000 (with an overflow of 1).

What do parentheses surrounding an object/function/class declaration mean?

See this question. The first set of parenthesis aren't necessary if you use a function name, but a nameless function requires this construct and the parenthesis serve for coders to realize that they've viewing a self-invoking function when browsing the code (see one blogger's best-practices recommendation).

Echo newline in Bash prints literal \n

Try

echo -e "hello\nworld"
hello
world

worked for me in nano editor.

From the man page:

-e enable interpretation of backslash escapes

How can I post data as form data instead of a request payload?

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Hope this helps.

How to upgrade safely php version in wamp server

For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/

I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.

Enjoy!

Trouble setting up git with my GitHub Account error: could not lock config file

This could be caused by the presence of ~/.gitconfig.lock It's possible this file could be an artifact of a previously running git that was aborted for some reason, e.g. ansible timed out or ^C

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

How to log cron jobs?

If you'd still like to check your cron jobs you should provide a valid email account when setting the Cron jobs in cPanel.

When you specify a valid email you will receive the output of the cron job that is executed. Thus you will be able to check it and make sure everything has been executed correctly. Note that you will not receive an email if there is no output from the cron job command.

Please bear in mind that you will receive an email for each of the executed cron jobs. This may flood your inbox in case your crons run too often

Matrix Multiplication in pure Python?

All the below answers would return you the list.Your need to convert it to matrix

def MATMUL(X, Y):
    rows_A = len(X)
    cols_A = len(X[0])
    rows_B = len(Y)
    cols_B = len(Y[0])

    if cols_A != rows_B:
        print "Matrices are not compatible to Multiply. Check condition C1==R2"
        return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]

    C = numpy.matrix(C).reshape(len(A),len(B[0]))

    return C

How do I read the first line of a file using cat?

Adding one more obnoxious alternative to the list:

perl -pe'$.<=1||last' file
# or 
perl -pe'$.<=1||last' < file
# or
cat file | perl -pe'$.<=1||last'

UIButton: set image for selected-highlighted state

Swift 3

// Default state (previously `.Normal`)
button.setImage(UIImage(named: "image1"), for: [])

// Highlighted
button.setImage(UIImage(named: "image2"), for: .highlighted)

// Selected
button.setImage(UIImage(named: "image3"), for: .selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), for: [.selected, .highlighted])

To set the background image we can use setBackgroundImage(_:for:)

Swift 2.x

// Normal
button.setImage(UIImage(named: "image1"), forState: .Normal)

// Highlighted
button.setImage(UIImage(named: "image2"), forState: .Highlighted)

// Selected
button.setImage(UIImage(named: "image3"), forState: .Selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), forState: [.Selected, .Highlighted])

inherit from two classes in C#

If you want to literally use the method code from A and B you can make your C class contain an instance of each. If you code against interfaces for A and B then your clients don't need to know you're giving them a C rather than an A or a B.

interface IA { void SomeMethodOnA(); }
interface IB { void SomeMethodOnB(); }
class A : IA { void SomeMethodOnA() { /* do something */ } }
class B : IB { void SomeMethodOnB() { /* do something */ } }
class C : IA, IB
{
    private IA a = new A();
    private IB b = new B();
    void SomeMethodOnA() { a.SomeMethodOnA(); }
    void SomeMethodOnB() { b.SomeMethodOnB(); }
}

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

dotnet ef not found in .NET Core 3

Global tools can be installed in the default directory or in a specific location. The default directories are:

  • Linux/macOS ---> $HOME/.dotnet/tools

  • Windows ---> %USERPROFILE%\.dotnet\tools

If you're trying to run a global tool, check that the PATH environment variable on your machine contains the path where you installed the global tool and that the executable is in that path.

Troubleshoot .NET Core tool usage issues

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How can one pull the (private) data of one's own Android app?

Starting form Dave Thomas script I've been able to write my own solution to overcome 2 problems:

  1. my backup was containing only the manifest file
  2. binary files got with Dave Thomas where unreadable

This is my script, that copies app data to sdcard and then pull it

#Check we have one connected device
adb devices -l | grep -e 'device\b' > /dev/null

if [ $? -gt 0 ]; then
    echo "No device connected to adb."
    exit 1
fi

# Set filename or directory to pull from device
# Set package name we will run as
while getopts f:p: opt; do
    case $opt in
        f)
            fileToPull=$OPTARG
            ;;
        p)
            packageName=$OPTARG
            ;;
    esac
done;

# Block package name arg from being blank
if [ -z "$packageName" ]; then
    echo "Please specify package name to run as when pulling file"
    exit 1
fi

# Check package exists
adb shell pm list packages | grep "$packageName" > /dev/null
if [ $? -gt 0 ]; then
    echo "Package name $packageName does not exist on device"
    exit 1
fi

    adb shell "run-as $packageName cp -r /data/data/$packageName/ /sdcard/$packageName"
    adb pull /sdcard/$packageName
    adb shell rm -rf /sdcard/$packageName

Android fade in and fade out with ImageView

Have you thought of using TransitionDrawable instead of custom animations? https://developer.android.com/reference/android/graphics/drawable/TransitionDrawable.html

One way to achieve what you are looking for is:

// create the transition layers
Drawable[] layers = new Drawable[2];
layers[0] = new BitmapDrawable(getResources(), firstBitmap);
layers[1] = new BitmapDrawable(getResources(), secondBitmap);

TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
imageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(FADE_DURATION);

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Composer Update Laravel

The following works for me:

composer update --no-scripts

Django auto_now and auto_now_add

But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods.

A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion).

from django.db import models
from django.utils import timezone


class AutoDateTimeField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        return timezone.now()

#usage
created_at = models.DateField(default=timezone.now)
updated_at = models.AutoDateTimeField(default=timezone.now)

How can I close a window with Javascript on Mozilla Firefox 3?

This code will work it out definitely

function closing() {
var answer = confirm("Do you wnat to close this window ?");
    if (answer){
        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
        window.close();
    }
    else{
        stop;
    }
}

Android findViewById() in Custom View

You can try something like this:

Inside customview constructor:

mContext = context;

Next inside customview you can call:

((MainActivity) mContext).updateText( text );

Inside MainAcivity define:

public void updateText(final String text) {

     TextView txtView = (TextView) findViewById(R.id.text);
     txtView.setText(text);
}

It works for me.

How to make EditText not editable through XML in Android?

As mentioned in other answers, you can do a setEnabled(false) but since you are asking how to set it via XML, here is how to do it.

Add the following attribute to your EditText:

android:enabled="false"

How can I create objects while adding them into a vector?

Question 1:

   vectorOfGamers.push_back(Player)

This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:

vectorOfGamers.push_back(Player(name, id)) 
  //^^assuming name and id are parameters to the vector, call Player constructor
  //^^In other words, push `instance`  of Player class into vector

Question 2:

These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?

Yes you can. You can create a vector of pointers that points to the base class Gamer. A good choice is to use a vector of smart_pointer, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?

Testing whether a value is odd or even

How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)

function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Time in milliseconds in C

A couple of things might affect the results you're seeing:

  1. You're treating clock_t as a floating-point type, I don't think it is.
  2. You might be expecting (1^4) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.
  3. Since the XOR is of constants, it's probably folded by the compiler, meaning it doesn't add a lot of work at runtime.
  4. Since the output is buffered (it's just formatting the string and writing it to memory), it completes very quickly indeed.

You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.

If you have it, try adding a call to sleep() between the start/stop snapshots. Note that sleep() is POSIX though, not standard C.

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

Having services in React application

I needed some formatting logic to be shared across multiple components and as an Angular developer also naturally leaned towards a service.

I shared the logic by putting it in a separate file

function format(input) {
    //convert input to output
    return output;
}

module.exports = {
    format: format
};

and then imported it as a module

import formatter from '../services/formatter.service';

//then in component

    render() {

        return formatter.format(this.props.data);
    }

Incrementing a date in JavaScript

Two methods:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

How do I clone a single branch in Git?

git clone <url> --branch <branch> --single-branch

Just put in URL and branch name.

How to make child divs always fit inside parent div?

I had a similar problem, but in my case, I have content in my div that height-wise will exceed the boundaries of the parent div. When it does, I want it to auto-scroll. I was able to accomplish this by using

.vscrolling_container { height: 100%; overflow: auto; }

What is the instanceof operator in JavaScript?

What is it?

Javascript is a prototypal language which means it uses prototypes for 'inheritance'. the instanceof operator tests if a constructor function's prototype propertype is present in the __proto__ chain of an object. This means that it will do the following (assuming that testObj is a function object):

obj instanceof testObj;
  1. Check if prototype of the object is equal to the prototype of the constructor: obj.__proto__ === testObj.prototype >> if this is true instanceof will return true.
  2. Will climb up the prototype chain. For example: obj.__proto__.__proto__ === testObj.prototype >> if this is true instanceof will return true.
  3. Will repeat step 2 until the full prototype of object is inspected. If nowhere on the prototype chain of the object is matched with testObj.prototype then instanceof operator will return false.

Example:

_x000D_
_x000D_
function Person(name) {_x000D_
  this.name = name;_x000D_
}_x000D_
var me = new Person('Willem');_x000D_
_x000D_
console.log(me instanceof Person); // true_x000D_
// because:  me.__proto__ === Person.prototype  // evaluates true_x000D_
_x000D_
console.log(me instanceof Object); // true_x000D_
// because:  me.__proto__.__proto__ === Object.prototype  // evaluates true_x000D_
_x000D_
console.log(me instanceof Array);  // false_x000D_
// because: Array is nowhere on the prototype chain
_x000D_
_x000D_
_x000D_

What problems does it solve?

It solved the problem of conveniently checking if an object derives from a certain prototype. For example, when a function recieves an object which can have various prototypes. Then, before using methods from the prototype chain, we can use the instanceof operator to check whether the these methods are on the object.

Example:

_x000D_
_x000D_
function Person1 (name) {_x000D_
  this.name = name;_x000D_
}_x000D_
_x000D_
function Person2 (name) {_x000D_
  this.name = name;_x000D_
}_x000D_
_x000D_
Person1.prototype.talkP1 = function () {_x000D_
  console.log('Person 1 talking');_x000D_
}_x000D_
_x000D_
Person2.prototype.talkP2 = function () {_x000D_
  console.log('Person 2 talking');_x000D_
}_x000D_
_x000D_
_x000D_
function talk (person) {_x000D_
  if (person instanceof Person1) {_x000D_
    person.talkP1();_x000D_
  }_x000D_
  _x000D_
  if (person instanceof Person2) {_x000D_
    person.talkP2();_x000D_
  }_x000D_
  _x000D_
  _x000D_
}_x000D_
_x000D_
const pers1 = new Person1 ('p1');_x000D_
const pers2 = new Person2 ('p2');_x000D_
_x000D_
talk(pers1);_x000D_
talk(pers2);
_x000D_
_x000D_
_x000D_

Here in the talk() function first is checked if the prototype is located on the object. After this the appropriate method is picked to execute. Not doing this check could result in executing a method which doesn't exist and thus a reference error.

When is it appropriate and when not?

We kind of already went over this. Use it when you are in need of checking the prototype of an object before doing something with it.

Why does an image captured using camera intent gets rotated on some devices on Android?

There is a more simple command to fix this error.

Just simply add after yourImageView.setBitmap(bitmap); this yourImageView.setRotation(90);

This fixed mine. Hope it helps !

Conda environments not showing up in Jupyter Notebook

This has been so frustrating, My problem was that within a newly constructed conda python36 environment, jupyter refused to load “seaborn” - even though seaborn was installed within that environment. It seemed to be able to import plenty of other files from the same environment — for example numpy and pandas but just not seaborn. I tried many of the fixes suggested here and on other threads without success. Until I realised that Jupyter was not running kernel python from within that environment but running the system python as kernel. Even though a decent looking kernel and kernel.json were already present in the environment. It was only after reading this part of the ipython documentation: https://ipython.readthedocs.io/en/latest/install/kernel_install.html#kernels-for-different-environments and using these commands:

source activate other-env
python -m ipykernel install --user --name other-env --display-name "Python (other-env)"

I was able to get everything going nicely. (I didn’t actually use the —user variable).

One thing I have not yet figured is how to set the default python to be the "Python (other-env)" one. At present an existing .ipynb file opened from the Home screen will use the system python. I have to use the Kernel menu “Change kernel” to select the environment python.