Programs & Examples On #Login script

A Login Script is a batch script for fine-tuning computer workstation logins. Please don't use this tag for web site login code, such as PHP.

Where does the @Transactional annotation belong?

Or does it make sense to annotate both "layers"? - doesn't it make sense to annotate both the service layer and the dao layer - if one wants to make sure that DAO method is always called (propagated) from a service layer with propagation "mandatory" in DAO. This would provide some restriction for DAO methods from being called from UI layer (or controllers). Also - when unit testing DAO layer in particular - having DAO annotated will also ensure it is tested for transactional functionality.

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Using GSON to parse a JSON array

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
    "number": "...",
    "title": ".." ,  //<- see that comma?
}

If you remove them your data will become

[
    {
        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"
    }
]

and

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

should work fine.

Create an empty list in python with certain size

I'm a bit surprised that the easiest way to create an initialised list is not in any of these answers. Just use a generator in the list function:

list(range(9))

How to parse JSON Array (Not Json Object) in Android

A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this website It's called jsonschema2pojo and does exactly that:

You give it your json and it generates a java object that can paste in your project. You can select GSON to annotate your variables, so extracting the object from your json gets even easier!

How to convert an Instant to a date format?

An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).

To print it as a date/time, you first need to decide which timezone to use. For example:

System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));

This will print the date/time in iso format: 2015-06-02T10:15:02.325

If you want a different format you can use a formatter:

LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);

Changing specific text's color using NSMutableAttributedString in Swift

Swift 4.1

NSAttributedStringKey.foregroundColor

for example if you want to change font in NavBar:

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

I'd suggest using RVM it allows you have multiple versions of Ruby/Rails installed with gem profiles and basically keep all your gems contained from one another. You may want to check out a similar post How can I install Ruby on Rails 3 on OSX

"Instantiating" a List in Java?

A List in java is an interface that defines certain qualities a "list" must have. Specific list implementations, such as ArrayList implement this interface and flesh out how the various methods are to work. What are you trying to accomplish with this list? Most likely, one of the built-in lists will work for you.

How do I join two lines in vi?

In Vim you can also use gJ.

??

Can I have multiple primary keys in a single table?

Primary Key is very unfortunate notation, because of the connotation of "Primary" and the subconscious association in consequence with the Logical Model. I thus avoid using it. Instead I refer to the Surrogate Key of the Physical Model and the Natural Key(s) of the Logical Model.

It is important that the Logical Model for every Entity have at least one set of "business attributes" which comprise a Key for the entity. Boyce, Codd, Date et al refer to these in the Relational Model as Candidate Keys. When we then build tables for these Entities their Candidate Keys become Natural Keys in those tables. It is only through those Natural Keys that users are able to uniquely identify rows in the tables; as surrogate keys should always be hidden from users. This is because Surrogate Keys have no business meaning.

However the Physical Model for our tables will in many instances be inefficient without a Surrogate Key. Recall that non-covered columns for a non-clustered index can only be found (in general) through a Key Lookup into the clustered index (ignore tables implemented as heaps for a moment). When our available Natural Key(s) are wide this (1) widens the width of our non-clustered leaf nodes, increasing storage requirements and read accesses for seeks and scans of that non-clustered index; and (2) reduces fan-out from our clustered index increasing index height and index size, again increasing reads and storage requirements for our clustered indexes; and (3) increases cache requirements for our clustered indexes. chasing other indexes and data out of cache.

This is where a small Surrogate Key, designated to the RDBMS as "the Primary Key" proves beneficial. When set as the clustering key, so as to be used for key lookups into the clustered index from non-clustered indexes and foreign key lookups from related tables, all these disadvantages disappear. Our clustered index fan-outs increase again to reduce clustered index height and size, reduce cache load for our clustered indexes, decrease reads when accessing data through any mechanism (whether index scan, index seek, non-clustered key lookup or foreign key lookup) and decrease storage requirements for both clustered and nonclustered indexes of our tables.

Note that these benefits only occur when the surrogate key is both small and the clustering key. If a GUID is used as the clustering key the situation will often be worse than if the smallest available Natural Key had been used. If the table is organized as a heap then the 8-byte (heap) RowID will be used for key lookups, which is better than a 16-byte GUID but less performant than a 4-byte integer.

If a GUID must be used due to business constraints than the search for a better clustering key is worthwhile. If for example a small site identifier and 4-byte "site-sequence-number" is feasible then that design might give better performance than a GUID as Surrogate Key.

If the consequences of a heap (hash join perhaps) make that the preferred storage then the costs of a wider clustering key need to be balanced into the trade-off analysis.

Consider this example::

ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

where the tuple "(P_Id,LastName)" requires a uniqueness constraint, and may be a lengthy Unicode LastName plus a 4-byte integer, it would be desirable to (1) declaratively enforce this constraint as "ADD CONSTRAINT pk_PersonID UNIQUE NONCLUSTERED (P_Id,LastName)" and (2) separately declare a small Surrogate Key to be the "Primary Key" of a clustered index. It is worth noting that Anita possibly only wishes to add the LastName to this constraint in order to make that a covered field, which is unnecessary in a clustered index because ALL fields are covered by it.

The ability in SQL Server to designate a Primary Key as nonclustered is an unfortunate historical circumstance, due to a conflation of the meaning "preferred natural or candidate key" (from the Logical Model) with the meaning "lookup key in storage" from the Physical Model. My understanding is that originally SYBASE SQL Server always used a 4-byte RowID, whether into a heap or a clustered index, as the "lookup key in storage" from the Physical Model.

How to set session timeout dynamically in Java web applications?

Is there a way to set the session timeout programatically

There are basically three ways to set the session timeout value:

  • by using the session-timeout in the standard web.xml file ~or~
  • in the absence of this element, by getting the server's default session-timeout value (and thus configuring it at the server level) ~or~
  • programmatically by using the HttpSession. setMaxInactiveInterval(int seconds) method in your Servlet or JSP.

But note that the later option sets the timeout value for the current session, this is not a global setting.

Append TimeStamp to a File Name

I prefer to use:

string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";

What does ToFileTime() do?

Converts the value of the current DateTime object to a Windows file time.

public long ToFileTime()

A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.

Source: MSDN documentation - DateTime.ToFileTime Method

Is there a way to make npm install (the command) to work behind proxy?

vim ~/.npmrc in your Linux machine and add following. Don't forget to add registry part as this cause failure in many cases.

proxy=http://<proxy-url>:<port>
https-proxy=https://<proxy-url>:<port>
registry=http://registry.npmjs.org/

What is an index in SQL?

A clustered index is like the contents of a phone book. You can open the book at 'Hilditch, David' and find all the information for all of the 'Hilditch's right next to each other. Here the keys for the clustered index are (lastname, firstname).

This makes clustered indexes great for retrieving lots of data based on range based queries since all the data is located next to each other.

Since the clustered index is actually related to how the data is stored, there is only one of them possible per table (although you can cheat to simulate multiple clustered indexes).

A non-clustered index is different in that you can have many of them and they then point at the data in the clustered index. You could have e.g. a non-clustered index at the back of a phone book which is keyed on (town, address)

Imagine if you had to search through the phone book for all the people who live in 'London' - with only the clustered index you would have to search every single item in the phone book since the key on the clustered index is on (lastname, firstname) and as a result the people living in London are scattered randomly throughout the index.

If you have a non-clustered index on (town) then these queries can be performed much more quickly.

Hope that helps!

Finding square root without using sqrt function?

//long division method.
#include<iostream>
using namespace std;
int main() {
int n, i = 1, divisor, dividend, j = 1, digit;
cin >> n;
while (i * i < n) {
    i = i + 1;
}
i = i - 1;
cout << i << '.';

divisor  = 2 * i;
dividend = n - (i * i );
while( j <= 5) {
    dividend = dividend * 100;
    digit = 0;
    while ((divisor * 10 + digit) * digit < dividend) {
        digit = digit + 1;
    }
    digit = digit  - 1;
    cout << digit;
    dividend = dividend - ((divisor * 10 + digit) * digit);
    divisor = divisor * 10 + 2*digit;
    j = j + 1;
}
cout << endl;
return 0;
}

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

Can you recommend a free light-weight MySQL GUI for Linux?

RazorSQL vote here too. It is not free, but it's not expensive ($70 for a perpetual license and 1 year of free upgrades).

If you use it for work, it will pay for itself quickly. I was jumping between MySQL GUI tools, SQL Server and Informix DBAccess, some of them through VMs because I use a Mac for development. Having a single tool to connect to any database out there is pretty nice. It is also highly customizable, and very reliable.

How do I comment on the Windows command line?

Lines starting with "rem" (from the word remarks) are comments:

rem comment here
echo "hello"

