Programs & Examples On #Testdriven.net

TestDriven.NET is a Visual Studio plugin which makes it easy to run unit tests from within the IDE.

Could not load type from assembly error

I ran into this scenario when trying to load a type (via reflection) in an assembly that was built against a different version of a reference common to the application where this error popped up.

As I'm sure the type is unchanged in both versions of the assembly I ended up creating a custom assembly resolver that maps the missing assembly to the one my application has already loaded. Simplest way is to add a static constructor to the program class like so:

using System.Reflection
static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "<AssemblyName>")
        {
            // Load assembly from startup path
            return Assembly.LoadFile($"{Application.StartupPath}\\<AssemblyName>.dll");
        }
        else
        {
            return null;
        }
    };
}

This of course assumes that the Assembly is located in the startup path of the application and can easily be adapted.

How do I get the path of the assembly the code is in?

This should work:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);

string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");

I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).

Where is web.xml in Eclipse Dynamic Web Project

If you missed to check the "generate web.xml" option when creating a new project, no worries If it is a Dynamic Web Project in your project right click on "Deployment Descriptor:...." and Click on "Generate Deployment Descriptor Stub" this will create a minimal /webapp/WEB-INF/web.xml.

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

How update the _id of one MongoDB Document?

You cannot update it. You'll have to save the document using a new _id, and then remove the old document.

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

Multipart forms from C# client

Thanks for the code, it saved me a lot of time (including the Except100 error!).

Anyway, I found a bug in the code, here:

formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length);

In case your POST data is utf-16, postData.Length, will return the number of characters and not the number of bytes. This will truncate the data being posted (for example, if you have 2 chars that are encoded as utf-16, they take 4 bytes, but postData.Length will say it takes 2 bytes, and you loose the 2 final bytes of the posted data).

Solution - replace that line with:

byte[] aPostData=encoding.GetBytes(postData);
formDataStream.Write(aPostData, 0, aPostData.Length);

Using this, the length is calculated by the size of the byte[], not the string size.

How to enable C++11/C++0x support in Eclipse CDT?

Neither the hack nor the cleaner version work for Indigo. The hack is ignored, and the required configuration options are missing. For no apparent reason, build started working after not working and not providing any useful reason why. At least from the command line, I get reproducible results.

Java Look and Feel (L&F)

Heres the code that creates a Dialog which allows the user of your application to change the Look And Feel based on the user's systems. Alternatively, if you can store the wanted Look And Feel's on your application, then they could be "portable", which is the desired result.

   public void changeLookAndFeel() {

        List<String> lookAndFeelsDisplay = new ArrayList<>();
        List<String> lookAndFeelsRealNames = new ArrayList<>();

        for (LookAndFeelInfo each : UIManager.getInstalledLookAndFeels()) {
            lookAndFeelsDisplay.add(each.getName());
            lookAndFeelsRealNames.add(each.getClassName());
        }

        String changeLook = (String) JOptionPane.showInputDialog(this, "Choose Look and Feel Here:", "Select Look and Feel", JOptionPane.QUESTION_MESSAGE, null, lookAndFeelsDisplay.toArray(), null);

        if (changeLook != null) {
            for (int i = 0; i < lookAndFeelsDisplay.size(); i++) {
                if (changeLook.equals(lookAndFeelsDisplay.get(i))) {
                    try {
                        UIManager.setLookAndFeel(lookAndFeelsRealNames.get(i));
                        break;
                    }
                    catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        err.println(ex);
                        ex.printStackTrace(System.err);
                    }
                }
            }
        }
    }

Random state (Pseudo-random number) in Scikit learn

sklearn.model_selection.train_test_split(*arrays, **options)[source]

Split arrays or matrices into random train and test subsets

Parameters: ... 
    random_state : int, RandomState instance or None, optional (default=None)

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

'<option value=''.$key.'">'

should be

'<option value="'.$key.'">'

Undefined symbols for architecture arm64

You need to just remove arm64 from Valid Architecture and set NO to Active Architecture Only . Now just Clean, Build and Run. You will not see this error again.

:) KP

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

How would you make two <div>s overlap?

With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:

div#logo {
  position: absolute;
  left: 100px; // or whatever
}

Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.

Hour from DateTime? in 24 hours format

Try this:

//String.Format("{0:HH:mm}", dt);  // where dt is a DateTime variable

public static string FormatearHoraA24(DateTime? fechaHora)
{
    if (!fechaHora.HasValue)
        return "";

    return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}

Determine if char is a num or letter

Neither of these does anything useful. Use isalpha() or isdigit() from the standard library. They're in <ctype.h>.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

Double.parseDouble(String) will return a primitive double type. Double.valueOf(String) will return a wrapper object of type Double.

So, for e.g.:

double d = Double.parseDouble("1");

Double d = Double.valueOf("1");

Moreover, valueOf(...) is an overloaded method. It has two variants:

  1. Double valueOf(String s)
  2. Double valueOf(double d)

Whereas parseDouble is a single method with the following signature:

  1. double parseDouble(String s)

How to select a dropdown value in Selenium WebDriver using Java

I have not tried in Selenium, but for Galen test this is working,

var list = driver.findElementByID("periodID"); // this will return web element

list.click(); // this will open the dropdown list.

list.typeText("14w"); // this will select option "14w".

You can try this in selenium, the galen and selenium working are similar.

Read lines from a text file but skip the first two lines

You can use random access.

Open "C:\docs\TESTFILE.txt" For Random As #1 

    Position = 3    ' Define record number.
    Get #1, Position, ARecord    ' Read record.

Close #1

Getting input values from text box

This is the sample code for the email and javascript.

params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += "      Query:    ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');

Why do we not have a virtual constructor in C++?

Virtual functions basically provide polymorphic behavior. That is, when you work with an object whose dynamic type is different than the static (compile time) type with which it is referred to, it provides behavior that is appropriate for the actual type of object instead of the static type of the object.

Now try to apply that sort of behavior to a constructor. When you construct an object the static type is always the same as the actual object type since:

To construct an object, a constructor needs the exact type of the object it is to create [...] Furthermore [...]you cannot have a pointer to a constructor

(Bjarne Stroustup (P424 The C++ Programming Language SE))

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

Can't connect to localhost on SQL Server Express 2012 / 2016

First try the most popular solution provided by Ravindra Bagale.

If your connection from localhost to the database still fails with error similar to the following:

Can't connect to SQL Server DB. Error: The TCP/IP connection to the host [IP address], port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall."

  1. Open the SQL Server Configuration Manager.
  2. Expand SQL Server Network Configuration for the server instance in question.
  3. Double-click "TCP/IP".
  4. Under the "Protocol" section, set "Enabled" to "Yes".
  5. Under the "IP Addresses" section, set the TCP port under "IP All" (which is 1433 by default).
  6. Under the "IP Addresses" section, find subsections with IP address 127.0.0.1 (for IPv4) and ::1 (for IPv6) and set both "Enabled" and "Active" to "Yes", and TCP port to 1433.

    TCP/IP Properties

  7. Go to Start > Control Panel > Administrative Tools > Services, and restart the SQL Server service (SQLEXPRESS).

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

How do I format a string using a dictionary in python-3.x?

print("{latitude} {longitude}".format(**geopoint))

How to update array value javascript?

function Update(key, value)
{    
    for (var i = 0; i < array.length; i++) {
        if (array[i].Key == key) {
            array[i].Value = value; 
            break;
        }
    }
}

What is the best way to trigger onchange event in react js

At least on text inputs, it appears that onChange is listening for input events:

var event = new Event('input', { bubbles: true });
element.dispatchEvent(event);

How to store and retrieve a dictionary with redis

If you don't know exactly how to organize data in Redis, I did some performance tests, including the results parsing. The dictonary I used (d) had 437.084 keys (md5 format), and the values of this form:

{"path": "G:\tests\2687.3575.json",
 "info": {"f": "foo", "b": "bar"},
 "score": 2.5}

First Test (inserting data into a redis key-value mapping):

conn.hmset('my_dict', d)  # 437.084 keys added in 8.98s

conn.info()['used_memory_human']  # 166.94 Mb

for key in d:
    json.loads(conn.hget('my_dict', key).decode('utf-8').replace("'", '"'))
    #  41.1 s

import ast
for key in d:
    ast.literal_eval(conn.hget('my_dict', key).decode('utf-8'))
    #  1min 3s

conn.delete('my_dict')  # 526 ms

Second Test (inserting data directly into Redis keys):

for key in d:
    conn.hmset(key, d[key])  # 437.084 keys added in 1min 20s

conn.info()['used_memory_human']  # 326.22 Mb

for key in d:
    json.loads(conn.hgetall(key)[b'info'].decode('utf-8').replace("'", '"'))
    #  1min 11s

for key in d:
    conn.delete(key)
    #  37.3s

As you can see, in the second test, only 'info' values have to be parsed, because the hgetall(key) already returns a dict, but not a nested one.

And of course, the best example of using Redis as python's dicts, is the First Test

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Chrome sendrequest error: TypeError: Converting circular structure to JSON

This works and tells you which properties are circular. It also allows for reconstructing the object with the references

  JSON.stringifyWithCircularRefs = (function() {
    const refs = new Map();
    const parents = [];
    const path = ["this"];

    function clear() {
      refs.clear();
      parents.length = 0;
      path.length = 1;
    }

    function updateParents(key, value) {
      var idx = parents.length - 1;
      var prev = parents[idx];
      if (prev[key] === value || idx === 0) {
        path.push(key);
        parents.push(value);
      } else {
        while (idx-- >= 0) {
          prev = parents[idx];
          if (prev[key] === value) {
            idx += 2;
            parents.length = idx;
            path.length = idx;
            --idx;
            parents[idx] = value;
            path[idx] = key;
            break;
          }
        }
      }
    }

    function checkCircular(key, value) {
      if (value != null) {
        if (typeof value === "object") {
          if (key) { updateParents(key, value); }

          let other = refs.get(value);
          if (other) {
            return '[Circular Reference]' + other;
          } else {
            refs.set(value, path.join('.'));
          }
        }
      }
      return value;
    }

    return function stringifyWithCircularRefs(obj, space) {
      try {
        parents.push(obj);
        return JSON.stringify(obj, checkCircular, space);
      } finally {
        clear();
      }
    }
  })();