Google Chrome Full Black Screen

For Ubuntu users - Instead of changing the settings within the Chrome browser, which risks propagating them to other machines that do not have that issue, it is best to just edit the .desktop launcher:

Open the appropriate file for your situation.

/usr/share/applications/google-chrome.desktop
/usr/share/applications/chromium-browser.desktop

Just append the flag (-disable-gpu) to the end of the three Exec= lines in your file.

...
Exec=/usr/bin/google-chrome-stable %U -disable-gpu
...
Exec=/usr/bin/google-chrome-stable -disable-gpu
...
Exec=/usr/bin/google-chrome-stable --incognito -disable-gpu
...

PHP - Get bool to echo false when false

I like this one to print that out

var_dump ($var);

How to change file encoding in NetBeans?

There is an old Bugreport concerning this issue.

How to display Base64 images in HTML?

If you have PHP on the back-end, you can use this code:

$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="'.$src.'">';

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

Getting current date and time in JavaScript

This little code is easy and works everywhere.

<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>

there is room to design

illegal character in path

I usualy would enter the path like this ....

FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe"); 

Did you register the @ at the beginning of the string? ;-)

Regex to test if string begins with http:// or https://

(http|https)?:\/\/(\S+)

This works for me

Not a regex specialist, but i will try to explain the awnser.

(http|https) : Parenthesis indicates a capture group, "I" a OR statement.

\/\/ : "\" allows special characters, such as "/"

(\S+) : Anything that is not whitespace until the next whitespace

How to set a selected option of a dropdown list control using angular JS

I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.

If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:

JS:

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];

HTML:

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

This would leave the "b" item to be selected.

How do I use T-SQL's Case/When?

As soon as a WHEN statement is true the break is implicit.

You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

More information here: break in case statement in T-SQL

Output data with no column headings using PowerShell

If you use "format-table" you can use -hidetableheaders

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

You are returning or inflating layout twice, just check to see if you only inflate once.

How to add a "sleep" or "wait" to my Lua Script?

wxLua has three sleep functions:

local wx = require 'wx'
wx.wxSleep(12)   -- sleeps for 12 seconds
wx.wxMilliSleep(1200)   -- sleeps for 1200 milliseconds
wx.wxMicroSleep(1200)   -- sleeps for 1200 microseconds (if the system supports such resolution)

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

How to create UILabel programmatically using Swift?

You can create a label using the code below. Updated.

let yourLabel: UILabel = UILabel()
yourLabel.frame = CGRect(x: 50, y: 150, width: 200, height: 21)
yourLabel.backgroundColor = UIColor.orange
yourLabel.textColor = UIColor.black
yourLabel.textAlignment = NSTextAlignment.center
yourLabel.text = "test label"
self.view.addSubview(yourLabel)

How to tell Jackson to ignore a field during serialization if its value is null?

Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:

From documentation:
com.fasterxml.jackson.annotation.JsonInclude

@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.

To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
   public Map<String,String> entries;
}

Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0

Python equivalent of a given wget command

TensorFlow makes life easier. file path gives us the location of downloaded file.

import tensorflow as tf
tf.keras.utils.get_file(origin='https://storage.googleapis.com/tf-datasets/titanic/train.csv',
                                    fname='train.csv',
                                    untar=False, extract=False)

Why doesn't Dijkstra's algorithm work for negative weight edges?

Dijkstra's Algorithm assumes that all edges are positive weighted and this assumption helps the algorithm run faster ( O(V^2) ) than others which take into account the possibility of negative edges (e.g bellman ford's algorithm with complexity of O(V^3)).

This algorithm wont give the correct result in the following case where A is the source vertex:

enter image description here

Also, Dijkstra's Algorithm may sometimes give correct solution even if there are negative edges. Following is an example of such a case:

enter image description here

It will never detect a negative cycle and always produce a result which will always be incorrect if a negative weight cycle is reachable from the source, as in such a case there exists no shortest path in the graph from the source vertex.

ValueError when checking if variable is None or numpy.array

Using not a to test whether a is None assumes that the other possible values of a have a truth value of True. However, most NumPy arrays don't have a truth value at all, and not cannot be applied to them.

If you want to test whether an object is None, the most general, reliable way is to literally use an is check against None:

if a is None:
    ...
else:
    ...

This doesn't depend on objects having a truth value, so it works with NumPy arrays.

Note that the test has to be is, not ==. is is an object identity test. == is whatever the arguments say it is, and NumPy arrays say it's a broadcasted elementwise equality comparison, producing a boolean array:

>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:

# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
    ...
else:
    ...

You can also use isinstance, which will also return True for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix is, you may not actually want this:

# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
    ...
else:
    ...    

Windows error 2 occured while loading the Java VM

For me it works a deleting "C:\ProgramData\Oracle\Java\javapath" in my system enviroment PATH variable

Edit: If you don't have that variable or it does not work you can directly delete or rename the directory "C:\ProgramData\Oracle\Java\javapath"

How to make responsive table

Basically

A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }
}

HTML

<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

Apply CSS to jQuery Dialog Buttons

If still noting is working for you add the following styles on your page style sheet

.ui-widget-content .ui-state-default {
  border: 0px solid #d3d3d3;
  background: #00ACD6 50% 50% repeat-x;
  font-weight: normal;
  color: #fff;
}

It will change the background color of the dialog buttons.

How do I pass along variables with XMLHTTPRequest

If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!

It is also possible to use POST, if you dont want your variables to be visible.

A complete sample would be:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

To test this, (using PHP) you could var_dump $_GET to see what you retrieve.

$(this).serialize() -- How to add a value?

You can write an extra function to process form data and you should add your nonform data as the data valu in the form.seethe example :

<form method="POST" id="add-form">
    <div class="form-group required ">
        <label for="key">Enter key</label>
        <input type="text" name="key" id="key"  data-nonformdata="hai"/>
    </div>
    <div class="form-group required ">
        <label for="name">Ente Name</label>
        <input type="text" name="name" id="name"  data-nonformdata="hello"/>
    </div>
    <input type="submit" id="add-formdata-btn" value="submit">
</form>

Then add this jquery for form processing

<script>
$(document).onready(function(){
    $('#add-form').submit(function(event){
        event.preventDefault();
        var formData = $("form").serializeArray();
        formData = processFormData(formData);
        // write further code here---->
    });
});
processFormData(formData)
{
    var data = formData;
    data.forEach(function(object){
        $('#add-form input').each(function(){
            if(this.name == object.name){
                var nonformData = $(this).data("nonformdata");
                formData.push({name:this.name,value:nonformData});
            }
        });
    });
    return formData;
}

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

to

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

How to create a self-signed certificate with OpenSSL