Example with a lot of the noise removed:

{
    "requestStartTime": "2020-05-22...",
    "ws": {
        "_events": {},
        "readyState": 2,
        "_closeTimer": {
            "_idleTimeout": 30000,
            "_idlePrev": {
                "_idleNext": "[Circular Reference]this.ws._closeTimer",
                "_idlePrev": "[Circular Reference]this.ws._closeTimer",
                "expiry": 33764,
                "id": -9007199254740987,
                "msecs": 30000,
                "priorityQueuePosition": 2
            },
            "_idleNext": "[Circular Reference]this.ws._closeTimer._idlePrev",
            "_idleStart": 3764,
            "_destroyed": false
        },
        "_closeCode": 1006,
        "_extensions": {},
        "_receiver": {
            "_binaryType": "nodebuffer",
            "_extensions": "[Circular Reference]this.ws._extensions",
        },
        "_sender": {
            "_extensions": "[Circular Reference]this.ws._extensions",
            "_socket": {
                "_tlsOptions": {
                    "pipe": false,
                    "secureContext": {
                        "context": {},
                        "singleUse": true
                    },
                },
                "ssl": {
                    "_parent": {
                        "reading": true
                    },
                    "_secureContext": "[Circular Reference]this.ws._sender._socket._tlsOptions.secureContext",
                    "reading": true
                }
            },
            "_firstFragment": true,
            "_compress": false,
            "_bufferedBytes": 0,
            "_deflating": false,
            "_queue": []
        },
        "_socket": "[Circular Reference]this.ws._sender._socket"
    }
}

To reconstruct call JSON.parse() then loop through the properties looking for the [Circular Reference] tag. Then chop that off and... eval... it with this set to the root object.

Don't eval anything that can be hacked. Better practice would be to do string.split('.') then lookup the properties by name to set the reference.

What is the difference between docker-compose ports vs expose

According to the docker-compose reference,

Ports is defined as:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

  • Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
  • Ports will be exposed to the host machine to a random port or a given port.

My docker-compose.yml looks like:

mysql:
  image: mysql:5.7
  ports:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose is defined as:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

Ports are not exposed to host machines, only exposed to other services.

mysql:
  image: mysql:5.7
  expose:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp

Edit

In recent versions of Docker, expose doesn't have any operational impact anymore, it is just informative. (see also)

what is the difference between OLE DB and ODBC data sources?

On a very basic level those are just different APIs for the different data sources (i.e. databases). OLE DB is newer and arguably better.

You can read more on both in Wikipedia:

  1. OLE DB
  2. ODBC

I.e. you could connect to the same database using an ODBC driver or OLE DB driver. The difference in the database behaviour in those cases is what your book refers to.

Can a table row expand and close?

jQuery

$(function() {
    $("td[colspan=3]").find("div").hide();
    $("tr").click(function(event) {
        var $target = $(event.target);
        $target.closest("tr").next().find("div").slideToggle();                
    });
});

HTML

<table>
    <thead>
        <tr>
            <th>one</th><th>two</th><th>three</th>
        </tr>
    </thead>
    <tbody>

        <tr>
            <td><p>data<p></td><td>data</td><td>data</td>
        </tr>
        <tr>
            <td colspan="3">
                <div>
                    <table>
                            <tr>
                                <td>data</td><td>data</td>
                            </tr>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable

To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.

I also made some minor changes to HTML and corresponding jQuery.

NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.

Credit to Peter Ajtai

How to make return key on iPhone make keyboard disappear?

Took me couple trials, had same issue, this worked for me:

Check your spelling at -

(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

I corrected mine at textField instead of textfield, capitalise "F"... and bingo!! it worked..

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Select all 'tr' except the first one

I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:

tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */

They both function in exactly the same way (in the context of HTML tables anyway) as:

tr:not(:first-child)

jQuery: selecting each td in a tr

expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.

$(this).find('td').each (function( column, td) {
  $(td).blah
});  

Xcode 4 - "Archive" is greyed out?

see the picture. but I have to type enough chars to post the picture.:)

enter image description here

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

How to search for string in an array

more simple Function whichs works on Apple OS too:

Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
Dim element
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

C++ - How to append a char to char*?

The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way

bool AppendCharToCharArray( char *array, size_t n, char c )
{
    size_t sz = std::strlen( array );

    if ( sz + 1 < n ) 
    {
        array[sz] = c;
        array[sz + 1] = '\0';
    }       

    return ( sz + 1 < n );
} 

If you need a function that will contain a copy of the original array plus the given character then it could look the following way

char * CharArrayPlusChar( const char *array, char c )
{
    size_t sz = std::strlen( array );
    char *s = new char[sz + 2];

    std::strcpy( s, array );
    s[sz] = c;
    s[sz + 1] = '\0';

    return ( s );
} 

NodeJS/express: Cache and 304 status code

Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.

The empty page can be easily solved by using Shift key+reload button at the browser.

The empty page can be a result of:

  • a bug in your code
  • while testing you served an empty page (you can't remember) that is cached by the browser
  • a bug in Safari (if so, please report it to Apple and don't try to fix it yourself)

Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.

How do I compare version numbers in Python?

You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.

For example, version 3.6.0+1234 should be the same as 3.6.0.

import semver
semver.match('3.6.0+1234', '==3.6.0')
# True

from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False

from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False

How do I correctly clone a JavaScript object?

Clone an object based on a template. What do you do if you don't want an exact copy, but you do want the robustness of some kind of reliable clone operation but you only want bits cloned or you want to make sure you can control the existence or format of each attribute value cloned?

I am contributing this because it's useful for us and we created it because we could not find something similar. You can use it to clone an object based on a template object which specifies what attributes of the object I want to clone, and the template allows for functions to transform those attributes into something different if they don't exist on the source object or however you want to handle the clone. If it's not useful I am sure someone can delete this answer.

   function isFunction(functionToCheck) {
       var getType = {};
       return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
   }

   function cloneObjectByTemplate(obj, tpl, cloneConstructor) {
       if (typeof cloneConstructor === "undefined") {
           cloneConstructor = false;
       }
       if (obj == null || typeof (obj) != 'object') return obj;

       //if we have an array, work through it's contents and apply the template to each item...
       if (Array.isArray(obj)) {
           var ret = [];
           for (var i = 0; i < obj.length; i++) {
               ret.push(cloneObjectByTemplate(obj[i], tpl, cloneConstructor));
           }
           return ret;
       }

       //otherwise we have an object...
       //var temp:any = {}; // obj.constructor(); // we can't call obj.constructor because typescript defines this, so if we are dealing with a typescript object it might reset values.
       var temp = cloneConstructor ? new obj.constructor() : {};

       for (var key in tpl) {
           //if we are provided with a function to determine the value of this property, call it...
           if (isFunction(tpl[key])) {
               temp[key] = tpl[key](obj); //assign the result of the function call, passing in the value
           } else {
               //if our object has this property...
               if (obj[key] != undefined) {
                   if (Array.isArray(obj[key])) {
                       temp[key] = [];
                       for (var i = 0; i < obj[key].length; i++) {
                           temp[key].push(cloneObjectByTemplate(obj[key][i], tpl[key], cloneConstructor));
                       }
                   } else {
                       temp[key] = cloneObjectByTemplate(obj[key], tpl[key], cloneConstructor);
                   }
               }
           }
       }

       return temp;
   }

A simple way to call it would be like this:

var source = {
       a: "whatever",
       b: {
           x: "yeah",
           y: "haha"
       }
   };
   var template = {
       a: true, //we want to clone "a"
       b: {
           x: true //we want to clone "b.x" too
       }
   }; 
   var destination = cloneObjectByTemplate(source, template);

If you wanted to use a function to make sure an attribute is returned or to make sure it's a particular type, use a template like this. Instead of using { ID: true } we are providing a function which still just copies the ID attribute of the source object but it makes sure that it's a number even if it does not exist on the source object.

 var template = {
    ID: function (srcObj) {
        if(srcObj.ID == undefined){ return -1; }
        return parseInt(srcObj.ID.toString());
    }
}

Arrays will clone fine but if you want to you can have your own function handle those individual attributes too, and do something special like this:

 var template = {
    tags: function (srcObj) {
        var tags = [];
        if (process.tags != undefined) {
            for (var i = 0; i < process.tags.length; i++) {

                tags.push(cloneObjectByTemplate(
                  srcObj.tags[i],
                  { a : true, b : true } //another template for each item in the array
                );
            }
        }
        return tags;
    }
 }

So in the above, our template just copies the tags attribute of the source object if it exists, (it's assumed to be an array), and for each element in that array the clone function is called to individually clone it based on a second template which just copies the a and b attributes of each of those tag elements.

If you are taking objects in and out of node and you want to control which attributes of those objects are cloned then this is a great way of controlling that in node.js and the code works in the browser too.

Here is an example of it's use: http://jsfiddle.net/hjchyLt1/

How do I print bold text in Python?

This depends if you're using linux/unix:

>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.

The word text should be bold.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

As Eddie explains above, you can enable better protocols manually:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; 

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

What is the correct way to do a CSS Wrapper?

The easiest way is to have a "wrapper" div element with a width set, and a left and right margin of auto.

Sample markup:

<!doctype html>
<html>
<head>
    <title></title>
    <style type="text/css">
        .wrapper { width: 960px; margin: 0 auto; background-color: #cccccc; }
        body { margin: 0; padding: 0 }
    </style>
</head>
<body>
    <div class="wrapper">
        your content...
    </div>
</body>
</html>

What's the complete range for Chinese characters in Unicode?

Unicode version 11.0.0

In Unicode the Chinese, Japanese and Korean (CJK) scripts share a common background, collectively known as CJK characters.

These ranges often contain non-assigned or reserved code points(such as U+2E9A , U+2EF4 - 2EFF),

Chinese characters

bottom  top     reference (also have a look at wiki page)   block name
4E00    9FEF    http://www.unicode.org/charts/PDF/U4E00.pdf CJK Unified Ideographs
3400    4DBF    http://www.unicode.org/charts/PDF/U3400.pdf CJK Unified Ideographs Extension A
20000   2A6DF   http://www.unicode.org/charts/PDF/U20000.pdf    CJK Unified Ideographs Extension B
2A700   2B73F   http://www.unicode.org/charts/PDF/U2A700.pdf    CJK Unified Ideographs Extension C
2B740   2B81F   http://www.unicode.org/charts/PDF/U2B740.pdf    CJK Unified Ideographs Extension D
2B820   2CEAF   http://www.unicode.org/charts/PDF/U2B820.pdf    CJK Unified Ideographs Extension E
2CEB0   2EBEF   https://www.unicode.org/charts/PDF/U2CEB0.pdf   CJK Unified Ideographs Extension F
3007    3007    https://zh.wiktionary.org/wiki/%E3%80%87    in block CJK Symbols and Punctuation
                
  • In CJK Unified Ideographs block, I notice many answers use upper bound 9FCC, but U+9FCD(?) is indeed a Chinese char. And all characters in this block are Chinese characters (also used in Japanese or Korean etc.).
  • Most of characters in CJK Unified Ideographs Ext (Except Ext F, only 17% in Ext F are Chinese characters), are traditional Chinese characters, which are rarely used in China.
  • ? is the Chinese character form of zero and still in use today

Therefore the range is

[0x3007,0x3007],[0x3400,0x4DBF],[0x4E00,0x9FEF],[0x20000,0x2EBFF]

CJK characters but never used in Chinese

They are Common Han used only for compatibility.

It is almost impossible to see them appear in any Chinese books, articles, writings etc.

All characters here have one corresponding glyph-identical Chinese character, such as ?(U+F90A) and ?(U+91D1), they are identical glyphs.

 F900    FAFF   https://www.unicode.org/charts/PDF/UF900.pdf  CJK Compatibility Ideographs
2F800   2FA1F   https://www.unicode.org/charts/PDF/U2F800.pdf CJK Compatibility Ideographs Supplement

CJK related symbols

2E80    2EFF    http://www.unicode.org/charts/PDF/U2E80.pdf CJK Radicals Supplement
            
2F00    2FDF    http://www.unicode.org/charts/PDF/U2F00.pdf Kangxi Radicals 
2FF0    2FFF    https://unicode.org/charts/PDF/U2FF0.pdf    Ideographic Description Character
3000    303F    https://www.unicode.org/charts/PDF/U3000.pdf    CJK Symbols and Punctuation
3100    312f    https://unicode.org/charts/PDF/U3100.pdf    Bopomofo
31A0    31BF    https://unicode.org/charts/PDF/U31A0.pdf    Bopomofo Extended
31C0    31EF    http://www.unicode.org/charts/PDF/U31C0.pdf CJK Strokes
3200    32FF    https://unicode.org/charts/PDF/U3200.pdf    Enclosed CJK Letters and Months
3300    33FF    https://unicode.org/charts/PDF/U3300.pdf    CJK Compatibility
FE30    FE4F    https://www.unicode.org/charts/PDF/UFE30.pdf    CJK Compatibility Forms
FF00    FFEF    https://www.unicode.org/charts/PDF/UFF00.pdf    Halfwidth and Fullwidth Forms
1F200   1F2FF   https://www.unicode.org/charts/PDF/U1F200.pdf   Enclosed Ideographic Supplement
  • some blocks such as Hangul Compatibility Jamo are excluded because of no relation to Chinese.
  • Kangxi Radicals is not Chinese characters, they are graphical components of Chinese characters, used specially to express radicals, .e.g. ?(U+2F3B) and ?(U+5F73), ?(U+2EDC) and ? (U+98DE)

Other common punctuation appearing in Chinese

This is a wide range, some punctuation may be never used, some punctuations such as ……”“ are used so much in Chinese.

0000    007F    https://unicode.org/charts/PDF/U0000.pdf    C0 Controls and Basic Latin 
2000    206F    https://unicode.org/charts/PDF/U2000.pdf    General Punctuation
……

There are also many Chinese-related symbols, such as Yijing Hexagram Symbols or Kanbun, but it's off-topic anyway. I write non-chinese-characters in CJK to have a better explanation of what Chinese characters are. And the ranges above already cover almost all the characters which appear in Chinese writing except math and other specialty notation.

Supplementary

CJK Symbols and Punctuation

 ???????<>«»??????????????[]?????????????????????????????????? ? ?

Halfwidth and Fullwidth Forms

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Refer

  1. https://zh.wikipedia.org/wiki/%E6%B1%89%E5%AD%97 (in chinese language, notice the right side bar)
  2. https://zh.wikipedia.org/wiki/%E4%B8%AD%E6%97%A5%E9%9F%93%E7%9B%B8%E5%AE%B9%E8%A1%A8%E6%84%8F%E6%96%87%E5%AD%97 (notice the bottom table)
  3. http://www.unicode.org

VirtualBox error "Failed to open a session for the virtual machine"

For MAC users

After some research, this worked for me:

  • Quit VirtualBox
  • Right click "Applications" folder
  • Click on "Get Info"
  • Change "Everyone" Permission to "Read Only"
  • Open VirtualBox, and now it should work.

How to select an option from drop down using Selenium WebDriver C#?

Other way could be this one:

driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();

and you can change the index in option[x] changing x by the number of element that you want to select.

I don't know if it is the best way but I hope that help you.

ipynb import another ipynb file

Run

!pip install ipynb

and then import the other notebook as

from ipynb.fs.full.<notebook_name> import *

or

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defs instead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

Call a python function from jinja2

If you are doing it with Django, you can just pass the function with the context:

context = {
    'title':'My title',
    'str': str,
}
...
return render(request, 'index.html', context)

Now you will be able to use the str function in jinja2 template

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Head and tail in one line

Python 2, using lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

How to get the number of days of difference between two dates on mysql?

SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM  membership_dates md

output::

id  entity_id    start_date            end_date             days

1   1236      2018-01-16 00:00:00     2018-08-31 00:00:00    227
2   2876      2015-06-26 00:00:00     2019-06-30 00:00:00   1465
3   3880      1990-06-05 00:00:00     2018-07-04 00:00:00   10256
4   3882      1993-07-05 00:00:00     2018-07-04 00:00:00   9130

hope it helps someone in future

Append an empty row in dataframe using pandas

Assuming your df.index is sorted you can use:

df.loc[df.index.max() + 1] = None

It handles well different indexes and column types.

[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:

df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None

long example:

df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']], 
                    columns=["timestamp", "speed", "text"],
                    index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11 Freq: L Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null int64 text 1 non-null object dtypes: datetime64[ns](1), int64(1), object(1) memory usage: 32.0+ bytes

df.loc[df.index.max() + 1] = None
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000 Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null float64 text 1 non-null object dtypes: datetime64[ns](1), float64(1), object(1) memory usage: 64.0+ bytes

df.head()

                            timestamp                   speed      text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423   23.0    text_field
2111-11-11 00:00:00.001 NaT NaN NaN

Import SQL file into mysql

For those of you struggling with getting this done trying every possible answer you can find on SO. Here's what worked for me on a VPS running Windows 2012 R2 :

  1. Place your sql file wherever the bin is for me it is located at C:\Program Files\MySQL\MySQL Server 8.0\bin

  2. Open windows command prompt (cmd)

  3. Run C:\Program Files\MySQL\MySQL Server 8.0\bin > mysql -u [username] -p
  4. Enter your password
  5. Run command use [database_name];
  6. Import your file with command source C://Program Files//MySQL//MySQL Server 8.0//bin//mydatabasename.sql

It did it for me as everything else had failed. It might help you too.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Set port for php artisan.php serve

when we use the

php artisan serve 

it will start with the default HTTP-server port mostly it will be 8000 when we want to run the more site in the localhost we have to change the port. Just add the --port argument:

php artisan serve --port=8081

enter image description here

git command to move a folder inside another

you can use this script

# git mv a folder and sub folders in windows 

function Move-GitFolder {
    param (
        $target,
        $destination
    )
    
    Get-ChildItem $target -recurse |
    Where-Object { ! $_.PSIsContainer } |
    ForEach-Object { 
        $fullTargetFolder = [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $target))
        $fullDestinationFolder = [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $destination))
        $fileDestination = $_.Directory.FullName.Replace($fullTargetFolder.TrimEnd('\'), $fullDestinationFolder.TrimEnd('\'))

        New-Item -ItemType Directory -Force -Path $fileDestination | Out-Null

        $filePath = Join-Path $fileDestination $_.Name

        git mv $_.FullName $filePath
        
    }
}

Usage

Move-GitFolder <Target folder> <Destination folder>

the advantage of this solution over other solutions is that it move folders and files recursively in a folder and even create the folder structure if it doesn't exist

How to create a folder with name as current date in batch (.bat) files

This depends on the regional settings of the computer, so first check the output of the date using the command prompt or by doing an echo of date.

To do so, create a batch file and add the below content

echo %date%    
pause

It produces an output, in my case it shows Fri 05/06/2015.

Now we need to get rid of the slash (/)

For that include the below code in the batch file.

set temp=%DATE:/=%

if you echo the "temp", you can see the date without the slash in it.


Now all you need to do is formatting the date in the way you want.

For example I need the date in the format of YYYYMMDD, then I need to set the dirname as below

To explain how this works, we need to compare the value of temp

Fri 05062015.

now position each characters with numbers starting with 0.

Fri 0506201 5

01234567891011

So for the date format which I need is 20150605,

The Year 2015, in which 2 is in the 8th position, so from 8th position till 4 places, it will make 2015.

The month 06, in which 0 is in the 6th position, so from 6th position till 2 places, it will make 06.

The day 05, in which 0 is in the 4th position, so from 4th position till 2 places, it will make 05.

So finally to set up the final format, we have the below.

SET dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"

To enhance this date format with "-" or "_" in between the date, month and year , you can modify with below

SET dirname="%temp:~8,4%-%temp:~6,2%-%temp:~4,2%"

or

SET dirname="%temp:~8,4%_%temp:~6,2%_%temp:~4,2%"

So the final batch code will be

======================================================

@echo off    
set temp=%DATE:/=%
set dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"
mkdir %dirname%

======================================================

The directory will be created at the place where this batch executes.

How to run function of parent window when child window closes?

Check following link. This would be helpful too..

In Parent Window:

function OpenChildAsPopup() {
        var childWindow = window.open("ChildWindow.aspx", "_blank",
        "width=200px,height=350px,left=200,top=100");
        childWindow.focus();
 }

function ChangeBackgroudColor() {
        var para = document.getElementById('samplePara');
        if (para !="undefied") {
            para.style.backgroundColor = '#6CDBF5';
        }
 }

Parent Window HTML Markup:

<div>
  <p id="samplePara" style="width: 350px;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  </p><br />
 <asp:Button ID="Button1" Text="Open Child Window" 
         runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>

In Child Window:

// This will be called when the child window is closed.     
  window.onunload = function (e) {
        opener.ChangeBackgroudColor();
        //or you can do
        //var para = opener.document.getElementById('samplePara');
        //if (para != "undefied") {
        //    para.style.backgroundColor = '#6CDBF5';
        //}
    };

Remove last specific character in a string c#

The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
        char let = value[i];
        if (let == '?' || let == '!' || let == '.')
        {
            removeLength++;
        }
        else
        {
            break;
        }
    }
    if (removeLength > 0)
    {
        return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked />

HTML5 does not require attributes to have values

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

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

There is yet another difference. If the type (Class) to test against is dynamic, e.g. passed as a method parameter, then instanceof won't cut it for you.

boolean test(Class clazz) {
   return (this instanceof clazz); // clazz cannot be resolved to a type.
}

but you can do:

boolean test(Class clazz) {
   return (clazz.isAssignableFrom(this.getClass())); // okidoki
}

Oops, I see this answer is already covered. Maybe this example is helpful to someone.

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

How to quickly and conveniently disable all console.log statements in my code?

Ive been using the following to deal with he problem:-

var debug = 1;
var logger = function(a,b){ if ( debug == 1 ) console.log(a, b || "");};

Set debug to 1 to enable debugging. Then use the logger function when outputting debug text. It's also set up to accept two parameters.

So, instead of

console.log("my","log");

use

logger("my","log");

How to list the size of each file and directory and sort by descending size in Bash?

Command

du -h --max-depth=0 * | sort -hr

Output

3,5M    asdf.6000.gz
3,4M    asdf.4000.gz
3,2M    asdf.2000.gz
2,5M    xyz.PT.gz
136K    xyz.6000.gz
116K    xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K    desc.common.tcl
8,0K    wer.2000p.gz
8,0K    wer.2000.gz
4,0K    ttree.3

Explanation

  • du displays "disk usage"
  • h is for "human readable" (both, in sort and in du)
  • max-depth=0 means du will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)
  • r is for "reverse" (biggest file first)

ncdu

When I came to this question, I wanted to clean up my file system. The command line tool ncdu is way better suited to this task.

Installation on Ubuntu:

$ sudo apt-get install ncdu

Usage:

Just type ncdu [path] in the command line. After a few seconds for analyzing the path, you will see something like this:

$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
.  96,1 GiB [##########] /home
.  17,7 GiB [#         ] /usr
.   4,5 GiB [          ] /var
    1,1 GiB [          ] /lib
  732,1 MiB [          ] /opt
. 275,6 MiB [          ] /boot
  198,0 MiB [          ] /storage
. 153,5 MiB [          ] /run
.  16,6 MiB [          ] /etc
   13,5 MiB [          ] /bin
   11,3 MiB [          ] /sbin
.   8,8 MiB [          ] /tmp
.   2,2 MiB [          ] /dev
!  16,0 KiB [          ] /lost+found
    8,0 KiB [          ] /media
    8,0 KiB [          ] /snap
    4,0 KiB [          ] /lib64
e   4,0 KiB [          ] /srv
!   4,0 KiB [          ] /root
e   4,0 KiB [          ] /mnt
e   4,0 KiB [          ] /cdrom
.   0,0   B [          ] /proc
.   0,0   B [          ] /sys
@   0,0   B [          ]  initrd.img.old
@   0,0   B [          ]  initrd.img
@   0,0   B [          ]  vmlinuz.old
@   0,0   B [          ]  vmlinuz

Delete the currently highlighted element with d, exit with CTRL + c

Symfony2 : How to get form validation errors after binding the request to the form

The function for symfony 2.1 and newer, without any deprecated function:

/**
 * @param \Symfony\Component\Form\Form $form
 *
 * @return array
 */
private function getErrorMessages(\Symfony\Component\Form\Form $form)
{
    $errors = array();

    if ($form->count() > 0) {
        foreach ($form->all() as $child) {
            /**
             * @var \Symfony\Component\Form\Form $child
             */
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }
    } else {
        /**
         * @var \Symfony\Component\Form\FormError $error
         */
        foreach ($form->getErrors() as $key => $error) {
            $errors[] = $error->getMessage();
        }
    }

    return $errors;
}

Why does the JFrame setSize() method not set the size correctly?

There are lots of good reasons for setting the size of a frame. One is to remember the last size the user set, and restore those settings. I have this code which seems to work for me:

package javatools.swing;
import java.util.prefs.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;

public class FramePositionMemory {
    public static final String WIDTH_PREF = "-width";

    public static final String HEIGHT_PREF = "-height";

    public static final String XPOS_PREF = "-xpos";

    public static final String YPOS_PREF = "-ypos";
    String prefix;
    Window frame;
    Class<?> cls;

    public FramePositionMemory(String prefix, Window frame, Class<?> cls) {
        this.prefix = prefix;
        this.frame = frame;
        this.cls = cls;
    }

    public void loadPosition() {
        Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
    //  Restore the most recent mainframe size and location
        int width = prefs.getInt(prefix + WIDTH_PREF, frame.getWidth());
        int height = prefs.getInt(prefix + HEIGHT_PREF, frame.getHeight());
        System.out.println("WID: " + width + " HEI: " + height);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int xpos = (screenSize.width - width) / 2;
        int ypos = (screenSize.height - height) / 2;
        xpos = prefs.getInt(prefix + XPOS_PREF, xpos);
        ypos = prefs.getInt(prefix + YPOS_PREF, ypos);
        frame.setPreferredSize(new Dimension(width, height));
        frame.setLocation(xpos, ypos);
        frame.pack();
    }

    public void storePosition() {
        Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
        prefs.putInt(prefix + WIDTH_PREF, frame.getWidth());
        prefs.putInt(prefix + HEIGHT_PREF, frame.getHeight());
        Point loc = frame.getLocation();
        prefs.putInt(prefix + XPOS_PREF, (int)loc.getX());
        prefs.putInt(prefix + YPOS_PREF, (int)loc.getY());
        System.out.println("STORE: " + frame.getWidth() + " " + frame.getHeight() + " " + loc.getX() + " " + loc.getY());
    }
}
public class Main {
void main(String[] args) {
        JFrame frame = new Frame();
        // SET UP YOUR FRAME HERE.
        final FramePositionMemory fm = new FramePositionMemory("scannacs2", frame, Main.class);
        frame.setSize(400, 400); // default size in the absence of previous setting
        fm.loadPosition();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                fm.storePosition();
            }
        });
        frame.setVisible(true);
    }
}

}

How to use the unsigned Integer in Java 8 and Java 9?

There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:

static long values = Long.parseUnsignedLong("123456789012345678");

but this is not declaration of the variable.

Inverse dictionary lookup in Python

There are cases where a dictionary is a one:one mapping

Eg,

d = {1: "one", 2: "two" ...}

Your approach is ok if you are only doing a single lookup. However if you need to do more than one lookup it will be more efficient to create an inverse dictionary

ivd = {v: k for k, v in d.items()}

If there is a possibility of multiple keys with the same value, you will need to specify the desired behaviour in this case.

If your Python is 2.6 or older, you can use

ivd = dict((v, k) for k, v in d.items())

How do I check that multiple keys are in a dict in a single pass?

Simple benchmarking rig for 3 of the alternatives.

Put in your own values for D and Q


>>> from timeit import Timer
>>> setup='''from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s"%(len(q),len(d)))'''

>>> Timer('set(q) <= set(d)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632499
0.28672504425048828

#This one only works for Python3
>>> Timer('set(q) <= d.keys()','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632084
2.5987625122070312e-05

>>> Timer('all(k in d for k in q)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632219
1.1920928955078125e-05

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I had a similar issue. Everything was working before. It's was originally made using Web Forms and later on added Web API for some things.

  • Tried uninstalling, installing and reinstalling Microsoft.AspNet.WebApi package.
  • Tried removing packages folder from solution and letting NuGet restore in VS.
  • Tried removing individual assembly references (under References) and reinstalling packages.
  • Tried adding binding redirects to 5.2.3.0 version in web.config mentioned in several answers. Nothing worked for me.

What worked was, in Visual Studio, change publish profile settings from Release to Debug. Strange, but that's what worked. So sharing here.

Where to find htdocs in XAMPP Mac

for each easy and useful access you can add terminal command via editing your bash profile, here how:

open terminal -> type cd hit enter. then type nano .bash_profile then add this line alias htdocs="cd ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs" Now hit ctrl + o then hit enter, then hit ctrl + x Now to refresh the terminal commands type the following command

source .bash_profile

Now you can use htdocs command each time you want to navigate htdocs folder.

How can you represent inheritance in a database?

In addition at the Daniel Vassallo solution, if you use SQL Server 2016+, there is another solution that I used in some cases without considerable lost of performances.

You can create just a table with only the common field and add a single column with the JSON string that contains all the subtype specific fields.

I have tested this design for manage inheritance and I am very happy for the flexibility that I can use in the relative application.

How can I profile C++ code running on Linux?

If your goal is to use a profiler, use one of the suggested ones.

However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.

Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.

You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This magnification effect, when compounded over multiple problems, can lead to truly massive speedup factors.

Caveat: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because

  1. They don't summarize at the instruction level, and
  2. They give confusing summaries in the presence of recursion.

They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something once. If you see a problem on more than one sample, it is real.

P.S. This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.

P.P.S As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).

Added: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.

Another objection I often hear is: "It will stop someplace random, and it will miss the real problem". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa.

Added: Let me make a Bayesian explanation of how it works. Suppose there is some instruction I (call or otherwise) which is on the call stack some fraction f of the time (and thus costs that much). For simplicity, suppose we don't know what f is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.

Then suppose we take just 2 stack samples, and we see instruction I on both samples, designated observation o=2/2. This gives us new estimates of the frequency f of I, according to this:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&&f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.1    1     1             0.1          0.1            0.25974026
0.1    0.9   0.81          0.081        0.181          0.47012987
0.1    0.8   0.64          0.064        0.245          0.636363636
0.1    0.7   0.49          0.049        0.294          0.763636364
0.1    0.6   0.36          0.036        0.33           0.857142857
0.1    0.5   0.25          0.025        0.355          0.922077922
0.1    0.4   0.16          0.016        0.371          0.963636364
0.1    0.3   0.09          0.009        0.38           0.987012987
0.1    0.2   0.04          0.004        0.384          0.997402597
0.1    0.1   0.01          0.001        0.385          1

                  P(o=2/2) 0.385                

The last column says that, for example, the probability that f >= 0.5 is 92%, up from the prior assumption of 60%.

Suppose the prior assumptions are different. Suppose we assume P(f=0.1) is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that I is cheap. Then we get:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&& f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.001  1    1              0.001        0.001          0.072727273
0.001  0.9  0.81           0.00081      0.00181        0.131636364
0.001  0.8  0.64           0.00064      0.00245        0.178181818
0.001  0.7  0.49           0.00049      0.00294        0.213818182
0.001  0.6  0.36           0.00036      0.0033         0.24
0.001  0.5  0.25           0.00025      0.00355        0.258181818
0.001  0.4  0.16           0.00016      0.00371        0.269818182
0.001  0.3  0.09           0.00009      0.0038         0.276363636
0.001  0.2  0.04           0.00004      0.00384        0.279272727
0.991  0.1  0.01           0.00991      0.01375        1

                  P(o=2/2) 0.01375                

Now it says P(f >= 0.5) is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of I. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.

Yet another way to look at it is called the Rule Of Succession. If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin? The respected way to answer is to say that it's a Beta distribution, with average value (number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%.

(The key is that we see I more than once. If we only see it once, that doesn't tell us much except that f > 0.)

So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If n samples are taken, and f is the cost, then I will appear on nf+/-sqrt(nf(1-f)) samples. Example, n=10, f=0.3, that is 3+/-1.4 samples.)


Added: To give an intuitive feel for the difference between measuring and random stack sampling:
There are profilers now that sample the stack, even on wall-clock time, but what comes out is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to find the bottleneck, the number of them you need to see is, on average, 2 divided by the fraction of time it takes. So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.

Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples. The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.

enter image description here

Measurement is horizontal; it tells you what fraction of time specific routines take. Sampling is vertical. If there is any way to avoid what the whole program is doing at that moment, and if you see it on a second sample, you've found the bottleneck. That's what makes the difference - seeing the whole reason for the time being spent, not just how much.

'router-outlet' is not a known element

Here is the Quick and Simple Solution if anyone is getting the error:

"'router-outlet' is not a known element" in angular project,

Then,

Just go to the "app.module.ts" file & add the following Line:

import { AppRoutingModule } from './app-routing.module';

And also 'AppRoutingModule' in imports.

How to detect if JavaScript is disabled?

A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

Why do I get a "permission denied" error while installing a gem?

I think the problem happened when you use rbenv. Try the below commands to fix it.

rbenv shell {rb_version}
rbenv global {rb_version}
or 
rbenv local {rb_version}

Button inside of anchor link works in Firefox but not in Internet Explorer?

You cannot have a button inside an a tag. You can do some javascript to make it work however.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

According to the following article: https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/

If you have an INDEX on your where clause (if id is indexed in your case), then it is better not to use SQL_CALC_FOUND_ROWS and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using SQL_CALC_FOUND_ROWS is more efficient.

Saving an Object (Data persistence)

Quick example using company1 from your question, with python3.

import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.

import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

Tree view of a directory/folder in Windows?

You can use Internet Explorer to browse folders and files together in tree. It is a file explorer in Favorites Window. You just need replace "favorites folder" to folder which you want see as a root folder

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

Calculating bits required to store decimal number

Well, you just have to calculate the range for each case and find the lowest power of 2 that is higher than that range.

For instance, in i), 3 decimal digits -> 10^3 = 1000 possible numbers so you have to find the lowest power of 2 that is higher than 1000, which in this case is 2^10 = 1024 (10 bits).

Edit: Basically you need to find the number of possible numbers with the number of digits you have and then find which number of digits (in the other base, in this case base 2, binary) has at least the same possible numbers as the one in decimal.

To calculate the number of possibilities given the number of digits: possibilities=base^ndigits

So, if you have 3 digits in decimal (base 10) you have 10^3=1000 possibilities. Then you have to find a number of digits in binary (bits, base 2) so that the number of possibilities is at least 1000, which in this case is 2^10=1024 (9 digits isn't enough because 2^9=512 which is less than 1000).

If you generalize this, you have: 2^nbits=possibilities <=> nbits=log2(possibilities)

Which applied to i) gives: log2(1000)=9.97 and since the number of bits has to be an integer, you have to round it up to 10.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.

You can see what files have been configured for you curl version with the

curl-config --configure
command :

$ curl-config --configure
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--disable-ldap' 
 '--disable-ldaps' 
 '--enable-ipv6' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--enable-threaded-resolver' 
 '--without-libidn' 
 '--with-random=/dev/urandom' 
 '--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt' 
 'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro' 
 'CPPFLAGS=-D_FORTIFY_SOURCE=2'

Here you need read access to /etc/ssl/certs/ca-certificates.crt

$ curl-config --configure
 '--build' 'i486-linux-gnu' 
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--enable-ipv6' 
 '--with-lber-lib=lber' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--with-gssapi=/usr' 
 '--with-ca-path=/etc/ssl/certs' 
 'build_alias=i486-linux-gnu' 
 'CFLAGS=-g -O2' 
 'LDFLAGS=' 
 'CPPFLAGS='

And the same here.

How to encrypt/decrypt data in php?

Here is an example using openssl_encrypt

//Encryption:
$textToEncrypt = "My Text to Encrypt";
$encryptionMethod = "AES-256-CBC";
$secretHash = "encryptionhash";
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);

//Decryption:
$decryptedText = openssl_decrypt($encryptedText, $encryptionMethod, $secretHash, 0, $iv);
print "My Decrypted Text: ". $decryptedText;

Get safe area inset top and bottom heights

Swift 4, 5

To pin a view to a safe area anchor using constraints can be done anywhere in the view controller's lifecycle because they're queued by the API and handled after the view has been loaded into memory. However, getting safe-area values requires waiting toward the end of a view controller's lifecycle, like viewDidLayoutSubviews().

This plugs into any view controller:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = view.safeAreaInsets.top
        bottomSafeArea = view.safeAreaInsets.bottom
    } else {
        topSafeArea = topLayoutGuide.length
        bottomSafeArea = bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

I prefer this method to getting it off of the window (when possible) because it’s how the API was designed and, more importantly, the values are updated during all view changes, like device orientation changes.

However, some custom presented view controllers cannot use the above method (I suspect because they are in transient container views). In such cases, you can get the values off of the root view controller, which will always be available anywhere in the current view controller's lifecycle.

anyLifecycleMethod()
    guard let root = UIApplication.shared.keyWindow?.rootViewController else {
        return
    }
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = root.view.safeAreaInsets.top
        bottomSafeArea = root.view.safeAreaInsets.bottom
    } else {
        topSafeArea = root.topLayoutGuide.length
        bottomSafeArea = root.bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

This Activity already has an action bar supplied by the window decor

Simply put, you can do the following:-

if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));

    }