I can`t comment so I add a separate answer. I tried to create a self-signed certificate for NGINX and it was easy, but when I wanted to add it to Chrome white list I had a problem. And my solution was to create a Root certificate and signed a child certificate by it.

So step by step. Create file config_ssl_ca.cnf Notice, config file has an option basicConstraints=CA:true which means that this certificate is supposed to be root.

This is a good practice, because you create it once and can reuse.

[ req ]
default_bits = 2048

prompt = no
distinguished_name=req_distinguished_name
req_extensions = v3_req

[ req_distinguished_name ]
countryName=UA
stateOrProvinceName=root region
localityName=root city
organizationName=Market(localhost)
organizationalUnitName=roote department
commonName=market.localhost
[email protected]

[ alternate_names ]
DNS.1        = market.localhost
DNS.2        = www.market.localhost
DNS.3        = mail.market.localhost
DNS.4        = ftp.market.localhost
DNS.5        = *.market.localhost

[ v3_req ]
keyUsage=digitalSignature
basicConstraints=CA:true
subjectKeyIdentifier = hash
subjectAltName = @alternate_names

Next config file for your child certificate will be call config_ssl.cnf.

[ req ]
default_bits = 2048

prompt = no
distinguished_name=req_distinguished_name
req_extensions = v3_req

[ req_distinguished_name ]
countryName=UA
stateOrProvinceName=Kyiv region
localityName=Kyiv
organizationName=market place
organizationalUnitName=market place department
commonName=market.localhost
[email protected]

[ alternate_names ]
DNS.1        = market.localhost
DNS.2        = www.market.localhost
DNS.3        = mail.market.localhost
DNS.4        = ftp.market.localhost
DNS.5        = *.market.localhost

[ v3_req ]
keyUsage=digitalSignature
basicConstraints=CA:false
subjectAltName = @alternate_names
subjectKeyIdentifier = hash

The first step - create Root key and certificate

openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -out ca.crt -days 365 -config config_ssl_ca.cnf

The second step creates child key and file CSR - Certificate Signing Request. Because the idea is to sign the child certificate by root and get a correct certificate

openssl genrsa -out market.key 2048
openssl req -new -sha256 -key market.key -config config_ssl.cnf -out market.csr

Open Linux terminal and do this command

echo 00 > ca.srl
touch index.txt

The ca.srl text file containing the next serial number to use in hex. Mandatory. This file must be present and contain a valid serial number.

Last Step, crate one more config file and call it config_ca.cnf

# we use 'ca' as the default section because we're usign the ca command
[ ca ]
default_ca = my_ca

[ my_ca ]
#  a text file containing the next serial number to use in hex. Mandatory.
#  This file must be present and contain a valid serial number.
serial = ./ca.srl

# the text database file to use. Mandatory. This file must be present though
# initially it will be empty.
database = ./index.txt

# specifies the directory where new certificates will be placed. Mandatory.
new_certs_dir = ./

# the file containing the CA certificate. Mandatory
certificate = ./ca.crt

# the file contaning the CA private key. Mandatory
private_key = ./ca.key

# the message digest algorithm. Remember to not use MD5
default_md = sha256

# for how many days will the signed certificate be valid
default_days = 365

# a section with a set of variables corresponding to DN fields
policy = my_policy

# MOST IMPORTANT PART OF THIS CONFIG
copy_extensions = copy

[ my_policy ]
# if the value is "match" then the field value must match the same field in the
# CA certificate. If the value is "supplied" then it must be present.
# Optional means it may be present. Any fields not mentioned are silently
# deleted.
countryName = match
stateOrProvinceName = supplied
organizationName = supplied
commonName = market.localhost
organizationalUnitName = optional
commonName = supplied

You may ask, why so difficult, why we must create one more config to sign child certificate by root. The answer is simple because child certificate must have a SAN block - Subject Alternative Names. If we sign the child certificate by "openssl x509" utils, the Root certificate will delete the SAN field in child certificate. So we use "openssl ca" instead of "openssl x509" to avoid the deleting of the SAN field. We create a new config file and tell it to copy all extended fields copy_extensions = copy.

openssl ca -config config_ca.cnf -out market.crt -in market.csr

The program asks you 2 questions:

  1. Sign the certificate? Say "Y"
  2. 1 out of 1 certificate requests certified, commit? Say "Y"

In terminal you can see a sentence with the word "Database", it means file index.txt which you create by the command "touch". It will contain all information by all certificates you create by "openssl ca" util. To check the certificate valid use:

openssl rsa -in market.key -check

If you want to see what inside in CRT:

openssl x509 -in market.crt -text -noout

If you want to see what inside in CSR:

openssl req -in market.csr -noout -text 

Load text file as strings using numpy.loadtxt()

Use genfromtxt instead. It's a much more general method than loadtxt:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

Using the file col.txt:

foo bar
cat dog
man wine

This gives:

[['foo' 'bar']
 ['cat' 'dog']
 ['man' 'wine']]

If you expect that each row has the same number of columns, read the first row and set the attribute filling_values to fix any missing rows.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does the COLLATE clause of CREATE DATABASE do?", then:

The COLLATE {collation_name} clause of the CREATE DATABASE statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.

Server (i.e. Instance)-level controls:

  • Database-level Collation for system Databases: master, model, msdb, and tempdb.
  • Due to controlling the DB-level Collation of tempdb, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.
  • Due to controlling the DB-level Collation of master, it is then the Collation used for Server-level data, such as Database names (i.e. name column in sys.databases), Login names, etc.
  • Handling of parameter / variable names
  • Handling of cursor names
  • Handling of GOTO labels
  • Default Collation used for newly created Databases when the COLLATE clause is missing

Database-level controls:

  • Default Collation used for newly created string columns (CHAR, VARCHAR, NCHAR, NVARCHAR, TEXT, and NTEXT -- but don't use TEXT or NTEXT) when the COLLATE clause is missing from the column definition. This goes for both CREATE TABLE and ALTER TABLE ... ADD statements.
  • Default Collation used for string literals (i.e. 'some text') and string variables (i.e. @StringVariable). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.
  • The Collation used for Database-level meta-data, such as object names (i.e. sys.objects), column names (i.e. sys.columns), index names (i.e. sys.indexes), etc.
  • The Collation used for Database-level objects: tables, columns, indexes, etc.

Also:

  • ASCII is an encoding which is 8-bit (for common usage; technically "ASCII" is 7-bit with character values 0 - 127, and "ASCII Extended" is 8-bit with character values 0 - 255). This group is the same across cultures.
  • The Code Page is the "extended" part of Extended ASCII, and controls which characters are used for values 128 - 255. This group varies between each culture.
  • Latin1 does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR) map those same 128 values to the same characters.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does this particular collation do?", then:

  • Because the name start with SQL_, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.

    Windows collations (those with names not starting with SQL_) are newer, more functional, have consistent sorting between VARCHAR and NVARCHAR for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.

  • Latin1_General is the culture / locale.
    • For NCHAR, NVARCHAR, and NTEXT data this determines the linguistic rules used for sorting and comparison.
    • For CHAR, VARCHAR, and TEXT data (columns, literals, and variables) this determines the:
      • linguistic rules used for sorting and comparison.
      • code page used to encode the characters. For example, Latin1_General collations use code page 1252, Hebrew collations use code page 1255, and so on.
  • CP{code_page} or {version}

    • For SQL Server collations: CP{code_page}, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.
    • For Windows collations: {version}, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80 (meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90 (for SQL Server 2005, which is version 9.0), most are 100 (for SQL Server 2008, version 10.0), and a small set has 140 (for SQL Server 2017, version 14.0).

      I said "for the most part" because the collations ending in _SC were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90 and 100 collations, but only starting in SQL Server 2012.

  • Next you have the sensitivities, that can be in any combination of the following, but always specified in this order:
    • CS = case-sensitive or CI = case-insensitive
    • AS = accent-sensitive or AI = accent-insensitive
    • KS = Kana type-sensitive or missing = Kana type-insensitive
    • WS = width-sensitive or missing = width insensitive
    • VSS = variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitive
  • Optional last piece:

    • _SC at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC at the end (or _140_ in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation.
    • _BIN or _BIN2 at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC. _BIN is the older style, and _BIN2 is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2. For details on the differences between _BIN and _BIN2, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2).
    • _UTF8 is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR and CHAR datatypes (but not the deprecated TEXT datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC in their name, and version 140 collations). There is also a single binary _UTF8 collation (_BIN2, not _BIN).

      PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR data (columns, variables, string literals) with a _UTF8 collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8 collation with either VARCHAR data using non-_UTF8 collations or NVARCHAR data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?

How to pass parameters to a partial view in ASP.NET MVC?

Use this overload (RenderPartialExtensions.RenderPartial on MSDN):

public static void RenderPartial(
    this HtmlHelper htmlHelper,
    string partialViewName,
    Object model
)

so:

@{Html.RenderPartial(
    "FullName",
    new { firstName = model.FirstName, lastName = model.LastName});
}

Visual Studio move project to a different folder

It's easy in VS2012; just use the change mapping feature:

  1. Create the folder where you want the solution to be moved to.
  2. Check-in all your project files (if you want to keep you changes), or rollback any checked out files.
  3. Close the solution.
  4. Open the Source Control Explorer.
  5. Right-click the solution, and select "Advanced -> Remove Mapping..."
  6. Change the "Local Folder" value to the one you created in step #1.
  7. Select "Change".
  8. Open the solution by double-clicking it in the source control explorer.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

For what it's worth, here's a general solution to positioning the image centered above the text without using any magic numbers. Note that the following code is outdated and you should probably use one of the updated versions below:

// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered 
//  below the image
CGSize imageSize = button.imageView.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//  above the text
CGSize titleSize = button.titleLabel.frame.size;
button.imageEdgeInsets = UIEdgeInsetsMake(
  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

The following version contains changes to support iOS 7+ that have been recommended in comments below. I haven't tested this code myself, so I'm not sure how well it works or whether it would break if used under previous versions of iOS.

// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered 
//  below the image
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//  above the text
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
button.imageEdgeInsets = UIEdgeInsetsMake(
  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

// increase the content height to avoid clipping
CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);

Swift 5.0 version

extension UIButton {
  func alignVertical(spacing: CGFloat = 6.0) {
    guard let imageSize = imageView?.image?.size,
      let text = titleLabel?.text,
      let font = titleLabel?.font
    else { return }

    titleEdgeInsets = UIEdgeInsets(
      top: 0.0,
      left: -imageSize.width,
      bottom: -(imageSize.height + spacing),
      right: 0.0
    )

    let titleSize = text.size(withAttributes: [.font: font])
    imageEdgeInsets = UIEdgeInsets(
      top: -(titleSize.height + spacing),
      left: 0.0,
      bottom: 0.0,
      right: -titleSize.width
    )

    let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0
    contentEdgeInsets = UIEdgeInsets(
      top: edgeOffset,
      left: 0.0,
      bottom: edgeOffset,
      right: 0.0
    )
  }
}

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

You can use the REASSIGN OWNED command.

Synopsis:

REASSIGN OWNED BY old_role [, ...] TO new_role

This changes all objects owned by old_role to the new role. You don't have to think about what kind of objects that the user has, they will all be changed. Note that it only applies to objects inside a single database. It does not alter the owner of the database itself either.

It is available back to at least 8.2. Their online documentation only goes that far back.

Is there a difference between "==" and "is"?

What's the difference between is and ==?

== and is are different comparison! As others already said:

  • == compares the values of the objects.
  • is compares the references of the objects.

In Python names refer to objects, for example in this case value1 and value2 refer to an int instance storing the value 1000:

value1 = 1000
value2 = value1

enter image description here

Because value2 refers to the same object is and == will give True:

>>> value1 == value2
True
>>> value1 is value2
True

In the following example the names value1 and value2 refer to different int instances, even if both store the same integer:

>>> value1 = 1000
>>> value2 = 1000

enter image description here

Because the same value (integer) is stored == will be True, that's why it's often called "value comparison". However is will return False because these are different objects:

>>> value1 == value2
True
>>> value1 is value2
False

When to use which?

Generally is is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.

You should only use is if you:

  • want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.

  • want to compare a value to a Python constant. The constants in Python are:

    • None
    • True1
    • False1
    • NotImplemented
    • Ellipsis
    • __debug__
    • classes (for example int is int or int is float)
    • there could be additional constants in built-in modules or 3rd party modules. For example np.ma.masked from the NumPy module)

In every other case you should use == to check for equality.

Can I customize the behavior?

There is some aspect to == that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__ method. For example:

class MyClass(object):
    def __init__(self, val):
        self._value = val

    def __eq__(self, other):
        print('__eq__ method called')
        try:
            return self._value == other._value
        except AttributeError:
            raise TypeError('Cannot compare {0} to objects of type {1}'
                            .format(type(self), type(other)))

This is just an artificial example to illustrate that the method is really called:

>>> MyClass(10) == MyClass(10)
__eq__ method called
True

Note that by default (if no other implementation of __eq__ can be found in the class or the superclasses) __eq__ uses is:

class AClass(object):
    def __init__(self, value):
        self._value = value

>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a

So it's actually important to implement __eq__ if you want "more" than just reference-comparison for custom classes!

On the other hand you cannot customize is checks. It will always compare just if you have the same reference.

Will these comparisons always return a boolean?

Because __eq__ can be re-implemented or overridden, it's not limited to return True or False. It could return anything (but in most cases it should return a boolean!).

For example with NumPy arrays the == will return an array:

>>> import numpy as np
>>> np.arange(10) == 2
array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

But is checks will always return True or False!


1 As Aaron Hall mentioned in the comments:

Generally you shouldn't do any is True or is False checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if statement). So doing the is True comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).

Like PEP8 mentions:

Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

String to object in JS

string = "firstName:name1, lastName:last1";

This will work:

var fields = string.split(', '),
    fieldObject = {};

if( typeof fields === 'object') ){
   fields.each(function(field) {
      var c = property.split(':');
      fieldObject[c[0]] = c[1];
   });
}

However it's not efficient. What happens when you have something like this:

string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";

split() will split 'http'. So i suggest you use a special delimiter like pipe

 string = "firstName|name1, lastName|last1";


   var fields = string.split(', '),
        fieldObject = {};

    if( typeof fields === 'object') ){
       fields.each(function(field) {
          var c = property.split('|');
          fieldObject[c[0]] = c[1];
       });
    }

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Download the Android SDK components for offline install

I know this topic is a bit old, but after struggling and waiting a lot to download, Ive changed my DNS settings to use google's one (4.4.4.4 and 8.8.8.8) and it worked!!

My connection is 30mbps from Brazil (Virtua), using isp's provider I was getting 80KB/s and after changing to google dns, I got 2MB/s average.

How to make flutter app responsive according to different screen size?

You can use responsive_helper package to make your app responsive.

It's a very easy method to make your app responsive. Just take a look at the example page and then you'll figure it out how to use it.

Resolving tree conflict

Basically, tree conflicts arise if there is some restructure in the folder structure on the branch. You need to delete the conflict folder and use svn clean once. Hope this solves your conflict.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

I would suggest Travis for Open source project. It's just simple to configure and use.

Simple steps to setup:

  1. Should have GITHUB account and register in Travis CI website using your GITHUB account.
  2. Add .travis.yml file in root of your project. Add Travis as service in your repository settings page.

Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.

Storing sex (gender) in database

I would go with Option 3 but multiple NON NULLABLE bit columns instead of one. IsMale (1=Yes / 0=No) IsFemale (1=Yes / 0=No)

if requried: IsUnknownGender (1=Yes / 0=No) and so on...

This makes for easy reading of the definitions, easy extensibility, easy programmability, no possibility of using values outside the domain and no requirement of a second lookup table+FK or CHECK constraints to lock down the values.

EDIT: Correction, you do need at least one constraint to ensure the set flags are valid.

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

How do I check if a PowerShell module is installed?

try {
    Import-Module SomeModule
    Write-Host "Module exists"
} 
catch {
    Write-Host "Module does not exist"
}

It should be pointed out that your cmdlet Import-Module has no terminating error, therefore the exception isnt being caught so no matter what your catch statement will never return the new statement you have written.

(https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-6

From The Above:

"A terminating error stops a statement from running. If PowerShell does not handle a terminating error in some way, PowerShell also stops running the function or script using the current pipeline. In other languages, such as C#, terminating errors are referred to as exceptions. For more information about errors, see about_Errors."

It should be written as:

Try {
    Import-Module SomeModule -Force -Erroraction stop
    Write-Host "yep"
}
Catch {
    Write-Host "nope"
}

Which returns:

nope

And if you really wanted to be thorough you should add in the other suggested cmdlets Get-Module -ListAvailable -Name and Get-Module -Name to be extra cautious, before running other functions/cmdlets. And if its installed from psgallery or elsewhere you could also run a Find-Module cmdlet to see if there is a new version available.

How to display a list using ViewBag

I had the problem that I wanted to use my ViewBag to send a list of elements through a RenderPartial as the object, and to this you have to do the cast first, I had to cast the ViewBag in the controller and in the View too.

In the Controller:

ViewBag.visitList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)                                                                 
visitaRepo.ObtenerLista().Where(m => m.Id_Contacto == id).ToList()

In the View:

List<CLIENTES_VIP_DB.VISITAS.VISITA> VisitaList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)ViewBag.visitList ;

Split files using tar, gz, zip, or bzip2

You can use the split command with the -b option:

split -b 1024m file.tar.gz

It can be reassembled on a Windows machine using @Joshua's answer.

copy /b file1 + file2 + file3 + file4 filetogether

Edit: As @Charlie stated in the comment below, you might want to set a prefix explicitly because it will use x otherwise, which can be confusing.

split -b 1024m "file.tar.gz" "file.tar.gz.part-"

// Creates files: file.tar.gz.part-aa, file.tar.gz.part-ab, file.tar.gz.part-ac, ...

Edit: Editing the post because question is closed and the most effective solution is very close to the content of this answer:

# create archives
$ tar cz my_large_file_1 my_large_file_2 | split -b 1024MiB - myfiles_split.tgz_
# uncompress
$ cat myfiles_split.tgz_* | tar xz

This solution avoids the need to use an intermediate large file when (de)compressing. Use the tar -C option to use a different directory for the resulting files. btw if the archive consists from only a single file, tar could be avoided and only gzip used:

# create archives
$ gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
# uncompress
$ cat myfile_split.gz_* | gunzip -c > my_large_file

For windows you can download ported versions of the same commands or use cygwin.

What is the difference between instanceof and Class.isAssignableFrom(...)?

This thread provided me some insight into how instanceof differed from isAssignableFrom, so I thought I'd share something of my own.

I have found that using isAssignableFrom to be the only (probably not the only, but possibly the easiest) way to ask one's self if a reference of one class can take instances of another, when one has instances of neither class to do the comparison.

Hence, I didn't find using the instanceof operator to compare assignability to be a good idea when all I had were classes, unless I contemplated creating an instance from one of the classes; I thought this would be sloppy.

MatPlotLib: Multiple datasets on the same scatter plot

You need a reference to an Axes object to keep drawing on the same subplot.

import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()

enter image description here

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

get all characters to right of last dash

string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");

if (indexOfHyphen >= 0)
{
    string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
    Console.WriteLine(contentAfterLastHyphen );
}

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

For files in directory, only echo filename (no path)

You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:

for filename in $(ls /home/user/);
do
    echo $filename
done;

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

Securely storing passwords for use in python script

I typically have a secrets.py that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>. This way you can rely on the operating systems in-built file security system without re-inventing your own.

Using Base64 encoding/decoding is also another way to obfuscate the password though not completely secure

More here - Hiding a password in a python script (insecure obfuscation only)

How to identify platform/compiler from preprocessor macros?

For Mac OS:

#ifdef __APPLE__

For MingW on Windows:

#ifdef __MINGW32__

For Linux:

#ifdef __linux__

For other Windows compilers, check this thread and this for several other compilers and architectures.

How to get numeric position of alphabets in java?

First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.

For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Trigger change event <select> using jquery

$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

Xcode 'CodeSign error: code signing is required'

I use Xcode 4.3.2, and my problem was that in there where a folder inside another folder with the same name, e.g myFolder/myFolder/.

The solution was to change the second folder's name e.g myFolder/_myFolder and the problem was solved.

I hope this can help some one.

What is the difference between Collection and List in Java?

Collection is a high-level interface describing Java objects that can contain collections of other objects. It's not very specific about how they are accessed, whether multiple copies of the same object can exist in the same collection, or whether the order is important. List is specifically an ordered collection of objects. If you put objects into a List in a particular order, they will stay in that order.

And deciding where to use these two interfaces is much less important than deciding what the concrete implementation you use is. This will have implications for the time and space performance of your program. For example, if you want a list, you could use an ArrayList or a LinkedList, each of which is going to have implications for the application. For other collection types (e.g. Sets), similar considerations apply.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Indent List in HTML and CSS

It sounds like some of your styles are being reset.

By default in most browsers, uls and ols have margin and padding added to them.

You can override this (and many do) by adding a line to your css like so

ul, ol {  //THERE MAY BE OTHER ELEMENTS IN THE LIST
    margin:0;
    padding:0;
}

In this case, you would remove the element from this list or add a margin/padding back, like so

ul{
    margin:1em;
}

Example: http://jsfiddle.net/jasongennaro/vbMbQ/1/

How can I list all cookies for the current page with Javascript?

Many people have already mentioned that document.cookie gets you all the cookies (except http-only ones).

I'll just add a snippet to keep up with the times.

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  cookies[name] = value;
  return cookies;
}, {});

The snippet will return an object with cookie names as the keys with cookie values as the values.

Slightly different syntax:

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  return { ...cookies, [name]: value };
}, {});

Check if a Postgres JSON array contains a string

As of PostgreSQL 9.4, you can use the ? operator:

select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';

You can even index the ? query on the "food" key if you switch to the jsonb type instead:

alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';

Of course, you probably don't have time for that as a full-time rabbit keeper.

Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:

d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(#   where food::text = '"carrots"'
d(# );
 Execution time: 3084.927 ms

d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
 Execution time: 1255.501 ms

d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 465.919 ms

d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 256.478 ms

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

Updating and committing only a file's permissions using git version control

@fooMonster article worked for me

# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe    script.sh

As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:

# git update-index --chmod=+x script.sh

commit the changes

# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh

Simple state machine example in C#?

There are 2 popular state machine packages in NuGet.

Appccelerate.StateMachine (13.6K downloads + 3.82K of legacy version (bbv.Common.StateMachine))

StateMachineToolkit (1.56K downloads)

The Appccelerate lib has good documentation, but it does not support .NET 4, so I chose StateMachineToolkit for my project.

Collapse all methods in Visual Studio Code

You should add user settings:

{
    "editor.showFoldingControls": "always",
    "editor.folding": true,
    "editor.foldingStrategy": "indentation", 
}

Find records with a date field in the last 24 hours

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

Unable to install boto3

Try this it works sudo apt install python-pip pip install boto3

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I removed compile 'com.android.support:support-v4:18.0.+' in dependencies, and it works

How to make div background color transparent in CSS

It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/

HTML:

   <button id="toggle-box">toggle</button>
   <div id="box" style="display:none;" ><img src="x"></div>
   <button id="toggle-box2">toggle</button>
   <div id="box2" style="display:none;"><img src="xx"></div>
   <button id="toggle-box3">toggle</button>
   <div id="box3" style="display:none;" ><img src="xxx"></div>

CSS:

#box {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:1;
}
#box2 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
      #box3 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
 body {background-color:#c0c0c0; }

JS:

$('#toggle-box').click().toggle(function() {
$('#box').animate({ width: 'show' });
}, function() {
$('#box').animate({ width: 'hide' });
});

$('#toggle-box2').click().toggle(function() {
$('#box2').animate({ width: 'show' });
}, function() {
$('#box2').animate({ width: 'hide' });
});
$('#toggle-box3').click().toggle(function() {
$('#box3').animate({ width: 'show' });
 }, function() {
$('#box3').animate({ width: 'hide' });
});

And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.

How to get Maven project version to the bash command line

this is an edit from above

cat pom.xml | grep "" | head -n 1 | sed -e "s/version//g" | sed -e "s/\s*[<>/]*//g"

I tested it out on on the cmdline works well

grep "" pom.xml | head -n 1 | sed -e "s/version//g" | sed -e "s/\s*[<>/]*//g"

is another version of the same. I have a need to get the version number in Jenkins CI in k8s without mvn installed so this is most helpful

thanks all.

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How can I save application settings in a Windows Forms application?

If you are planning on saving to a file within the same directory as your executable, here's a nice solution that uses the JSON format:

using System;
using System.IO;
using System.Web.Script.Serialization;

namespace MiscConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = MySettings.Load();
            Console.WriteLine("Current value of 'myInteger': " + settings.myInteger);
            Console.WriteLine("Incrementing 'myInteger'...");
            settings.myInteger++;
            Console.WriteLine("Saving settings...");
            settings.Save();
            Console.WriteLine("Done.");
            Console.ReadKey();
        }

        class MySettings : AppSettings<MySettings>
        {
            public string myString = "Hello World";
            public int myInteger = 1;
        }
    }

    public class AppSettings<T> where T : new()
    {
        private const string DEFAULT_FILENAME = "settings.json";

        public void Save(string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this));
        }

        public static void Save(T pSettings, string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings));
        }

        public static T Load(string fileName = DEFAULT_FILENAME)
        {
            T t = new T();
            if(File.Exists(fileName))
                t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
            return t;
        }
    }
}

List of all special characters that need to be escaped in a regex

Assuming that you have and trust (to be authoritative) the list of escape characters Java regex uses (would be nice if these characters were exposed in some Pattern class member) you can use the following method to escape the character if it is indeed necessary:

private static final char[] escapeChars = { '<', '(', '[', '{', '\\', '^', '-', '=', '$', '!', '|', ']', '}', ')', '?', '*', '+', '.', '>' };

private static String regexEscape(char character) {
    for (char escapeChar : escapeChars) {
        if (character == escapeChar) {
            return "\\" + character;
        }
    }
    return String.valueOf(character);
}

How to iterate through LinkedHashMap with lists as values

You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.

for (Entry<String, ArrayList<String>> entry : test1.entrySet() {
     System.out.println(entry.getKey() + "/" + entry.getValue());
}

I tried this but get only returns string

Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

Open files in 'rt' and 'wt' modes

The 'r' is for reading, 'w' for writing and 'a' is for appending.

The 't' represents text mode as apposed to binary mode.

Several times here on SO I've seen people using rt and wt modes for reading and writing files.

Edit: Are you sure you saw rt and not rb?

These functions generally wrap the fopen function which is described here:

http://www.cplusplus.com/reference/cstdio/fopen/

As you can see it mentions the use of b to open the file in binary mode.

The document link you provided also makes reference to this b mode:

Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.

Maven: mvn command not found

Maven setup:

a. install maven from https://maven.apache.org/download.cgi

b. unzip maven and keep in C drive.

c. Set MAVEN_HOME in system variable. enter image description here

d. Set path for maven enter image description here

How to ftp with a batch file?

The answer by 0x90h helped a lot...

I saved this file as u.ftp:

open 10.155.8.215 
user
password
lcd /D "G:\Subfolder\"
cd  folder/
binary
mget file.csv
disconnect
quit

I then ran this command:

ftp -i -s:u.ftp

And it worked!!!

Thanks a lot man :)

Java Delegates?

No, but they're fakeable using proxies and reflection:

  public static class TestClass {
      public String knockKnock() {
          return "who's there?";
      }
  }

  private final TestClass testInstance = new TestClass();

  @Test public void
  can_delegate_a_single_method_interface_to_an_instance() throws Exception {
      Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod("knockKnock")
                                                                   .of(TestClass.class)
                                                                   .to(Callable.class);
      Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);
      assertThat(callable.call(), is("who's there?"));
  }

The nice thing about this idiom is that you can verify that the delegated-to method exists, and has the required signature, at the point where you create the delegator (although not at compile-time, unfortunately, although a FindBugs plug-in might help here), then use it safely to delegate to various instances.

See the karg code on github for more tests and implementation.

SQL MAX of multiple columns?

DECLARE @TableName TABLE (Number INT, Date1 DATETIME, Date2 DATETIME, Date3 DATETIME, Cost MONEY)

INSERT INTO @TableName 
SELECT 1, '20000101', '20010101','20020101',100 UNION ALL
SELECT 2, '20000101', '19900101','19980101',99 

SELECT Number,
       Cost  ,
       (SELECT MAX([Date])
       FROM    (SELECT Date1 AS [Date]
               UNION ALL
               SELECT Date2
               UNION ALL
               SELECT Date3
               )
               D
       )
       [Most Recent Date]
FROM   @TableName

jQuery if div contains this text, replace that part of the text

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

An existing connection was forcibly closed by the remote host - WCF

I have catched the same exception and found a InnerException: SocketException. in the svclog trace.

After looking in the windows event log I saw an error coming from the System.ServiceModel.Activation.TcpWorkerProcess class.

Are you hosting your wcf service in IIS with netTcpBinding and port sharing?

It seems there is a bug in IIS port sharing feature, check the fix:

My solution is to host your WCF service in a Windows Service.

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

Count the number of times a string appears within a string

Your regular expression should be \btrue\b to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:

string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;

Make sure the System.Text.RegularExpressions namespace is included at the top of the file.

Server.Mappath in C# classlibrary

Use this System.Web.Hosting.HostingEnvironment.MapPath().

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

how to insert datetime into the SQL Database table?

if you got actuall time in mind GETDATE() would be the function what you looking for

Rails how to run rake task

Rake::Task['reklamer:orville'].invoke

or

Rake::Task['reklamer:orville'].invoke(args)

Is it possible to create static classes in PHP (like in C#)?

I generally prefer to write regular non static classes and use a factory class to instantiate single ( sudo static ) instances of the object.

This way constructor and destructor work as per normal, and I can create additional non static instances if I wish ( for example a second DB connection )

I use this all the time and is especially useful for creating custom DB store session handlers, as when the page terminates the destructor will push the session to the database.

Another advantage is you can ignore the order you call things as everything will be setup on demand.

class Factory {
    static function &getDB ($construct_params = null)
    {
        static $instance;
        if( ! is_object($instance) )
        {
            include_once("clsDB.php");
            $instance = new clsDB($construct_params);   // constructor will be called
        }
        return $instance;
    }
}

The DB class...

class clsDB {

    $regular_public_variables = "whatever";

    function __construct($construct_params) {...}
    function __destruct() {...}

    function getvar() { return $this->regular_public_variables; }
}

Anywhere you want to use it just call...

$static_instance = &Factory::getDB($somekickoff);

Then just treat all methods as non static ( because they are )

echo $static_instance->getvar();

Task<> does not contain a definition for 'GetAwaiter'

public async Task<model> GetSomething(int id)
{
    return await context.model.FindAsync(id);
}

Error in contrasts when defining a linear model in R

The answers by the other authors have already addressed the problem of factors with only one level or NAs.

Today, I stumbled upon the same error when using the rstatix::anova_test() function but my factors were okay (more than one level, no NAs, no character vectors, ...). Instead, I could fix the error by dropping all variables in the dataframe that are not included in the model. I don't know what's the reason for this behavior but just knowing about this might also be helpful when encountering this error.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

If the .htaccess file not avilable create it on root folder and past this line of code.

Put this in .htaccess file (tested working well for API)

<IfModule mod_php5.c>
    php_value always_populate_raw_post_data -1
</IfModule>

What's the name for hyphen-separated case?

Here is a more recent discombobulation. Documentation everywhere in angular JS and Pluralsight courses and books on angular, all refer to kebab-case as snake-case, not differentiating between the two.

Its too bad caterpillar-case did not stick because snake_case and caterpillar-case are easily remembered and actually look like what they represent (if you have a good imagination).

How to install cron

On CentOS/RHEL:

yum install cronie

Can a constructor in Java be private?

I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:

  • to prevent instantiation outside of the object, in the following cases:

    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
      .
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final

  • overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

How to programmatically send SMS on the iPhone?

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    UIImage *ui =resultimg.image;
    pasteboard.image = ui;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

How to get absolute value from double - c-language

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

SQL SELECT WHERE field contains words

Rather slow, but working method to include any of words:

SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
   OR column1 LIKE '%word2%'
   OR column1 LIKE '%word3%'

If you need all words to be present, use this:

SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
  AND column1 LIKE '%word2%'
  AND column1 LIKE '%word3%'

If you want something faster, you need to look into full text search, and this is very specific for each database type.

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

How to properly create an SVN tag from trunk?

Just use this:

svn  copy  http://svn.example.com/project/trunk  
           http://svn.example.com/project/branches/release-1
           -m  "branch for release 1.0"

(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.

See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2

Execute raw SQL using Doctrine 2

Here's an example of a raw query in Doctrine 2 that I'm doing:

public function getAuthoritativeSportsRecords()
{   
    $sql = " 
        SELECT name,
               event_type,
               sport_type,
               level
          FROM vnn_sport
    ";

    $em = $this->getDoctrine()->getManager();
    $stmt = $em->getConnection()->prepare($sql);
    $stmt->execute();
    return $stmt->fetchAll();
}   

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I solve that with putting this at the end of my app module build.gradle:

    configurations.all {
     resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.0'
        }
    }
  }
}

ORA-00054: resource busy and acquire with NOWAIT specified

You'll have to wait. The session that was killed was in the middle of a transaction and updated lots of records. These records have to be rollbacked and some background process is taking care of that. In the meantime you cannot modify the records that were touched.

Checking if a number is a prime number in Python

There are many efficient ways to test primality (and this isn't one of them), but the loop you wrote can be concisely rewritten in Python:

def is_prime(a):
    return all(a % i for i in xrange(2, a))

That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

Exact time measurement for performance testing

System.Diagnostics.Stopwatch is designed for this task.

Which HTTP methods match up to which CRUD methods?

I Was searching for the same answer, here is what IBM say. IBM Link

POST            Creates a new resource.
GET             Retrieves a resource.
PUT             Updates an existing resource.
DELETE          Deletes a resource.

how to know status of currently running jobs

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

check field execution_status

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

If you need the result of execution, check the field last_run_outcome

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

https://msdn.microsoft.com/en-us/library/ms186722.aspx

What is the proper way to URL encode Unicode characters?

IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.

tmux set -g mouse-mode on doesn't work

Just a quick heads-up to anyone else who is losing their mind right now:

https://github.com/tmux/tmux/blob/310f0a960ca64fa3809545badc629c0c166c6cd2/CHANGES#L12

so that's just

 :setw -g mouse

Angular 2 Scroll to top on Route Change

Angular lately introduced a new feature, inside angular routing module make changes like below

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'top'
  })],

How to create a button programmatically?

enter image description here

 func viewDidLoad(){
                    saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                    self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                    saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                    self.saveActionButton.setTitle("Done", for: .normal)
                    self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                    self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                    self.saveActionButton.layer.borderWidth = 1
                    self.saveActionButton.center.y = self.view.frame.size.height - 80
                    self.view.addSubview(saveActionButton)
        }

          func doneAction(){
          print("Write your own logic")
         }

TypeScript function overloading

You can declare an overloaded function by declaring the function as having a type which has multiple invocation signatures:

interface IFoo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

Then the following:

var foo1: IFoo = ...;

var n: number = foo1.bar('baz');     // OK
var s: string = foo1.bar(123);       // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR

The actual definition of the function must be singular and perform the appropriate dispatching internally on its arguments.

For example, using a class (which could implement IFoo, but doesn't have to):

class Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: any): any 
    {
        if (typeof(arg) === 'number')
            return arg.toString();
        if (typeof(arg) === 'string')
            return arg.length;
    }
}

What's interesting here is that the any form is hidden by the more specifically typed overrides.

var foo2: new Foo();

var n: number = foo2.bar('baz');     // OK
var s: string = foo2.bar(123);       // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR

How to delete all records from table in sqlite with Android?

To delete all the rows within the table you can use:

db.delete(TABLE_NAME, null, null);

How to get current relative directory of your Makefile?

One line in the Makefile should be enough:

DIR := $(notdir $(CURDIR))

Use a URL to link to a Google map with a marker on it

In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.

Have a look at the following document:

https://developers.google.com/maps/documentation/urls/guide

You can use URLs in search, directions, map and street view modes.

For example, to show the marker at specified position you can use the following URL:

https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324

For further details please read aforementioned documentation.

You can also file feature requests for this API in Google issue tracker.

Hope this helps!

How to load a jar file at runtime

I googled a bit, and found this code here:

File file = getJarFileToLoadFrom();   
String lcStr = getNameOfClassToLoad();   
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
Class loadedClass = cl.loadClass(lcStr);   

Can anyone share opinions/comments/answers regarding this approach?

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

Combining two Series into a DataFrame in pandas

If you are trying to join Series of equal length but their indexes don't match (which is a common scenario), then concatenating them will generate NAs wherever they don't match.

x = pd.Series({'a':1,'b':2,})
y = pd.Series({'d':4,'e':5})
pd.concat([x,y],axis=1)

#Output (I've added column names for clarity)
Index   x    y
a      1.0  NaN
b      2.0  NaN
d      NaN  4.0
e      NaN  5.0

Assuming that you don't care if the indexes match, the solution is to reindex both Series before concatenating them. If drop=False, which is the default, then Pandas will save the old index in a column of the new dataframe (the indexes are dropped here for simplicity).

pd.concat([x.reset_index(drop=True),y.reset_index(drop=True)],axis=1)

#Output (column names added):
Index   x   y
0       1   4
1       2   5

Storing Images in DB - Yea or Nay?

For a large number of small images, the database might be better.

I had an application with many small thumbnails (2Kb each). When I put them on the filesystem, they each consumed 8kb, due to the filesystem's blocksize. A 400% increase in space!

See this post for more information on block size: What is the block size of the iphone filesystem?

Using "If cell contains" in VBA excel

This will loop through all cells in a given range that you define ("RANGE TO SEARCH") and add dashes at the cell below using the Offset() method. As a best practice in VBA, you should never use the Select method.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub

Visual Studio keyboard shortcut to display IntelliSense

On Visual Studio Community 7.5.3 on Mac this works for me:

Ctrl + Space

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

How do I get a list of files in a directory in C++?

HANDLE WINAPI FindFirstFile(
  __in   LPCTSTR lpFileName,
  __out  LPWIN32_FIND_DATA lpFindFileData
);

Setup the attributes to only look for directories.

how to get files from <input type='file' .../> (Indirect) with javascript

Above answers are pretty sufficient. Additional to the onChange, if you upload a file using drag and drop events, you can get the file in drop event by accessing eventArgs.dataTransfer.files.

How to change css property using javascript

Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.

Matplotlib color according to class labels

Assuming that you have your data in a 2d array, this should work:

import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()

You can also set a cmap attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter line with:

pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)

A list of color maps can be found here

How to initialize an array of objects in Java

If you are unsure of the size of the array or if it can change you can do this to have a static array.

ArrayList<Player> thePlayersList = new ArrayList<Player>(); 

thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g

Players[] thePlayers = thePlayersList.toArray();

How to read and write to a text file in C++?

Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.

Some things to keep in mind, use single quotes ' when dealing with single characters, and double " for strings. Also it is a bad habit to use global variables when not necessary.

Have fun!

List all devices, partitions and volumes in Powershell

On Windows Powershell:

Get-PSDrive 
[System.IO.DriveInfo]::getdrives()
wmic diskdrive
wmic volume

Also the utility dskwipe: http://smithii.com/dskwipe

dskwipe.exe -l

Is key-value observation (KVO) available in Swift?

Another example for anyone who runs into a problem with types such as Int? and CGFloat?. You simply set you class as a subclass of NSObject and declare your variables as follows e.g:

class Theme : NSObject{

   dynamic var min_images : Int = 0
   dynamic var moreTextSize : CGFloat = 0.0

   func myMethod(){
       self.setValue(value, forKey: "\(min_images)")
   }

}

Best way to format if statement with multiple conditions

Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.

if(MyChecksAreOk()) { Code to execute }

...

private bool MyChecksAreOk()
{ 
    return ConditionOne && ConditionTwo && ConditionThree;
}

It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.

remote: repository not found fatal: not found

This answer is a bit late but I hope it helps someone out there all the same.

In my case, it was because the repository had been moved. I recloned the project and everything became alright afterwards. A better alternative would have been to re-initialize git.

I hope this helps.. Merry coding!

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

Execution failed for task :':app:mergeDebugResources'. Android Studio

For me. I changed the color of .xml image (vector image) like this.

ic_action_add.xml

  <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

to:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="#FF000000"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

i just changed android:fillColor="@android:color/white" to android:fillColor="#FF000000"

and it's worked for me :)

Visual studio code terminal, how to run a command with administrator rights?

Option 1 - Easier & Persistent

Running Visual Studio Code as Administrator should do the trick.

If you're on Windows you can:

  1. Right click the shortcut or app/exe
  2. Go to properties
  3. Compatibility tab
  4. Check "Run this program as an administrator"
There is a caveat to it though

Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.

Related Changes in Codebase

Option 2 - More like Sudo

If for some weird reason this is not running your commands as an Administrator you can try the runas command. Microsoft: runas command

Examples
  • runas /user:Administrator myCommand
  • runas "/user:First Last" "my command"
Notes
  • Just don't forget to put double quotes around anything that has a space in it.
  • Also it's quite possible that you have never set the password on the Administrator account, as it will ask you for the password when trying to run the command. You can always use an account without the username of Administrator if it has administrator access rights/permissions.

CSS3 Transparency + Gradient

This is some really cool stuff! I needed pretty much the same, but with horizontal gradient from white to transparent. And it is working just fine! Here ist my code:

.gradient{
        /* webkit example */
        background-image: -webkit-gradient(
          linear, right top, left top, from(rgba(255, 255, 255, 1.0)),
          to(rgba(255, 255, 255, 0))
        );

        /* mozilla example - FF3.6+ */
        background-image: -moz-linear-gradient(
          right center,
          rgba(255, 255, 255, 1.0) 20%, rgba(255, 255, 255, 0) 95%
        );

        /* IE 5.5 - 7 */
        filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColorStr=#FFFFFF
        );

        /* IE8 uses -ms-filter for whatever reason... */
        -ms-filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColoStr=#FFFFFF
        );
    }

How is returning the output of a function different from printing it?

Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.

I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.

return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user. Consider these two programs:

def function_that_prints():
    print "I printed"

def function_that_returns():
    return "I returned"

f1 = function_that_prints()
f2 = function_that_returns()

print "Now let us see what the values of f1 and f2 are"

print f1 --->None

print f2---->"I returned"

When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.

When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"

Angularjs how to upload multipart form data and a file?

First of all

  1. You don't need any special changes in the structure. I mean: html input tags.

_x000D_
_x000D_
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
       value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
       set-file-data="fileToUpload = value;" _x000D_
       type="file" id="my_file" />
_x000D_
_x000D_
_x000D_

1.2 create own directive,

_x000D_
_x000D_
.directive("fileModel",function() {_x000D_
 return {_x000D_
  restrict: 'EA',_x000D_
  scope: {_x000D_
   setFileData: "&"_x000D_
  },_x000D_
  link: function(scope, ele, attrs) {_x000D_
   ele.on('change', function() {_x000D_
    scope.$apply(function() {_x000D_
     var val = ele[0].files[0];_x000D_
     scope.setFileData({ value: val });_x000D_
    });_x000D_
   });_x000D_
  }_x000D_
 }_x000D_
})
_x000D_
_x000D_
_x000D_

  1. In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

  1. Then create separate function in controller to handle form submit call. like for e.g below code:

  2. In service function handle "responseType" param purposely so that server should not throw "byteerror".

  3. transformRequest, to modify request format with attached identity.

  4. withCredentials : false, for HTTP authentication information.

_x000D_
_x000D_
in controller:_x000D_
_x000D_
  // code this accordingly, so that your file object _x000D_
  // will be picked up in service call below._x000D_
  fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
  .service('fileUpload', ['$http', 'ajaxService',_x000D_
    function($http, ajaxService) {_x000D_
_x000D_
      this.uploadFileToUrl = function(data) {_x000D_
        var data = {}; //file object _x000D_
_x000D_
        var fd = new FormData();_x000D_
        fd.append('file', data.file);_x000D_
_x000D_
        $http.post("endpoint server path to whom sending file", fd, {_x000D_
            withCredentials: false,_x000D_
            headers: {_x000D_
              'Content-Type': undefined_x000D_
            },_x000D_
            transformRequest: angular.identity,_x000D_
            params: {_x000D_
              fd_x000D_
            },_x000D_
            responseType: "arraybuffer"_x000D_
          })_x000D_
          .then(function(response) {_x000D_
            var data = response.data;_x000D_
            var status = response.status;_x000D_
            console.log(data);_x000D_
_x000D_
            if (status == 200 || status == 202) //do whatever in success_x000D_
            else // handle error in  else if needed _x000D_
          })_x000D_
          .catch(function(error) {_x000D_
            console.log(error.status);_x000D_
_x000D_
            // handle else calls_x000D_
          });_x000D_
      }_x000D_
    }_x000D_
  }])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
_x000D_
_x000D_

How can I print each command before executing?

The easiest way to do this is to let bash do it:

set -x

Or run it explicitly as bash -x myscript.

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

get UTC timestamp in python with datetime

Also note the calendar.timegm() function as described by this blog entry:

import calendar
calendar.timegm(utc_timetuple)

The output should agree with the solution of vaab.

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Only read selected columns

To read a specific set of columns from a dataset you, there are several other options:

1) With freadfrom the data.table-package:

You can specify the desired columns with the select parameter from fread from the data.table package. You can specify the columns with a vector of column names or column numbers.

For the example dataset:

library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))

Alternatively, you can use the drop parameter to indicate which columns should not be read:

dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))

All result in:

> data
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

UPDATE: When you don't want fread to return a data.table, use the data.table = FALSE-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)

2) With read.csv.sql from the sqldf-package:

Another alternative is the read.csv.sql function from the sqldf package:

library(sqldf)
dat <- read.csv.sql("data.txt",
                    sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                    sep = "\t")

3) With the read_*-functions from the readr-package:

library(readr)
dat <- read_table("data.txt",
                  col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                        Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
                  col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                   Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')

From the documentation an explanation for the used characters with col_types:

each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column

Specifying a custom DateTime format when serializing with Json.Net

With below converter

public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            DateTimeFormat = "yyyy-MM-dd";
        }

        public CustomDateTimeConverter(string format)
        {
            DateTimeFormat = format;
        }
    }

Can use it with a default custom format

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter))]
    public DateTime ReturnDate { get;set;}
}

Or any specified format for a property

class ReturnObjectB 
{
    [JsonConverter(typeof(DateFormatConverter), "dd MMM yy")]
    public DateTime ReturnDate { get;set;}
}

Getting and removing the first character of a string

There is also str_sub from the stringr package

x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Instantiate and Present a viewController in Swift

If you want to present it modally, you should have something like bellow:

let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)

How do I access (read, write) Google Sheets spreadsheets with Python?

I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput or subprocess.

Search and replace part of string in database

Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

Get the week start date and week end date from week number

for Access Queries, you can use in the below format as a field

"FirstDayofWeek:IIf(IsDate([ForwardedForActionDate]),CDate(Format([ForwardedForActionDate],"dd/mm/yyyy"))-(Weekday([ForwardedForActionDate])-1))"

direct Calculation allowed..

Lambda expression to convert array/List of String to array/List of Integers

The helper methods from the accepted answer are not needed. Streams can be used with lambdas or usually shortened using Method References. Streams enable functional operations. map() converts the elements and collect(...) or toArray() wrap the stream back up into an array or collection.

Venkat Subramaniam's talk (video) explains it better than me.

1 Convert List<String> to List<Integer>

List<String> l1 = Arrays.asList("1", "2", "3");
List<Integer> r1 = l1.stream().map(Integer::parseInt).collect(Collectors.toList());

// the longer full lambda version:
List<Integer> r1 = l1.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());

2 Convert List<String> to int[]

int[] r2 = l1.stream().mapToInt(Integer::parseInt).toArray();

3 Convert String[] to List<Integer>

String[] a1 = {"4", "5", "6"};
List<Integer> r3 = Stream.of(a1).map(Integer::parseInt).collect(Collectors.toList());

4 Convert String[] to int[]

int[] r4 = Stream.of(a1).mapToInt(Integer::parseInt).toArray();

5 Convert String[] to List<Double>

List<Double> r5 = Stream.of(a1).map(Double::parseDouble).collect(Collectors.toList());

6 (bonus) Convert int[] to String[]

int[] a2 = {7, 8, 9};
String[] r6 = Arrays.stream(a2).mapToObj(Integer::toString).toArray(String[]::new);

Lots more variations are possible of course.

Also see Ideone version of these examples. Can click fork and then run to run in the browser.

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

C++ auto keyword. Why is it magic?

It's not going anywhere ... it's a new standard C++ feature in the implementation of C++11. That being said, while it's a wonderful tool for simplifying object declarations as well as cleaning up the syntax for certain call-paradigms (i.e., range-based for-loops), don't over-use/abuse it :-)

add onclick function to a submit button

<button type="submit" name="uname" value="uname" onclick="browserlink(ex.google.com,home.html etc)or myfunction();"> submit</button>

if you want to open a page on the click of a button in HTML without any scripting language then you can use above code.

Server Discovery And Monitoring engine is deprecated

If you are using a MongoDB server then after using connect in the cluster clock on connect and finding the URL, the URL will be somehing like this

<mongodb+srv://Rohan:<password>@cluster0-3kcv6.mongodb.net/<dbname>?retryWrites=true&w=majority>

In this case, don't forget to replace the password with your database password and db name and then use

const client = new MongoClient(url,{useUnifiedTopology:true});

PowerShell To Set Folder Permissions

In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:

$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose

Verbosity is optional in the last line

How to append one file to another in Linux from the shell?

Note: if you need to use sudo, do this:

sudo bash -c 'cat file2 >> file1'

The usual method of simply prepending sudo to the command will fail, since the privilege escalation doesn't carry over into the output redirection.

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Shortest way to print current year in a website

There are many solutions to this problem as provided by above experts. Below solution can be use which will not block the page rendering or not even re-trigger it.

In Pure Javascript:

_x000D_
_x000D_
window.addEventListener('load', (
    function () {
        document.getElementById('copyright-year').appendChild(
            document.createTextNode(
                new Date().getFullYear()
            )
        );
    }
));
_x000D_
<div> &copy; <span id="copyright-year"></span></div>
_x000D_
_x000D_
_x000D_

In jQuery:

_x000D_
_x000D_
$(document).ready(function() {
  document.getElementById('copyright-year').appendChild(
    document.createTextNode(
      new Date().getFullYear()
    )
  );
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> &copy; <span id="copyright-year"></span></div>
_x000D_
_x000D_
_x000D_

Clear the value of bootstrap-datepicker

Current version 1.4.0 has clearBtn option:

$('.datepicker').datepicker({
    clearBtn: true
});

Besides adding button to interface it allows to delete value from input box manually.

Flexbox: 4 items per row

Flex wrap + negative margin

Why flex vs. display: inline-block?

Why negative margin?

Either you use SCSS or CSS-in-JS for the edge cases (i.e. first element in column), or you set a default margin and get rid of the outer margin later.

Implementation

https://codepen.io/zurfyx/pen/BaBWpja

<div class="outerContainer">
    <div class="container">
        <div class="elementContainer">
            <div class="element">
            </div>
        </div>
        ...
    </div>
</div>
:root {
  --columns: 2;
  --betweenColumns: 20px; /* This value is doubled when no margin collapsing */
}

.outerContainer {
    overflow: hidden; /* Hide the negative margin */
}

.container {
    background-color: grey;
    display: flex;
    flex-wrap: wrap;
    margin: calc(-1 * var(--betweenColumns));
}

.elementContainer {
    display: flex; /* To prevent margin collapsing */
    width: calc(1/var(--columns) * 100% - 2 * var(--betweenColumns));
    margin: var(--betweenColumns);
}

.element {
    display: flex;
    border: 1px solid red;
    background-color: yellow;
    width: 100%;
    height: 42px;
}

Do I really need to encode '&' as '&amp;'?

In HTML a & marks the begin of a reference, either of a character reference or of an entity reference. From that point on the parser expects either a # denoting a character reference, or an entity name denoting an entity reference, both followed by a ;. That’s the normal behavior.

But if the reference name or just the reference opening & is followed by a white space or other delimiters like ", ', <, >, &, the ending ; and even a reference to represent a plain & can be omitted:

<p title="&amp;">foo &amp; bar</p>
<p title="&amp">foo &amp bar</p>
<p title="&">foo & bar</p>

Only in these cases the ending ; or even the reference itself can be omitted (at least in HTML 4). I think HTML 5 requires the ending ;.

But the specification recommends to always use a reference like the character reference &#38; or the entity reference &amp; to avoid confusion:

Authors should use "&amp;" (ASCII decimal 38) instead of "&" to avoid confusion with the beginning of a character reference (entity reference open delimiter). Authors should also use "&amp;" in attribute values since character references are allowed within CDATA attribute values.