How to include (source) R script in other scripts

Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
  library(tools)
  path <- tryCatch(normalizePath(path), error=function(e) path)
  m<-md5sum(path)

  go<-TRUE
  if (!is.vector(.GlobalEnv$sourced)) {
    .GlobalEnv$sourced <- list()
  }
  if(! is.null(.GlobalEnv$sourced[[path]])) {
    if(m == .GlobalEnv$sourced[[path]]) {
      message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
      go<-FALSE
    }
    else {
      message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
      go<-TRUE
    }
  } 
  if(.force) {
    go<-TRUE
    message("  ...forcing.")
  }
  if(go) {
    message(sprintf("sourcing %s", path))
    .GlobalEnv$sourced[path] <- m
    base::source(path, ...)
  }
}

It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

Android splash screen image sizes to fit all devices

In my case, I used list drawable in style.xml. With layer list drawable, you have just needed one png for all screen size.

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/flash_screen</item>
    <item name="android:windowTranslucentStatus" tools:ignore="NewApi">true</item>
</style>

and flash_screen.xml in drawable folder.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white"></item>
    <item>
        <bitmap android:src="@drawable/background_noizi" android:gravity="center"></bitmap>
    </item>
</layer-list>

"background_noizi" is a png file in the drawable folder. I hope this helps.

NumPy first and last element from array

You can simply use take method and index of element (Last index can be -1).

arr = np.array([1,2,3])

last = arr.take(-1)
# 3

Only on Firefox "Loading failed for the <script> with source"

Today I ran into the exact same problem while working on a progressive web app (PWA) page and deleting some cache and service worker data for that page from Firefox. The dev console reported that none of the 4 Javascript files on the page would load anymore. The problem persisted in Safe mode, so it was not an add-on issue. The same script files loaded fine from other web pages on the same website. No amount of clearing the Firefox cache or wiping web page data from Firefox would help, nor would rebooting the Windows 10 PC. Chrome all the time worked fine on the problem page. In the end I did a restore of the entire Firefox profile folder from a day-old backup, and the problem was immediately gone, so it was not a problem with my PWA app. Apparently something in Firefox got corrupted.

How to delete specific characters from a string in Ruby?

Using String#gsub with regular expression:

"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "

This will remove surrounding parentheses only.

"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "

Adding new files to a subversion repository

To add a new file in SVN

svn add file_name
svn commit -m "text about changes..."

To add a new file in a directory in SVN

svn add directory_name/file_name
svn commit -m "text about changes"

To add all new files in a directory with some targets (files) are already versioned (added):

svn add directory_name/*
svn commit -m "text about changes"

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

Query to get only numbers from a string

In Oracle

You can get what you want using this:

SUBSTR('ABCD1234EFGH',REGEXP_INSTR ('ABCD1234EFGH', '[[:digit:]]'),REGEXP_COUNT ('ABCD1234EFGH', '[[:digit:]]'))

Sample Query:

SELECT SUBSTR('003Preliminary Examination Plan  ',REGEXP_INSTR ('003Preliminary Examination Plan  ', '[[:digit:]]'),REGEXP_COUNT ('003Preliminary Examination Plan  ', '[[:digit:]]')) SAMPLE1,
SUBSTR('Coordination005',REGEXP_INSTR ('Coordination005', '[[:digit:]]'),REGEXP_COUNT ('Coordination005', '[[:digit:]]')) SAMPLE2,
SUBSTR('Balance1000sheet',REGEXP_INSTR ('Balance1000sheet', '[[:digit:]]'),REGEXP_COUNT ('Balance1000sheet', '[[:digit:]]')) SAMPLE3 FROM DUAL

How to show shadow around the linearlayout in Android?

Create a new XML by example named "shadow.xml" at DRAWABLE with the following code (you can modify it or find another better):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/middle_grey"/>
        </shape>
    </item>

    <item android:left="2dp"
          android:right="2dp"
          android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white"/>
        </shape>
    </item>

</layer-list>

After creating the XML in the LinearLayout or another Widget you want to create shade, you use the BACKGROUND property to see the efect. It would be something like :

<LinearLayout
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingRight="@dimen/margin_med"
    android:background="@drawable/shadow"
    android:minHeight="?attr/actionBarSize"
    android:gravity="center_vertical">

Object passed as parameter to another class, by value or reference?

An Object if passed as a value type then changes made to the members of the object inside the method are impacted outside the method also. But if the object itself is set to another object or reinitialized then it will not be reflected outside the method. So i would say object as a whole is passed as Valuetype only but object members are still reference type.

        private void button1_Click(object sender, EventArgs e)
    {
        Class1 objc ;
         objc = new Class1();
        objc.empName = "name1";
        checkobj( objc);
        MessageBox.Show(objc.empName);  //propert value changed; but object itself did not change
    }
    private void checkobj ( Class1 objc)
    {
        objc.empName = "name 2";
        Class1 objD = new Class1();
        objD.empName ="name 3";
        objc = objD ;
        MessageBox.Show(objc.empName);  //name 3
    }

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Testing if a checkbox is checked with jQuery

$("#ans").attr('checked') 

will tell you if it's checked. You can also use a second parameter true/false to check/uncheck the checkbox.

$("#ans").attr('checked', true);

Per comment, use prop instead of attr when available. E.g:

$("#ans").prop('checked')

Installing a local module using npm?

Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.

For example:

/local/mymodule/package.json:
  "name": "mymodule",
  "peerDependencies":
  {
    "foo": "^2.5"
  }

/dev/myproject/package.json:
  "dependencies":
  {
    "mymodule": "file:/local/mymodule",
    "foo": "^2.5"
  }

In this scenario, npm sets up myproject's node_modules/ like this:

/dev/myproject/node_modules/
  foo/
  mymodule -> /local/mymodule

When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.

So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(

"register" keyword in C?

You are messing with the compiler's sophisticated graph-coloring algorithm. This is used for register allocation. Well, mostly. It acts as a hint to the compiler -- that's true. But not ignored in its entirety since you are not allowed to take the address of a register variable (remember the compiler, now on your mercy, will try to act differently). Which in a way is telling you not to use it.

The keyword was used long, long back. When there were only so few registers that could count them all using your index finger.

But, as I said, deprecated doesn't mean you cannot use it.

Replace Fragment inside a ViewPager

Works Great with AndroidTeam's solution, however I found that I needed the ability to go back much like FrgmentTransaction.addToBackStack(null) But merely adding this will only cause the Fragment to be replaced without notifying the ViewPager. Combining the provided solution with this minor enhancement will allow you to return to the previous state by merely overriding the activity's onBackPressed() method. The biggest drawback is that it will only go back one at a time which may result in multiple back clicks

private ArrayList<Fragment> bFragments = new ArrayList<Fragment>();
private ArrayList<Integer> bPosition = new ArrayList<Integer>();

public void replaceFragmentsWithBackOut(ViewPager container, Fragment oldFragment, Fragment newFragment) {
    startUpdate(container);

    // remove old fragment

    if (mCurTransaction == null) {
         mCurTransaction = mFragmentManager.beginTransaction();
     }
    int position = getFragmentPosition(oldFragment);
     while (mSavedState.size() <= position) {
         mSavedState.add(null);
     }

     //Add Fragment to Back List
     bFragments.add(oldFragment);

     //Add Pager Position to Back List
     bPosition.add(position);

     mSavedState.set(position, null);
     mFragments.set(position, null);

     mCurTransaction.remove(oldFragment);

     // add new fragment

     while (mFragments.size() <= position) {
         mFragments.add(null);
     }
     mFragments.set(position, newFragment);
     mCurTransaction.add(container.getId(), newFragment);

    finishUpdate(container);

    // ensure getItem returns newFragemtn after calling handleGetItemInbalidated()
    handleGetItemInvalidated(container, oldFragment, newFragment);

    container.notifyItemChanged(oldFragment, newFragment);
 }


public boolean popBackImmediate(ViewPager container){
    int bFragSize = bFragments.size();
    int bPosSize = bPosition.size();

    if(bFragSize>0 && bPosSize>0){
        if(bFragSize==bPosSize){
            int last = bFragSize-1;
            int position = bPosition.get(last);

            //Returns Fragment Currently at this position
            Fragment replacedFragment = mFragments.get(position);               
            Fragment originalFragment = bFragments.get(last);

            this.replaceFragments(container, replacedFragment, originalFragment);

            bPosition.remove(last);
            bFragments.remove(last);

            return true;
        }
    }

    return false;       
}

Hope this helps someone.

Also as far as getFragmentPosition() goes it's pretty much getItem() in reverse. You know which fragments go where, just make sure you return the correct position it will be in. Here's an example:

    @Override
    protected int getFragmentPosition(Fragment fragment) {
            if(fragment.equals(originalFragment1)){
                return 0;
            }
            if(fragment.equals(replacementFragment1)){
                return 0;
            }
            if(fragment.equals(Fragment2)){
                return 1;
            }
        return -1;
    }

How can I remove a trailing newline?

This would replicate exactly perl's chomp (minus behavior on arrays) for "\n" line terminator:

def chomp(x):
    if x.endswith("\r\n"): return x[:-2]
    if x.endswith("\n") or x.endswith("\r"): return x[:-1]
    return x

(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \r\n in account)

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

Using request.setAttribute in a JSP page

You can do it using pageContext attributes, though:

In the JSP:

<form action="Enter.do">
    <button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>

In the Servlet (linked to the "Enter.do" url-pattern):

String s=(String) request.getServletContext().getAttribute("opp");

There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.

Sort objects in an array alphabetically on one property of the array

Shorter code with ES6

objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))

Pass variables by reference in JavaScript

Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.

The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...

function action(){
  /* Process this.arg, modification allowed */
}

action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();

You can also promise stuff up to enjoy the well-known chain: Here is the whole thing, with promise-like structure

function action(){
  /* Process this.arg, modification allowed */
  this.arg = ["a", "b"];
}

action.setArg = function(){this.arg = arguments; return this;}

action.setArg(["empty-array"], "some string", 0x100, "last argument")()

Or better yet...

action.setArg(["empty-array"],"some string",0x100,"last argument").call()

.gitignore is ignored by Git

PhpStorm (and probably some other IDE users), in my case problem was that I created and added file outside the project, through the finder.

I deleted that one, and recreated the same one but in PhpStorm project, with right-click -> New -> File, and it worked right away.

Running python script inside ipython

from within the directory of "my_script.py" you can simply do:

%run ./my_script.py

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

How to handle onchange event on input type=file in jQuery?

Demo : http://jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

How to sort a list of strings numerically?

The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.

You have to CAST your input as an int instead:

sorted strings:

stringList = (1, 10, 2, 21, 3)

sorted ints:

intList = (1, 2, 3, 10, 21)

To cast, just put the stringList inside int ( blahblah ).

Again:

stringList = (1, 10, 2, 21, 3)

newList = int (stringList)

print newList

=> returns (1, 2, 3, 10, 21) 

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

Epoch vs Iteration when training neural networks

1.Epoch is 1 complete cycle where Neural network has seen all he data.
2. One might have say 100,000 images to train the model, however memory space might not be sufficient to process all the images at once, hence we split training the model on smaller chunks of data called batches. e.g. batch size is 100.
3. We need to cover all the images using multiple batches. So we will need 1000 iterations to cover all the 100,000 images. (100 batch size * 1000 iterations)
4. Once Neural Network looks at entire data it is called 1 Epoch (Point 1). One might need multiple epochs to train the model. (let us say 10 epochs).

How do I start a process from C#?

Just as Matt says, use Process.Start.

You can pass a URL, or a document. They will be started by the registered application.

Example:

Process.Start("Test.Txt");

This will start Notepad.exe with Text.Txt loaded.

Automapper missing type map configuration or unsupported mapping - Error

I found the solution, Thanks all for reply.

category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));

But, I have already dont know the reason. I cant understand fully.

What's the idiomatic syntax for prepending to a short python list?

Lets go over 4 methods

  1. Using insert()
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using [] and +
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using Slicing
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using collections.deque.appendleft()
>>> 
>>> from collections import deque
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 

Eclipse internal error while initializing Java tooling

In my case "MySQL service" is disabled. And I got same error.

So if you are using MySQL then check for it.

Press win+R then write services.msc and hit enter. Search for MySQL service. Start the service.

How to sort Map values by key in Java?

In Java 8

To sort a Map<K, V> by key, putting keys into a List<K>:

List<K> result = map.keySet().stream().sorted().collect(Collectors.toList());

To sort a Map<K, V> by key, putting entries into a List<Map.Entry<K, V>>:

List<Map.Entry<K, V>> result =
    map.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByKey())
       .collect(Collectors.toList());

Last but not least: to sort strings in a locale-sensitive manner - use a Collator (comparator) class:

Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY); // case insensitive collator

List<Map.Entry<String, String>> result =
    map.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByKey(collator))
       .collect(Collectors.toList());

How to specify the private SSH-key to use when executing shell command on Git?

Other people's suggestions about ~/.ssh/config are extra complicated. It can be as simple as:

Host github.com
  IdentityFile ~/.ssh/github_rsa

What's the best CRLF (carriage return, line feed) handling strategy with Git?

This is just a workaround solution:

In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.

In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.

Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.

My solution:

Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"

Unix-Machines

  1. Add following lines to a config's [alias] section. This command lists all changed (i.e. modified/new) files:

    lc = "!f() { git status --porcelain \
                 | egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
                 | cut -c 4- ; }; f "
    
  2. Convert all those changed files into dos format:

    unix2dos $(git lc)
    
  3. Optionally ...

    1. Create a git hook for this action to automate this process

    2. Use params and include it and modify the grep function to match only particular filenames, e.g.:

      ... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
      
    3. Feel free to make it even more convenient by using an additional shortcut:

      c2dos = "!f() { unix2dos $(git lc) ; }; f "
      

      ... and fire the converted stuff by typing

      git c2dos
      

How do I create executable Java program?

You can use the jar tool bundled with the SDK and create an executable version of the program.

This is how it's done.

I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.

First create your program:

$cat HelloWorldSwing.java
    package start;

    import javax.swing.*;

    public class HelloWorldSwing {
        public static void main(String[] args) {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel label = new JLabel("Hello World");
            frame.add(label);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
    class Dummy {
        // just to have another thing to pack in the jar
    }

Very simple, just displays a window with "Hello World"

Then compile it:

$javac -d . HelloWorldSwing.java

Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.

$ls start/
Dummy.class     HelloWorldSwing.class

Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.

This is the content of my manifest file.

$cat manifest.mf
Main-class: start.HelloWorldSwing

Just describe what the main class is ( the one with the public static void main method )

Once the manifest is ready, the jar executable is invoked.

It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.

$jar -cmf manifest.mf hello.jar start

This creates the .jar file on the system

enter image description here

You can later just double click on that file and it will run as expected.

enter image description here

To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.

Here's a video I've found about: Create a Jar File in Jcreator.

I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.

You can also use jnlp ( Java Network Launcher Protocol ) too.

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

Get city name using geolocation

You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {
            console.log(position.coords.latitude)
            console.log(position.coords.longitude)

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                console.log(location)
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

and to display this data on the page using jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>

    <p>Country: <span id="country"></span></p>
    <p>State: <span id="state"></span></p>
    <p>City: <span id="city"></span></p>
    <p>Address: <span id="address"></span></p>

    <p>Latitude: <span id="latitude"></span></p>
    <p>Longitude: <span id="longitude"></span></p>

    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

Java Replace Line In Text File

Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function

http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

once you do that you can save the line into a variable and manipulate the contents.

Drop unused factor levels in a subsetted data frame

Since R version 2.12, there's a droplevels() function.

levels(droplevels(subdf$letters))

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

Visual Studio: Relative Assembly References Paths

I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so

Reference Paths in VS20xx

That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.

If the dll is found in the Solution, the builder should prioritize the local version over the published team version.

How to repeat a string a variable number of times in C++?

In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch):

std::string(5, '.') + "lolcat"

NB. This can't be used to repeat multi-character strings.

How to pass anonymous types as parameters?

I would use IEnumerable<object> as type for the argument. However not a great gain for the unavoidable explicit cast. Cheers

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this problem and it was due to my windows machine playing up. I went into control panel -> system -> advanced - environment variables.

I edited the PATH variable (which was already correctly set up), changed NOTHING, clicked OK to come back out of the screens.

Then eclipse worked. No idea why, except because windows. Hopefully this may help someone.

How do I simulate placeholder functionality on input date field?

I'm using this css method in order to simulate placeholder on the input date.

The only thing that need js is to setAttribute of the value, if using React, it works out of the box.

_x000D_
_x000D_
input[type="date"] {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]:before {_x000D_
  content: attr(placeholder);_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background: #fff;_x000D_
  color: rgba(0, 0, 0, 0.65);_x000D_
  pointer-events: none;_x000D_
  line-height: 1.5;_x000D_
  padding: 0 0.5rem;_x000D_
}_x000D_
_x000D_
input[type="date"]:focus:before,_x000D_
input[type="date"]:not([value=""]):before_x000D_
{_x000D_
  display: none;_x000D_
}
_x000D_
<input type="date" placeholder="Choose date" value="" onChange="this.setAttribute('value', this.value)" />
_x000D_
_x000D_
_x000D_

Virtualbox shared folder permissions

In my case the following was necessary:

sudo chgrp vboxsf /media/sf_sharedFolder

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John

EDIT:

Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

How to create custom view programmatically in swift having controls text field, button etc

Swift 3 / Swift 4 Update:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

What is the iOS 5.0 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

Troubleshooting "Illegal mix of collations" error in mysql

You can try this script, that converts all of your databases and tables to utf8.

Cannot read property 'length' of null (javascript)

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

Pass a local file in to URL in Java

I tried it with Java on Linux. The following possibilities are OK:

file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html  (if current directory is /home/userId)

not working is:

file://aaaa.html

Java "user.dir" property - what exactly does it mean?

user.dir is the "User working directory" according to the Java Tutorial, System Properties

How to test if string exists in file with Bash?

My version using fgrep

  FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
  if [ $FOUND -eq 0 ]; then
    echo "Not able to find"
  else
    echo "able to find"     
  fi  

Getting realtime output using subprocess

if you just want to forward the log to console in realtime

Below code will work for both

 p = subprocess.Popen(cmd,
                         shell=True,
                         cwd=work_dir,
                         bufsize=1,
                         stdin=subprocess.PIPE,
                         stderr=sys.stderr,
                         stdout=sys.stdout)

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

Copy file or directories recursively in Python

To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)

import os, shutil

root_src_dir = r'C:\MyMusic'    #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp'  #Path to the destination folder

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.

What's the difference between ".equals" and "=="?

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Even though the strings have the same exact characters (“xyz”), The code above will actually output: obj1==obj2 is FALSE

Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

This code will output the following:

obj1==obj2 is TRUE

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

If your items are wider than the ListBox, the other answers here won't help: the items in the ItemTemplate remain wider than the ListBox.

The fix that worked for me was to disable the horizontal scrollbar, which, apparently, also tells the container of all those items to remain only as wide as the list box.

Hence the combined fix to get ListBox items that are as wide as the list box, whether they are smaller and need stretching, or wider and need wrapping, is as follows:

<ListBox HorizontalContentAlignment="Stretch" 
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">

(credits for the scroll bar idea)

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Escaping single quote in PHP when inserting into MySQL

You have a couple of things fighting in your strings.

  • lack of correct MySQL quoting (mysql_real_escape_string())
  • potential automatic 'magic quote' -- check your gpc_magic_quotes setting
  • embedded string variables, which means you have to know how PHP correctly finds variables

It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.

How to generate random number with the specific length in python

If you want it as a string (for example, a 10-digit phone number) you can use this:

n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])

How do you get the width and height of a multi-dimensional array?

You use Array.GetLength with the index of the dimension you wish to retrieve.

In WPF, what are the differences between the x:Name and Name attributes?

x:Name and Name are referencing different namespaces.

x:name is a reference to the x namespace defined by default at the top of the Xaml file.

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Just saying Name uses the default below namespace.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

x:Name is saying use the namespace that has the x alias. x is the default and most people leave it but you can change it to whatever you like

xmlns:foo="http://schemas.microsoft.com/winfx/2006/xaml"

so your reference would be foo:name

Define and Use Namespaces in WPF


OK lets look at this a different way. Say you drag and drop an button onto your Xaml page. You can reference this 2 ways x:name and name. All xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" and xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" are is references to multiple namespaces. Since xaml holds the Control namespace(not 100% on that) and presentation holds the FrameworkElement AND the Button class has a inheritance pattern of:

Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement, 
                    IInputElement, ISupportInitialize, IHaveResources

So as one would expect anything that inherits from FrameworkElement would have access to all its public attributes. so in the case of Button it is getting its Name attribute from FrameworkElement, at the very top of the hierarchy tree. So you can say x:Name or Name and they will both be accessing the getter/setter from the FrameworkElement.

MSDN Reference

WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. The XmlnsDefinitionAttribute attribute is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace.

So the assembly attributes will look something like:

PresentationFramework.dll - XmlnsDefinitionAttribute:

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Data")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Navigation")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Shapes")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Documents")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls")]  

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

Difference between iCalendar (.ics) and the vCalendar (.vcs)

The VCS files can have its information coded in Quoted printable which is a nightmare. The above solution recommending "VCS to ICS Calendar Converter" is the way to go.

What are carriage return, linefeed, and form feed?

\f is used for page break. You cannot see any effect in the console. But when you use this character constant in your file then you can see the difference.

Other example is that if you can redirect your output to a file then you don't have to write a file or use file handling.

For ex:

Write this code in c++

void main()    
{
    clrscr();
    cout<<"helloooooo" ;

    cout<<"\f";
    cout<<"hiiiii" ;

}

and when you compile this it generate an exe(for ex. abc.exe)

then you can redirect your output to a file using this:

abc > xyz.doc

then open the file xyz.doc you can see the actual page break between hellooo and hiiii....

Conditional statement in a one line lambda function in python?

The right way to do this is simple:

def rate(T):
    if (T > 200):
        return 200*exp(-T)
    else:
        return 400*exp(-T)

There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.

The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).


From a comment:

Well the function needed to fit in one line, which i didn't think you could do with a named function?

I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:

>>> def foo(x): return x + 1

Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.

Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.

But on the off chance that this really is what you need here: Just use exec instead of eval.

You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:

exec(my_function_string, my_globals, my_locals)

In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.

In earlier 2.x (before 2.6, I think?) you have to do it like this instead:

exec my_function_string in my_globals, my_locals

How to delete mysql database through shell command

Try the following command:

mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.

Your module should be :

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ContactComponent
  ]
})
export class ContactModule {}

Flutter : Vertically center column

For me the problem was there was was Expanded inside the column which I had to remove and it worked.

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded( // remove this
              flex: 2,
              child: Text("content here"),
            ),
          ],
        )

How do I return the SQL data types from my query?

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME='yourTable';

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

Java generics - get class?

I'm able to get the Class of the generic type this way:

class MyList<T> {
  Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java

For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

How do I generate random number for each row in a TSQL Select?

Do you have an integer value in each row that you could pass as a seed to the RAND function?

To get an integer between 1 and 14 I believe this would work:

FLOOR( RAND(<yourseed>) * 14) + 1

ZIP file content type for HTTP request

[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];

"Unable to find remote helper for 'https'" during git clone

CentOS Minimal usually install version 1.8 git by yum install gitcommand.

The best way is to build & install it from source code. Current version is 2.18.0.

  1. Download the source code from https://mirrors.edge.kernel.org/pub/software/scm/git/ or curl -o git-2.18.0.tar.gz https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.18.0.tar.gz

  2. Unzip by tar -zxf git-2.18.0.tar.gz && cd git-2.18.0

  3. Install the dependency package by executing yum install autoconf curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto openjade perl* texinfo

  4. Install docbook2X, it's not in the rpm repository. Download and install by

    $ curl -o docbook2X-0.8.8-17.el7.x86_64.rpm http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/docbook2X-0.8.8-17.el7.x86_64.rpm $ rpm -Uvh docbook2X-0.8.8-17.el7.x86_64.rpm

And make a unix link name:

ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
  1. Compile and install, reference to https://git-scm.com/book/en/v2/Getting-Started-Installing-Git

    $ make configure $ ./configure --prefix=/usr $ make all doc info $ sudo make install install-doc install-html install-info

  2. Reboot your server (If not, you may encounter Unable to find remote helper for 'https' error)

    $ reboot now

  3. Test:

    $ git clone https://github.com/volnet/v-labs.git $ cd v-labs $ touch test.txt $ git add . $ git commit -m "test git install" $ git push -u

Is there an easy way to add a border to the top and bottom of an Android View?

// Just simply add border around the image view or view

<ImageView
                android:id="@+id/imageView2"
                android:layout_width="90dp"
                android:layout_height="70dp"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@+id/imageView1"
                android:background="@android:color/white"
                android:padding="5dip" />

// After that dynamically put color into your view or image view object

objView.setBackgroundColor(Color.GREEN);

//VinodJ/Abhishek

Guzzlehttp - How get the body of a response from Guzzle 6?

If expecting JSON back, the simplest way to get it:

$data = json_decode($response->getBody()); // returns an object

// OR

$data = json_decode($response->getBody(), true); // returns an array

json_decode() will automatically cast the body to string, so there is no need to call getContents().

python setup.py uninstall

Probably you can do this as an alternative :-

1) Get the python version -

[linux machine]# python
Python 2.4.3 (#1, Jun 18 2012, 14:38:55) 

-> The above command gives you the current python Version which is 2.4.3

2) Get the installation directory of python -

[linux machine]# whereis python
python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/local/bin/python2.5 /usr/include/python2.4 /usr/share/man/man1/python.1.gz

-> From above command you can get the installation directory which is - /usr/lib/python2.4/site-packages

3) From here you can remove the packages and python egg files

[linux machine]# cd /usr/lib/python2.4/site-packages
[linux machine]# rm -rf paramiko-1.12.0-py2.4.egg paramiko-1.7.7.1-py2.4.egg paramiko-1.9.0-py2.4.egg

This worked for me.. And i was able to uninstall package which was troubling me :)

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

How to open Android Device Monitor in latest Android Studio 3.1

As said in "Testing the game on your Android device", I followed these three steps

  1. With the game still running on your device, return to your computer.
  2. Navigate to the directory containing the Android SDK Tools.
  3. Navigate to tools and double click the application called monitor.

This was prompting the following error

Android Device Monitor Error

I've also tested using cmd and the same error persisted

cmd

To fix it, I had to go to AndroidSDKTools\tools\lib\monitor-x86_64 and double click in the monitor application

monitor application

And then the Android Device Manager just started as normal

Android Device Manager

Function to calculate distance between two coordinates

Derek's solution worked fine for me, and I've just simply converted it to PHP, hope it helps somebody out there !

function calcCrow($lat1, $lon1, $lat2, $lon2){
        $R = 6371; // km
        $dLat = toRad($lat2-$lat1);
        $dLon = toRad($lon2-$lon1);
        $lat1 = toRad($lat1);
        $lat2 = toRad($lat2);

        $a = sin($dLat/2) * sin($dLat/2) +sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2); 
        $c = 2 * atan2(sqrt($a), sqrt(1-$a)); 
        $d = $R * $c;
        return $d;
}

// Converts numeric degrees to radians
function toRad($Value) 
{
    return $Value * pi() / 180;
}

jQuery add class .active on menu

Wasim's answer a few posts up from here works as advertised:

http://jsfiddle.net/Realto619/jKf3F/1/

How to create a batch file to run cmd as administrator

You might have to use another batch file first to launch the second with admin rights.

In the first use

runas /noprofile /user:mymachine\administrator yourbatchfile.bat

Upon further reading, you must be able to type in the password at the prompt. You cannot pipe the password as this feature was locked down for security reasons.

You may have more luck with psexec.

Remove duplicates from a list of objects based on property in Java 8

You can get a stream from the List and put in in the TreeSet from which you provide a custom comparator that compares id uniquely.

Then if you really need a list you can put then back this collection into an ArrayList.

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

...
List<Employee> unique = employee.stream()
                                .collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),
                                                           ArrayList::new));

Given the example:

List<Employee> employee = Arrays.asList(new Employee(1, "John"), new Employee(1, "Bob"), new Employee(2, "Alice"));

It will output:

[Employee{id=1, name='John'}, Employee{id=2, name='Alice'}]

Another idea could be to use a wrapper that wraps an employee and have the equals and hashcode method based with its id:

class WrapperEmployee {
    private Employee e;

    public WrapperEmployee(Employee e) {
        this.e = e;
    }

    public Employee unwrap() {
        return this.e;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        WrapperEmployee that = (WrapperEmployee) o;
        return Objects.equals(e.getId(), that.e.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hash(e.getId());
    }
}

Then you wrap each instance, call distinct(), unwrap them and collect the result in a list.

List<Employee> unique = employee.stream()
                                .map(WrapperEmployee::new)
                                .distinct()
                                .map(WrapperEmployee::unwrap)
                                .collect(Collectors.toList());

In fact, I think you can make this wrapper generic by providing a function that will do the comparison:

public class Wrapper<T, U> {
    private T t;
    private Function<T, U> equalityFunction;

    public Wrapper(T t, Function<T, U> equalityFunction) {
        this.t = t;
        this.equalityFunction = equalityFunction;
    }

    public T unwrap() {
        return this.t;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        @SuppressWarnings("unchecked")
        Wrapper<T, U> that = (Wrapper<T, U>) o;
        return Objects.equals(equalityFunction.apply(this.t), that.equalityFunction.apply(that.t));
    }

    @Override
    public int hashCode() {
        return Objects.hash(equalityFunction.apply(this.t));
    }
}

and the mapping will be:

.map(e -> new Wrapper<>(e, Employee::getId))

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How to go back last page

The way I did it while navigating to different page add a query param by passing current location

this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }

Read this query param in your component

this.router.queryParams.subscribe((params) => {
    this.returnUrl = params.returnUrl;
});

If returnUrl is present enable the back button and when user clicks the back button

this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa

This should able to navigate to previous page. Instead of using location.back I feel the above method is more safe consider the case where user directly lands to your page and if he presses the back button with location.back it will redirects user to previous page which will not be your web page.

Setting up Vim for Python

A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/

Changing background color of selected item in recyclerview

Create Drawable file in Drawable foloder

<item android:drawable="@color/SelectedColor" android:state_pressed="true"></item>
<item android:drawable="@color/SelectedColor" android:state_selected="true"></item>
<item android:drawable="@color/DefultColor"></item>

And in xml file

android:background="@drawable/Drawable file"

In RecyclerView onBindViewHolder

holder.button.setSelected(holder.button.isSelected()?true:false);

Like toggle button

Return a string method in C#

Use x.fullNameMethod() to call the method.

How do I add a margin between bootstrap columns without wrapping

You should work with padding on the inner container rather than with margin. Try this!

HTML

<div class="row info-panel">
    <div class="col-md-4" id="server_1">
       <div class="server-action-menu">
           Server 1
       </div>
   </div>
</div>

CSS

.server-action-menu {
    background-color: transparent;
    background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
    background-repeat: repeat;
    border-radius:10px;
    padding: 5px;
}

Best XML parser for Java

In addition to SAX and DOM there is STaX parsing available using XMLStreamReader which is an xml pull parser.

How can I selectively merge or pick changes from another branch in Git?

Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.

First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:

git merge --no-ff --no-commit -s ours branchname1

... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.

git checkout branchname1 -- file1 file2 etc.

If you were merging from more than one other branch, repeat as needed.

git checkout branchname2 -- file3 file4 etc.

Now the files from the other branch are in the index, ready to be committed, with history.

git commit

And you'll have a lot of explaining to do in that commit message.

Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.

Create JPA EntityManager without persistence.xml configuration file

DataNucleus JPA that I use also has a way of doing this in its docs. No need for Spring, or ugly implementation of PersistenceUnitInfo.

Simply do as follows

import org.datanucleus.metadata.PersistenceUnitMetaData;
import org.datanucleus.api.jpa.JPAEntityManagerFactory;

PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("mydomain.test.A");
pumd.setExcludeUnlistedClasses();
pumd.addProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:nucleus");
pumd.addProperty("javax.persistence.jdbc.user", "sa");
pumd.addProperty("javax.persistence.jdbc.password", "");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");

EntityManagerFactory emf = new JPAEntityManagerFactory(pumd, null);

What is the difference between dim and set in vba

Dim: you are defining a variable (here: r is a variable of type Range)

Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).

You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:

Dim r As Integer
r=5