Programs & Examples On #Fast fail

Passing arguments to AsyncTask, and returning results

Change your method to look like this:

String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list

And change your async task implementation

public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(baraj_mapa.this);
        dialog.setTitle("Calculating...");
        dialog.setMessage("Please wait...");
        dialog.setIndeterminate(true);
        dialog.show();
    }

    protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> passed = passing[0]; //get passed arraylist

        //Some calculations...

        return result; //return result
    }

    protected void onPostExecute(ArrayList<String> result) {
        dialog.dismiss();
        String minim = result.get(0);
        int min = Integer.parseInt(minim);
        String glons = result.get(1);
        String glats = result.get(2);
        double glon = Double.parseDouble(glons);
        double glat = Double.parseDouble(glats);
        GeoPoint g = new GeoPoint(glon, glat);
        String korisni_linii = result.get(3);
    }

UPD:

If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:

new calc_stanica() {
    protected void onPostExecute(ArrayList<String> result) {
      // here you have access to the context in which execute was called in first place. 
      // You'll have to mark all the local variables final though..
     }
}.execute(passing);

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

If you want to downgrade php from 7.1.1 to 5.6 in xampp follow the steps(For Windows):-

  1. Go to https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.36/
  2. Download and extract the file xampp-win32-5.6.36-0-VC11.zip see the image [image 1][1]
  3. Delete php folder and apache folder present in C:\xampp

  4. Copy php folder and apache folder from extracted file and paste it to C:\xampp

  5. Add " C: " before \xampp\ to php ini file present in php folder.

  6. Start your apache and MySQL and check php version. It will show php 5.6.36

Can you remove elements from a std::list while iterating through it?

Here's an example using a for loop that iterates the list and increments or revalidates the iterator in the event of an item being removed during traversal of the list.

for(auto i = items.begin(); i != items.end();)
{
    if(bool isActive = (*i)->update())
    {
        other_code_involving(*i);
        ++i;

    }
    else
    {
        i = items.erase(i);

    }

}

items.remove_if(CheckItemNotActive);

Datatables - Setting column width

I can tell you another simple way to fix the width of data table in html itself.

use

<colgroup>
    <col width="3%">
    <col width="3%">
</colgroup>

here is a sample code of data table below:

         <table class="table datatable">
                                <colgroup>
                                    <col width="33%">
                                    <col width="33%">
                                    <col width="33%">
                                    <col width="33%">
                                </colgroup>
                                   <thead>
                                        <tr>
                                            <th>User Id</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Phone</th>
                                        </tr>
                                    </thead>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                            </table>

How to restrict UITextField to take only numbers in Swift?

Here's an cleaner solution:

 guard CharacterSet(charactersIn: "123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
     return false
 }
 return true

For decimals just add ., example 123456789.

How to find/identify large commits in git history?

If you are on Windows, here is a PowerShell script that will print the 10 largest files in your repository:

$revision_objects = git rev-list --objects --all;
$files = $revision_objects.Split() | Where-Object {$_.Length -gt 0 -and $(Test-Path -Path $_ -PathType Leaf) };
$files | Get-Item -Force | select fullname, length | sort -Descending -Property Length | select -First 10

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked.

So, you are getting a warning,

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property.

Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this:

  1. First close all the existing projects by right clicking in Project explorer.
  2. Remove all the projects already synchronized with the server.
  3. Remove the server and redeploy it.
  4. Create a new dynamic project, do nothing yet just try running this on the server.
  5. Check the console, do you get the warning now. (My case I didn't get any).
    This means that something is wrong with your project not with eclipse or the server.
  6. Now restart the server. Don't run any app yet.
    You probably know that the Tomcat container loads up context of all the synchronized apps at the start.
  7. It will load context of any already synchronized app.
  8. Here is the catch, if there is really something wrong in your project it will show the stack trace of the exceptions.Look carefully and you will find where is the bug in your app.

Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else.

And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one.

Get local IP address in Node.js

An improvement on the top answer for the following reasons:

  • Code should be as self-explanatory as possible.

  • Enumerating over an array using for...in... should be avoided.

  • for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available.

     var os = require('os'),
         interfaces = os.networkInterfaces(),
         address,
         addresses = [],
         i,
         l,
         interfaceId,
         interfaceArray;
    
     for (interfaceId in interfaces) {
         if (interfaces.hasOwnProperty(interfaceId)) {
             interfaceArray = interfaces[interfaceId];
             l = interfaceArray.length;
    
             for (i = 0; i < l; i += 1) {
    
                 address = interfaceArray[i];
    
                 if (address.family === 'IPv4' && !address.internal) {
                     addresses.push(address.address);
                 }
             }
         }
     }
    
     console.log(addresses);
    

How do I delete everything in Redis?

FLUSHALL Remove all keys from all databases

FLUSHDB Remove all keys from the current database

SCRIPT FLUSH Remove all the scripts from the script cache.

How to convert std::string to lower case?

Using range-based for loop of C++11 a simpler code would be :

#include <iostream>       // std::cout
#include <string>         // std::string
#include <locale>         // std::locale, std::tolower

int main ()
{
  std::locale loc;
  std::string str="Test String.\n";

 for(auto elem : str)
    std::cout << std::tolower(elem,loc);
}

Show compose SMS view in Android

Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state. as Senthil Mg said you can use sms manager to send the sms directly but SMSManager has been moved to android.telephony.SmsManager

I know it's not a lot of more info, but it might help someone some day.

Row count where data exists

If you need VBA, you could do something quick like this:

Sub Test()
    With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastRow
    End With
End Sub

This will print the number of the last row with data in it. Obviously don't need MsgBox in there if you're using it for some other purpose, but lastRow will become that value nonetheless.

How to close the current fragment by using Button like the back button?

Try this:

ft.addToBackStack(null);   // ft is FragmentTransaction

So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

Read Numeric Data from a Text File in C++

you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    double data[size of your data];

    std::ifstream input("file.txt");

    for (int i = 0; i < size of your data; i++) {
        input >> data[i];
        std::cout<< data[i]<<std::endl;
        }

}

How to write a:hover in inline CSS?

There is no way to do this. Your options are to use a JavaScript or a CSS block.

Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.

Onclick javascript to make browser go back to previous page?

Works for me everytime

<a href="javascript:history.go(-1)">
    <button type="button">
        Back
    </button>
</a>

Reset push notification settings for app

The Apple Tech Note also described you can restore the device to reset the Push Notification dialog.

It does not say that you can also use the option "General -> Reset -> Erase All Content And Settings" on the device itself (iOS 5.x).

VB.NET: how to prevent user input in a ComboBox

Even if the question is marked answered, I would like to add some points to it.

Set the DropDownStyle property of the combobox to DropDownList works for sure.

BUT what if the drop down list is longer, the user will have to scroll it to the desired item as he has no access to keyboard.

 Private Sub cbostate_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cbostate.Validating
    If cbostate.SelectedValue Is Nothing AndAlso cbostate.Text <> String.Empty Then
        e.Cancel = True
        MsgBox("Invalid State")
    End If
End Sub

I did it like this. I wanted to restrict the user entering 'random values' instead of 'state' but keeping he should be able to type and search states.

This validating event occurs when the control loses focus. So if user enters wrong value in combobox, It will not allow user to do anything on the form, perhaps it will not even allow to change the focus from the combobox

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

In my case, same code worked fine on Firefox, but not on Google Chrome. Google Chrome's JavaScript console said:

XMLHttpRequest cannot load http://www.xyz.com/getZipInfo.php?zip=11234. 
Origin http://xyz.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"

I had to drop the www part of the Ajax URL for it to match correctly with the origin URL and it worked fine then.

What is the convention in JSON for empty vs. null?

Empty array for empty collections and null for everything else.

@font-face not working

Not sure exactly what your problem is, but try the following:

  1. Do the font files exist?
  2. Do you need quotes around the URLs?
  3. Are you using a CSS3-enabled browser?

Check here for examples, if they don't work for you then you have another problem

Edit:

You have a bunch of repeated declarations in your source, does this work?

@font-face { font-family: Gotham; src: url('../fonts/gothammedium.eot'); }

a { font-family:Gotham,Verdana,Arial; }

Remove lines that contain certain string

Regex is a little quicker than the accepted answer (for my 23 MB test file) that I used. But there isn't a lot in it.

import re

bad_words = ['bad', 'naughty']

regex = f"^.*(:{'|'.join(bad_words)}).*\n"
subst = ""

with open('oldfile.txt') as oldfile:
    lines = oldfile.read()

result = re.sub(regex, subst, lines, re.MULTILINE) 

with open('newfile.txt', 'w') as newfile:
    newfile.write(result)

enter image description here

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

Where can I find free WPF controls and control templates?

I searched for some good themes across internet and found nothing. So I ported selected controls of GTK Hybrid theme. It's MIT licensed and you can find it here:

https://github.com/stil/candyshop

It's not enterprise grade style and probably has some flaws, but I use it in my personal projects.

demo

In php, is 0 treated as empty?

Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:

$myVar = '';
if (empty($myVar))
{
  echo "Its empty";
}
echo "<br/>";

if ($myVar===0)
{
  echo "also zero!";
}

just for notice $myVar==0 act like empty function.

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

How can get the text of a div tag using only javascript (no jQuery)

Because textContent is not supported in IE8 and older, here is a workaround:

var node = document.getElementById('test'),
var text  = node.textContent || node.innerText;
alert(text);

innerText does work in IE.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

You can try by adding following line to catalina.bat after last entry of JAVA_OPTS

set JAVA_OPTS=%JAVA_OPTS% -Dhttps.protocols=TLSv1.2 -Djdk.tls.client.protocols=TLSv1.2

Conda command not found

Maybe you should type add this to your .bashrc or .zshrc

export PATH="/anaconda3/bin":$PATH

It worked for me.

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

How to find list of possible words from a letter matrix [Boggle Solver]

You could split the problem up into two pieces:

  1. Some kind of search algorithm that will enumerate possible strings in the grid.
  2. A way of testing whether a string is a valid word.

Ideally, (2) should also include a way of testing whether a string is a prefix of a valid word – this will allow you to prune your search and save a whole heap of time.

Adam Rosenfield's Trie is a solution to (2). It's elegant and probably what your algorithms specialist would prefer, but with modern languages and modern computers, we can be a bit lazier. Also, as Kent suggests, we can reduce our dictionary size by discarding words that have letters not present in the grid. Here's some python:

def make_lookups(grid, fn='dict.txt'):
    # Make set of valid characters.
    chars = set()
    for word in grid:
        chars.update(word)

    words = set(x.strip() for x in open(fn) if set(x.strip()) <= chars)
    prefixes = set()
    for w in words:
        for i in range(len(w)+1):
            prefixes.add(w[:i])

    return words, prefixes

Wow; constant-time prefix testing. It takes a couple of seconds to load the dictionary you linked, but only a couple :-) (notice that words <= prefixes)

Now, for part (1), I'm inclined to think in terms of graphs. So I'll build a dictionary that looks something like this:

graph = { (x, y):set([(x0,y0), (x1,y1), (x2,y2)]), }

i.e. graph[(x, y)] is the set of coordinates that you can reach from position (x, y). I'll also add a dummy node None which will connect to everything.

Building it's a bit clumsy, because there's 8 possible positions and you have to do bounds checking. Here's some correspondingly-clumsy python code:

def make_graph(grid):
    root = None
    graph = { root:set() }
    chardict = { root:'' }

    for i, row in enumerate(grid):
        for j, char in enumerate(row):
            chardict[(i, j)] = char
            node = (i, j)
            children = set()
            graph[node] = children
            graph[root].add(node)
            add_children(node, children, grid)

    return graph, chardict

def add_children(node, children, grid):
    x0, y0 = node
    for i in [-1,0,1]:
        x = x0 + i
        if not (0 <= x < len(grid)):
            continue
        for j in [-1,0,1]:
            y = y0 + j
            if not (0 <= y < len(grid[0])) or (i == j == 0):
                continue

            children.add((x,y))

This code also builds up a dictionary mapping (x,y) to the corresponding character. This lets me turn a list of positions into a word:

def to_word(chardict, pos_list):
    return ''.join(chardict[x] for x in pos_list)

Finally, we do a depth-first search. The basic procedure is:

  1. The search arrives at a particular node.
  2. Check if the path so far could be part of a word. If not, don't explore this branch any further.
  3. Check if the path so far is a word. If so, add to the list of results.
  4. Explore all children not part of the path so far.

Python:

def find_words(graph, chardict, position, prefix, results, words, prefixes):
    """ Arguments:
      graph :: mapping (x,y) to set of reachable positions
      chardict :: mapping (x,y) to character
      position :: current position (x,y) -- equals prefix[-1]
      prefix :: list of positions in current string
      results :: set of words found
      words :: set of valid words in the dictionary
      prefixes :: set of valid words or prefixes thereof
    """
    word = to_word(chardict, prefix)

    if word not in prefixes:
        return

    if word in words:
        results.add(word)

    for child in graph[position]:
        if child not in prefix:
            find_words(graph, chardict, child, prefix+[child], results, words, prefixes)

Run the code as:

grid = ['fxie', 'amlo', 'ewbx', 'astu']
g, c = make_graph(grid)
w, p = make_lookups(grid)
res = set()
find_words(g, c, None, [], res, w, p)

and inspect res to see the answers. Here's a list of words found for your example, sorted by size:

 ['a', 'b', 'e', 'f', 'i', 'l', 'm', 'o', 's', 't',
 'u', 'w', 'x', 'ae', 'am', 'as', 'aw', 'ax', 'bo',
 'bu', 'ea', 'el', 'em', 'es', 'fa', 'ie', 'io', 'li',
 'lo', 'ma', 'me', 'mi', 'oe', 'ox', 'sa', 'se', 'st',
 'tu', 'ut', 'wa', 'we', 'xi', 'aes', 'ame', 'ami',
 'ase', 'ast', 'awa', 'awe', 'awl', 'blo', 'but', 'elb',
 'elm', 'fae', 'fam', 'lei', 'lie', 'lim', 'lob', 'lox',
 'mae', 'maw', 'mew', 'mil', 'mix', 'oil', 'olm', 'saw',
 'sea', 'sew', 'swa', 'tub', 'tux', 'twa', 'wae', 'was',
 'wax', 'wem', 'ambo', 'amil', 'amli', 'asem', 'axil',
 'axle', 'bleo', 'boil', 'bole', 'east', 'fame', 'limb',
 'lime', 'mesa', 'mewl', 'mile', 'milo', 'oime', 'sawt',
 'seam', 'seax', 'semi', 'stub', 'swam', 'twae', 'twas',
 'wame', 'wase', 'wast', 'weam', 'west', 'amble', 'awest',
 'axile', 'embox', 'limbo', 'limes', 'swami', 'embole',
 'famble', 'semble', 'wamble']

The code takes (literally) a couple of seconds to load the dictionary, but the rest is instant on my machine.

Generator expressions vs. list comprehensions

The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.

For example:

sum(x*2 for x in xrange(256))

dict( (k, some_func(k)) for k in some_list_of_keys )

The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)

You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.

For example:

reversed( [x*2 for x in xrange(256)] )

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

How to get URI from an asset File?

Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

Get the path to the file like:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath

List of all index & index columns in SQL Server DB

based on Tim Ford code, this is the right answer:

  select tab.[name]  as [table_name],
         idx.[name]  as [index_name],
         allc.[name] as [column_name],
         idx.[type_desc],
         idx.[is_unique],
         idx.[data_space_id],
         idx.[ignore_dup_key],
         idx.[is_primary_key],
         idx.[is_unique_constraint],
         idx.[fill_factor],
         idx.[is_padded],
         idx.[is_disabled],
         idx.[is_hypothetical],
         idx.[allow_row_locks],
         idx.[allow_page_locks],
         idxc.[is_descending_key],
         idxc.[is_included_column],
         idxc.[index_column_id]

     from sys.[tables] as tab

    inner join sys.[indexes]       idx  on tab.[object_id] =  idx.[object_id]
    inner join sys.[index_columns] idxc on idx.[object_id] = idxc.[object_id] and  idx.[index_id]  = idxc.[index_id]
    inner join sys.[all_columns]   allc on tab.[object_id] = allc.[object_id] and idxc.[column_id] = allc.[column_id]

    where tab.[name] Like '%table_name%'
      and idx.[name] Like '%index_name%'
    order by tab.[name], idx.[index_id], idxc.[index_column_id]

Python error "ImportError: No module named"

I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

1) Change directory (cd) to the directory above the directory where your files are. In this case, you're trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

2) When you are in the tookit directory, enter this line of code on your command line:

export PYTHONPATH=.

This sets your PYTHONPATH to ".", which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn't just look in your current directory, but in all the directories that are in your current directory).

3) After you've set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

Hope this helps. I was quite frustrated with this myself.

Can HTML checkboxes be set to readonly?

Some of the answers on here seem a bit roundabout, but here's a small hack.

<form id="aform" name="aform" method="POST">
    <input name="chkBox_1" type="checkbox" checked value="1" disabled="disabled" />
    <input id="submitBttn" type="button" value="Submit" onClick='return submitPage();'>
</form>?

then in jquery you can either choose one of two options:

$(document).ready(function(){
    //first option, you don't need the disabled attribute, this will prevent
    //the user from changing the checkbox values
    $("input[name^='chkBox_1']").click(function(e){
        e.preventDefault();
    });

    //second option, keep the disabled attribute, and disable it upon submit
    $("#submitBttn").click(function(){
        $("input[name^='chkBox_1']").attr("disabled",false);
        $("#aform").submit();
    });

});

?

demo: http://jsfiddle.net/5WFYt/

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Go to Project > Properties > Java Compiler > Building
  2. Look under Build Path Problems
  3. Un-check "Abort build when build path error occurs"
    It won't solve all your errors but at least it will let you run your program :)

How does Trello access the user's clipboard?

With the help of raincoat's code on GitHub, I managed to get a running version accessing the clipboard with plain JavaScript.

function TrelloClipboard() {
    var me = this;

    var utils = {
        nodeName: function (node, name) {
            return !!(node.nodeName.toLowerCase() === name)
        }
    }
    var textareaId = 'simulate-trello-clipboard',
        containerId = textareaId + '-container',
        container, textarea

    var createTextarea = function () {
        container = document.querySelector('#' + containerId)
        if (!container) {
            container = document.createElement('div')
            container.id = containerId
            container.setAttribute('style', [, 'position: fixed;', 'left: 0px;', 'top: 0px;', 'width: 0px;', 'height: 0px;', 'z-index: 100;', 'opacity: 0;'].join(''))
            document.body.appendChild(container)
        }
        container.style.display = 'block'
        textarea = document.createElement('textarea')
        textarea.setAttribute('style', [, 'width: 1px;', 'height: 1px;', 'padding: 0px;'].join(''))
        textarea.id = textareaId
        container.innerHTML = ''
        container.appendChild(textarea)

        textarea.appendChild(document.createTextNode(me.value))
        textarea.focus()
        textarea.select()
    }

    var keyDownMonitor = function (e) {
        var code = e.keyCode || e.which;
        if (!(e.ctrlKey || e.metaKey)) {
            return
        }
        var target = e.target
        if (utils.nodeName(target, 'textarea') || utils.nodeName(target, 'input')) {
            return
        }
        if (window.getSelection && window.getSelection() && window.getSelection().toString()) {
            return
        }
        if (document.selection && document.selection.createRange().text) {
            return
        }
        setTimeout(createTextarea, 0)
    }

    var keyUpMonitor = function (e) {
        var code = e.keyCode || e.which;
        if (e.target.id !== textareaId || code !== 67) {
            return
        }
        container.style.display = 'none'
    }

    document.addEventListener('keydown', keyDownMonitor)
    document.addEventListener('keyup', keyUpMonitor)
}

TrelloClipboard.prototype.setValue = function (value) {
    this.value = value;
}

var clip = new TrelloClipboard();
clip.setValue("test");

See a working example: http://jsfiddle.net/AGEf7/

How to configure slf4j-simple

You can programatically change it by setting the system property:

public class App {

    public static void main(String[] args) {

        System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");

        final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);

        log.trace("trace");
        log.debug("debug");
        log.info("info");
        log.warn("warning");
        log.error("error");

    }
}

The log levels are ERROR > WARN > INFO > DEBUG > TRACE.

Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.

what is the difference between GROUP BY and ORDER BY in sql

They have totally different meaning and aren't really related at all.

ORDER BY allows you to sort the result set according to different criteria, such as first sort by name from a-z, then sort by the price highest to lowest.

(ORDER BY name, price DESC)

GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on those groups. You could for instance select all employees, group them by their workplace location and calculate the average salary of all employees of each workplace location.

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

Find all files in a directory with extension .txt in Python

Something like this will work:

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

javax.faces.application.ViewExpiredException: View could not be restored

Please add this line in your web.xml It works for me

<context-param>
        <param-name>org.ajax4jsf.handleViewExpiredOnClient</param-name> 
        <param-value>true</param-value>     
    </context-param>

Mockito, JUnit and Spring

Here's my short summary.

If you want to write a unit test, don't use a Spring applicationContext because you don't want any real dependencies injected in the class you are unit testing. Instead use mocks, either with the @RunWith(MockitoJUnitRunner.class) annotation on top of the class, or with MockitoAnnotations.initMocks(this) in the @Before method.

If you want to write an integration test, use:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("yourTestApplicationContext.xml")

To set up your application context with an in-memory database for example. Normally you don't use mocks in integration tests, but you could do it by using the MockitoAnnotations.initMocks(this) approach described above.

How to get PID of process by specifying process name and store it in a variable to use further?

Another possibility would be to use pidof it usually comes with most distributions. It will return you the PID of a given process by using it's name.

pidof process_name

This way you could store that information in a variable and execute kill -9 on it.

#!/bin/bash
pid=`pidof process_name`
kill -9 $pid

Oracle SQL query for Date format

if you are using same date format and have select query where date in oracle :

   select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';

To_DATE provided by oracle

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

Ruby class instance variable vs. class variable

As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.

Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class (or rather, a subclass of Class) corresponding to it. (When you say class Foo, you're really declaring a constant Foo and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.

The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.

In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Based on user @andygjp's answer, its better if you override the base Db.SaveChanges() method and add a function to override any date which does not fall between SqlDateTime.MinValue and SqlDateTime.MaxValue.

Here is the sample code

public class MyDb : DbContext
{
    public override int SaveChanges()
    {
        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries().Where(x => (x.State == EntityState.Added || x.State == EntityState.Modified)))
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Taken from the user @sky-dev's comment on https://stackoverflow.com/a/11297294/9158120

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

How to add facebook share button on my website?

This Facebook page has a simple tool to create various share buttons.

For example, this is some output I got:

<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>

SQL server stored procedure return a table

Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.

CREATE PROCEDURE test
AS 
BEGIN

    SELECT * FROM sys.databases

    RETURN 27
END

--Use this to test
DECLARE @returnval int

EXEC @returnval = test 

SELECT @returnval

Converting a sentence string to a string array of words in Java

This should help,

 String s = "This is a sample sentence";
 String[] words = s.split(" ");

this will make an array with elements as the string separated by " ".

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was able to resolve this by using my calling my high order component before exporting the class component. My problem was specifically using react-i18next and its withTranslation method, but here was the solution:

export default withTranslation()(Header);

And then I was able to call the class Component as originally I had hoped:

<Header someProp={someValue} />

Big-oh vs big-theta

Because my keyboard has an O key.
It does not have a T or an O key.

I suspect most people are similarly lazy and use O when they mean T because it's easier to type.

Exception: "URI formats are not supported"

     string ImagePath = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
        string a = "";
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream receiveStream = response.GetResponseStream();
            if (receiveStream.CanRead)
            { a = "OK"; }
        }

        catch { }

How to generate a random alpha-numeric string

Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;
    }
}

Output

uuid = 2d7428a6-b58c-4008-8575-f05549f16316

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Update: My original answer involved having the controller contain DOM-aware code, which breaks Angular conventions in favor of HTML. @dmackerman mentioned directives in a comment on my answer, and I completely missed that until just now. With that input, here's the right way to do this without breaking Angular or HTML conventions:


There's also a way to get both - grab the value of the element and use that to update the model in a directive:

<div ng-controller="Main">
    <input type="text" id="rootFolder" ng-model="rootFolders" disabled="disabled" value="Bob" size="40" />
</div>

and then:

app.directive('input', ['$parse', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if(attrs.value) {
                $parse(attrs.ngModel).assign(scope, attrs.value);
            }
        }
    };
}]);

You can of course modify the above directive to do more with the value attribute before setting the model to its value, including using $parse(attrs.value, scope) to treat the value attribute as an Angular expression (though I'd probably use a different [custom] attribute for that, personally, so the standard HTML attributes are consistently treated as constants).

Also, there is a similar question over at Making data templated in available to ng-model which may also be of interest.

How can I find the current OS in Python?

Something along the lines:

import os
if os.name == "posix":
    print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
    print("unknown OS")

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

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

LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).

RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.

WebView : to load html, static or dynamic pages.

For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html

Leave out quotes when copying from cell

To keep line breaks when pasting in notepad, replace this line in the macro:

strTemp = ActiveCell.Value

by:

strTemp = Replace(ActiveCell.Value, Chr(10), vbCrLf)

Regular expression to find URLs within a string

IMPROVED

Detects Urls like these:

Regex:

/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm

How can the Euclidean distance be calculated with NumPy?

With Python 3.8, it's very easy.

https://docs.python.org/3/library/math.html#math.dist

math.dist(p, q)

Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.

Roughly equivalent to:

sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

How do I restrict a float value to only two places after the decimal point in C?

You can still use:

float ceilf(float x); // don't forget #include <math.h> and link with -lm.

example:

float valueToRound = 37.777779;
float roundedValue = ceilf(valueToRound * 100) / 100;

Compare two files in Visual Studio

If you have VS installed, you could also call

"%VS110COMNTOOLS%..\IDE\vsdiffmerge.exe" "File1" "File2"

or for VS 2013

"%VS120COMNTOOLS%..\IDE\vsdiffmerge.exe" "File1" "File2"

Source: http://roadtoalm.com/2013/10/22/use-visual-studio-as-your-diff-and-merging-tool-for-local-files/

nodejs vs node on ubuntu 12.04

I had the same issue symbolic link helped me out: sudo ln -s /usr/bin/nodejs /usr/bin/node after that sudo npm install -g phantomjs-prebuilt

went smoothly

Generate fixed length Strings filled with whitespaces

String.format("%15s",s) // pads right
String.format("%-15s",s) // pads left

Great summary here

Playing a video in VideoView in Android

To confirm you video is in the correct format (resolution, bitrate, codec, etc.) check with the official documentation - extract below:

Standard definition (Low quality)
Video codec - H.264
Video resolution - 176 x 144 px
Video frame rate - 12 fps
Video bitrate - 56 Kbps
Audio codec - AAC-LC
Audio channels - (mono)
Audio bitrate - 24 Kbps

Standard definition (High quality)
Video codec - H.264
Video resolution - 480 x 360 px
Video frame rate - 30 fps
Video bitrate - 500 Kbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 128 Kbps

High definition 720p (N/A on all devices)
Video codec - H.264
Video resolution - 1280 x 720 px
Video frame rate - 30 fps
Video bitrate - 2 Mbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 192 Kbps

No module named setuptools

For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

sudo apt-get install -y python-setuptools

For python3:

sudo apt-get install -y python3-setuptools

After that, install your package again normally, using

sudo python setup.py install

That's all.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

If you're on Mac, restarting the DNS responder fixed the issue for me.

sudo killall -HUP mDNSResponder

JSON.NET Error Self referencing loop detected for type

Use JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings 
{ 
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});

Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings 
{ 
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
});

Pick what makes sense for the object you are serializing.

Reference http://james.newtonking.com/json/help/

What's the best way to set a single pixel in an HTML5 canvas?

If you are concerned about the speed then you could also consider WebGL.

Make cross-domain ajax JSONP request with jQuery

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});

Why can't I reference my class library?

I deleted *.csproj.user ( resharper file) of my project, then, close all tabs and reopen it. After that I was able to compile my project and there was no resharper warnings.

Invoke(Delegate)

If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).

In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created

private void btn_Click(object sender, EvenetArgs e)
{
    var thread1 = new Thread(SetText1);
    var thread2 = new Thread(SetText2);
    thread1.Start();
    thread2.Start();
}

private void SetText1() 
{
    textBox1.Text = "Test";
}

private void SetText2() 
{
    textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}

Converting a string to JSON object

Let's us consider you have string like

example : "name:lucy,age:21,gender:female"

_x000D_
_x000D_
function getJsonData(query){_x000D_
    let arrayOfKeyValues = query.split(',');_x000D_
    let modifiedArray =  new Array();_x000D_
    console.log(arrayOfKeyValues);_x000D_
    for(let i=0;i< arrayOfKeyValues.length;i++){_x000D_
        let arrayValues = arrayOfKeyValues[i].split(':');_x000D_
        let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';_x000D_
        modifiedArray.push(arrayString);_x000D_
    }_x000D_
    let jsonDataString = '{'+modifiedArray.toString()+'}';_x000D_
    let jsonData = JSON.parse(jsonDataString);_x000D_
    console.log(jsonData);_x000D_
    console.log(typeof jsonData);_x000D_
    return jsonData;_x000D_
}_x000D_
_x000D_
let query = "name:lucy,age:21,gender:female";_x000D_
let response = getJsonData(query);_x000D_
console.log(response);
_x000D_
_x000D_
_x000D_

`

How can you dynamically create variables via a while loop?

Use the exec() method. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value can do the following.

Python 2

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

Python 3

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.items():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

nano error: Error opening terminal: xterm-256color

  1. edit your .bash_profile file

    vim .bash_profile

  2. commnet

    #export TERM=xterm-256color

  3. add this

    export TERMINFO=/usr/share/terminfo

    export TERM=xterm-basic

    to your .bash_profile

  4. finally

    run:

    source .bash_profile

Android: How can I print a variable on eclipse console?

By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)

    JSONArray list = new JSONArray(); 
    if (jsonArray != null){
        int len = jsonArray.length();
        for (int i=0;i<len;i++)
        { 
            boolean flag;
            try {
                flag = jsonArray.get(i).toString().equals(obj.toString());
                //Excluding the item at position
                if (!flag) 
                {
                    list.put(jsonArray.get(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }  
        } 
    }
    jsonArray = list;

Javascript Drag and drop for touch devices

I had the same solution as gregpress answer, but my draggable items used a class instead of an id. It seems to work.

var $target = $(event.target);  
if( $target.hasClass('draggable') ) {  
    event.preventDefault();  
}

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

How to temporarily exit Vim and go back

If you are on a Unix system, Ctrl + Z will suspend Vim and give you a shell.

Type fg to go back. Note that Vim creates a swap file while editing, and suspending Vim wouldn't delete that file (you aren't exiting Vim after all). On dumb terminals, this method was pretty standard for edit-compile-edit cycles using vi. I just found out that for me, gVim minimizes on typing Z.

Import Python Script Into Another?

Following worked for me and it seems very simple as well:

Let's assume that we want to import a script ./data/get_my_file.py and want to access get_set1() function in it.

import sys
sys.path.insert(0, './data/')
import get_my_file as db

print (db.get_set1())

What do the terms "CPU bound" and "I/O bound" mean?

When your program is waiting for I/O (ie. a disk read/write or network read/write etc), the CPU is free to do other tasks even if your program is stopped. The speed of your program will mostly depend on how fast that IO can happen, and if you want to speed it up you will need to speed up the I/O.

If your program is running lots of program instructions and not waiting for I/O, then it is said to be CPU bound. Speeding up the CPU will make the program run faster.

In either case, the key to speeding up the program might not be to speed up the hardware, but to optimize the program to reduce the amount of IO or CPU it needs, or to have it do I/O while it also does CPU intensive stuff.

Python: Best way to add to sys.path relative to the current running script

When we try to run python file with path from terminal.

import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)

Save the file (test.py).

Runing system.

Open terminal and go the that dir where is save file. then write

python test.py "/home/saiful/Desktop/bird.jpg"

Hit enter

Output:

File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg

What's a clean way to stop mongod on Mac OS X?

Check out these docs:

http://www.mongodb.org/display/DOCS/Starting+and+Stopping+Mongo#StartingandStoppingMongo-SendingaUnixINTorTERMsignal

If you started it in a terminal you should be ok with a ctrl + 'c' -- this will do a clean shutdown.

However, if you are using launchctl there are specific instructions for that which will vary depending on how it was installed.

If you are using Homebrew it would be launchctl stop homebrew.mxcl.mongodb

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

Android Studio - How to Change Android SDK Path

in windows press ctrl+shift+alt+s which will open project properties where you can find first option named SDK Location click on it and there you can change SDK path, JDK path and NDK path also

How ViewBag in ASP.NET MVC works

The ViewBag is an System.Dynamic.ExpandoObject as suggested. The properties in the ViewBag are essentially KeyValue pairs, where you access the value by the key. In this sense these are equivalent:

ViewBag.Foo = "Bar";
ViewBag["Foo"] = "Bar";

How do I draw a circle in iOS Swift?

Here is my version using Swift 5 and Core Graphics.

I have created a class to draw two circles. The first circle is created using addEllipse(). It puts the ellipse into a square, thus creating a circle. I find it surprising that there is no function addCircle(). The second circle is created using addArc() of 2pi radians

import UIKit

@IBDesignable
class DrawCircles: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else {
            print("could not get graphics context")
            return
        }

        context.setLineWidth(2)

        context.setStrokeColor(UIColor.blue.cgColor)

        context.addEllipse(in: CGRect(x: 30, y: 30, width: 50.0, height: 50.0))

        context.strokePath()

        context.setStrokeColor(UIColor.red.cgColor)

        context.beginPath() // this prevents a straight line being drawn from the current point to the arc

        context.addArc(center: CGPoint(x:100, y: 100), radius: 20, startAngle: 0, endAngle: 2.0*CGFloat.pi, clockwise: false)

        context.strokePath()
    }
}

in your ViewController's didViewLoad() add the following:

let myView = DrawCircles(frame: CGRect(x: 50, y: 50, width: 300, height: 300))

self.view.addSubview(myView)

When it runs it should look like this. I hope you like my solution!

enter image description here

How do I use the JAVA_OPTS environment variable?

Actually, you can, even though accepted answer saying that you can't.

There is a _JAVA_OPTIONS environment variable, more about it here

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

Currency formatting in Python

Oh, that's an interesting beast.

I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point

I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:

http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup

The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.

Once you have that installed you can do the following:

>>> from kiwi.datatypes import currency
>>> v = currency('10.5').format()

Which will then give you:

'$10.50'

or

'10,50 kr'

Depending on the currently selected locale.

The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

How to pass multiple values through command argument in Asp.net?

You can try this:

CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'

Oracle date difference to get number of years

I'd use months_between, possibly combined with floor:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;

select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;

floor makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor.

Difference between Statement and PreparedStatement

nothing much to add,

1 - if you want to execute a query in a loop (more than 1 time), prepared statement can be faster, because of optimization that you mentioned.

2 - parameterized query is a good way to avoid SQL Injection. Parameterized querys are only available in PreparedStatement.

'True' and 'False' in Python

While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

I thought Python treats anything with value as True. Why is this happening?

Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

if 0:
    print("Won't get here")

This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

from decimal import *
from fractions import *

if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
    print("Won't get here")

Here are the other value which evaluate to False:

if None or False or '' or () or [] or {} or set() or range(0):
    print("Won't get here")

Sources:

  1. Python Truth Value Testing is Awesome
  2. Truth Value Testing (in Built-in Types)

How do I disable form resizing for users?

I always use this:

// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;

This way you can always resize the form from Designer without changing code.

What's the function like sum() but for multiplication? product()?

Actually, Guido vetoed the idea: http://bugs.python.org/issue1093

But, as noted in that issue, you can make one pretty easily:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)

Return from a promise then()

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

Hope this helps!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }

jQuery toggle animation

$('.login').toggle(
    function(){
        $('#panel').animate({
            height: "150", 
            padding:"20px 0",
            backgroundColor:'#000000',
            opacity:.8
        }, 500);
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
    },
    function(){
        $('#panel').animate({
            height: "0", 
            padding:"0px 0",
            opacity:.2
        }, 500);     
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
});

Password masking console application

 string pass = "";
 Console.WriteLine("Enter your password: ");
 ConsoleKeyInfo key;

 do {
  key = Console.ReadKey(true);

  if (key.Key != ConsoleKey.Backspace) {
   pass += key.KeyChar;
   Console.Write("*");
  } else {
   Console.Write("\b \b");
   char[] pas = pass.ToCharArray();
   string temp = "";
   for (int i = 0; i < pass.Length - 1; i++) {
    temp += pas[i];
   }
   pass = temp;
  }
 }
 // Stops Receving Keys Once Enter is Pressed
 while (key.Key != ConsoleKey.Enter);

 Console.WriteLine();
 Console.WriteLine("The Password You entered is : " + pass);

Describe table structure

In DBTools for Sybase, it's sp_columns your_table_name.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

What is the difference between iterator and iterable and how to use them?

Implementing Iterable interface allows an object to be the target of the "foreach" statement.

class SomeClass implements Iterable<String> {}

class Main 
{
  public void method()
  {
     SomeClass someClass = new SomeClass();
     .....

    for(String s : someClass) {
     //do something
    }
  }
}

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

How to limit text width

You can apply css like this:

div {
   word-wrap: break-word;
   width: 100px;
}

Usually browser does not break words, but word-wrap: break-word; will force it to break words too.

Demo: http://jsfiddle.net/Mp7tc/

More info about word-wrap

Passing additional variables from command line to make

There's another option not cited here which is included in the GNU Make book by Stallman and McGrath (see http://www.chemie.fu-berlin.de/chemnet/use/info/make/make_7.html). It provides the example:

archive.a: ...
ifneq (,$(findstring t,$(MAKEFLAGS)))
        +touch archive.a
        +ranlib -t archive.a
else
        ranlib archive.a
endif

It involves verifying if a given parameter appears in MAKEFLAGS. For example .. suppose that you're studying about threads in c++11 and you've divided your study across multiple files (class01, ... , classNM) and you want to: compile then all and run individually or compile one at a time and run it if a flag is specified (-r, for instance). So, you could come up with the following Makefile:

CXX=clang++-3.5
CXXFLAGS = -Wall -Werror -std=c++11
LDLIBS = -lpthread

SOURCES = class01 class02 class03

%: %.cxx
    $(CXX) $(CXXFLAGS) -o [email protected] $^ $(LDLIBS)
ifneq (,$(findstring r,  $(MAKEFLAGS)))
    ./[email protected]
endif

all: $(SOURCES)

.PHONY: clean

clean:
    find . -name "*.out" -delete

Having that, you'd:

  • build and run a file w/ make -r class02;
  • build all w/ make or make all;
  • build and run all w/ make -r (suppose that all of them contain some certain kind of assert stuff and you just want to test them all)

How can I get column names from a table in Oracle?

The answer is here: http://php.net/manual/en/function.mysql-list-fields.php I'd use the following code in your case:

$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$fields = array();
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $fields[] = $row['Field'];
    }
}

How to scale a UIImageView proportionally?

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 


//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
//CGRect frame = imageView.frame;
//frame.size.width = 100;
//imageView.frame = frame;

//original lines that deal with frame commented out, yo.
imageView.frame = CGRectMake(10, 20, 60, 60);

...

//Add image view
[myView addSubview:imageView]; 

The original code posted at the top worked well for me in iOS 4.2.

I found that creating a CGRect and specifying all the top, left, width, and height values was the easiest way to adjust the position in my case, which was using a UIImageView inside a table cell. (Still need to add code to release objects)

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

Android: How to create a Dialog without a title?

Set the title to empty string using builder.

    Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("");
...
    builder.show();

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

[Vue warn]: Cannot find element

I think sometimes stupid mistakes can give us this error.

<div id="#main"> <--- id with hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

To

<div id="main"> <--- id without hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

Object reference not set to an instance of an object.

I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);
}

This makes it possible to call:

string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

Django CSRF check failing with an Ajax POST request

Easy ajax calls with Django

(26.10.2020)
This is in my opinion much cleaner and simpler than the correct answer.

The view

@login_required
def some_view(request):
    """Returns a json response to an ajax call. (request.user is available in view)"""
    # Fetch the attributes from the request body
    data_attribute = request.GET.get('some_attribute')  # Make sure to use POST/GET correctly
    # DO SOMETHING...
    return JsonResponse(data={}, status=200)

urls.py

urlpatterns = [
    path('some-view-does-something/', views.some_view, name='doing-something'),
]

The ajax call

The ajax call is quite simple, but is sufficient for most cases. You can fetch some values and put them in the data object, then in the view depicted above you can fetch their values again via their names.

You can find the csrftoken function in django's documentation. Basically just copy it and make sure it is rendered before your ajax call so that the csrftoken variable is defined.

$.ajax({
    url: "{% url 'doing-something' %}",
    headers: {'X-CSRFToken': csrftoken},
    data: {'some_attribute': some_value},
    type: "GET",
    dataType: 'json',
    success: function (data) {
        if (data) {
            console.log(data);
            // call function to do something with data
            process_data_function(data);
        }
    }
});

Add HTML to current page with ajax

This might be a bit off topic but I have rarely seen this used and it is a great way to minimize window relocations as well as manual html string creation in javascript.

This is very similar to the one above but this time we are rendering html from the response without reloading the current window.

If you intended to render some kind of html from the data you would receive as a response to the ajax call, it might be easier to send a HttpResponse back from the view instead of a JsonResponse. That allows you to create html easily which can then be inserted into an element.

The view

# The login required part is of course optional
@login_required
def create_some_html(request):
    """In this particular example we are filtering some model by a constraint sent in by 
    ajax and creating html to send back for those models who match the search"""
    # Fetch the attributes from the request body (sent in ajax data)
    search_input = request.GET.get('search_input')

    # Get some data that we want to render to the template
    if search_input:
        data = MyModel.objects.filter(name__contains=search_input) # Example
    else:
        data = []

    # Creating an html string using template and some data
    html_response = render_to_string('path/to/creation_template.html', context = {'models': data})

    return HttpResponse(html_response, status=200)

The html creation template for view

creation_template.html

{% for model in models %}
   <li class="xyz">{{ model.name }}</li>
{% endfor %}

urls.py

urlpatterns = [
    path('get-html/', views.create_some_html, name='get-html'),
]

The main template and ajax call

This is the template where we want to add the data to. In this example in particular we have a search input and a button that sends the search input's value to the view. The view then sends a HttpResponse back displaying data matching the search that we can render inside an element.

{% extends 'base.html' %}
{% load static %}
{% block content %}
    <input id="search-input" placeholder="Type something..." value="">
    <button id="add-html-button" class="btn btn-primary">Add Html</button>
    <ul id="add-html-here">
        <!-- This is where we want to render new html -->
    </ul>
{% end block %}

{% block extra_js %}
    <script>
        // When button is pressed fetch inner html of ul
        $("#add-html-button").on('click', function (e){
            e.preventDefault();
            let search_input = $('#search-input').val();
            let target_element = $('#add-html-here');
            $.ajax({
                url: "{% url 'get-html' %}",
                headers: {'X-CSRFToken': csrftoken},
                data: {'search_input': search_input},
                type: "GET",
                dataType: 'html',
                success: function (data) {
                    if (data) {
                        /* You could also use json here to get multiple html to
                        render in different places */
                        console.log(data);
                        // Add the http response to element
                        target_element.html(data);
                    }
                }
            });
        })
    </script>
{% endblock %}

Deleting DataFrame row in Pandas based on column value

Just adding another way for DataFrame expanded over all columns:

for column in df.columns:
   df = df[df[column]!=0]

Example:

def z_score(data,count):
   threshold=3
   for column in data.columns:
       mean = np.mean(data[column])
       std = np.std(data[column])
       for i in data[column]:
           zscore = (i-mean)/std
           if(np.abs(zscore)>threshold):
               count=count+1
               data = data[data[column]!=i]
   return data,count

Install Node.js on Ubuntu

Here is the full description to create the first program using the express generator,

Ubuntu's package manager

To install Node.js and npm via apt-get, run these commands:

sudo apt-get update
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm

Express application generator:

$ npm install express-generator -g

Display the command options with the -h option:

$ express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

For example, the following creates an Express application named myapp in the current working directory:

$ express myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.jade
   create : myapp/views/layout.jade
   create : myapp/views/error.jade
   create : myapp/bin
   create : myapp/bin/www

Then install dependencies:

$ cd myapp
$ npm install

Run the app with this command:

$ DEBUG=myapp:* npm start

Then load http://localhost:3000/ in your browser to access the application.

The generated application has the following directory structure:

+-- app.js
+-- bin
¦   +-- www
+-- package.json
+-- public
¦   +-- images
¦   +-- javascripts
¦   +-- stylesheets
¦       +-- style.css
+-- routes
¦   +-- index.js
¦   +-- users.js
+-- views
    +-- error.jade
    +-- index.jade
    +-- layout.jade

7 directories, 9 files

How to assign a value to a TensorFlow variable?

Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34 

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.

How to fully clean bin and obj folders within Visual Studio?

I use VisualStudioClean which is easy to understand and predictable. Knowing how it works and what files it is going to delete relieves me.

Previously I tried VSClean (note VisualStudioClean is not VSClean), VSClean is more advanced, it has many configurations that sometimes makes me wondering what files it is going to delete? One mis-configuration will result in lose of my source codes. Testing how the configuration will work need backing up all my projects which take a lot of times, so in the end I choose VisualStudioClean instead.

Conclusion : VisualStudioClean if you want basic cleaning, VSClean for more complex scenario.

Python date string to date object

Directly related question:

What if you have

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above.

Answer:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

How to script FTP upload and download?

This script generates the command file then pipes the command file to the ftp program, creating a log along the way. Finally print the original bat file, the command files and the log of this session.

@echo on
@echo off > %0.ftp
::== GETmy!dir.bat
>> %0.ftp echo a00002t
>> %0.ftp echo iasdad$2
>> %0.ftp echo help
>> %0.ftp echo prompt
>> %0.ftp echo ascii
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir WORKLOAD.CP1c.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo **************************************************   
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo quit
ftp -d -v -s:%0.ftp 150.45.12.18 > %0.log
type %0.bat 
type %0.ftp 
type %0.log 

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

MySQL: Insert record if not exists in table

insert into customer_keyskill(customerID, keySkillID)
select  2,1 from dual
where not exists ( 
    select  customerID  from customer_keyskill 
    where customerID = 2 
    and keySkillID = 1 )

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use

StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64

Visual Studio move project to a different folder

in visual studio comunity 2019, i did what Victor David Francisco Enrique says, but needed only to delete the .vs invisbile folder

Close window automatically after printing dialog closes

This worked for me 11/2020 <body onafterprint="window.close()"> ... simple.

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
    l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
    l.value+= 'log in\n';_x000D_
    l.focus();_x000D_
    l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
_x000D_
_x000D_

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
    l.value+= 'alert in\n';_x000D_
    alert('alert!');_x000D_
    l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
    l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
_x000D_
_x000D_

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I have faced same issue a couple of days ago while updating the database. In my case, there was few new non nullable columns added for maintenance which was not supplied in the code which is causing the exception. I figure out those fields and supplied values for them and its resolved.

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

check the code below this will be helpful for you:

<script type="text/javascript">
  window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

TypeError: 'dict' object is not callable

A more functional approach would be by using dict.get

input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))

One can observe that the conversion is a little clumsy, better would be to use the abstraction of function composition:

def compose2(f, g):
    return lambda x: f(g(x))

strikes = list(map(compose2(number_map.get, int), input_str.split()))

Example:

list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]

Obviously in Python 3 you would avoid the explicit conversion to a list. A more general approach for function composition in Python can be found here.

(Remark: I came here from the Design of Computer Programs Udacity class, to write:)

def word_score(word):
    "The sum of the individual letter point scores for this word."
    return sum(map(POINTS.get, word))

ADB not recognising Nexus 4 under Windows 7

I had the same problem, but I didn't want to change to PTP mode. This is how I fixed it with MTP still enabled.

  1. Uninstalled Google USB Driver from Eclipse in the Android SDK Manager.
  2. Uninstalled the driver from Device Manager - click box for "delete driver from my computer"
  3. Unplugged and re-plugged my phone into the computer.
  4. Windows "improperly" installed drivers for the Nexus 4.
  5. The Nexus 4 was now showing up in My Computer like a drive.
  6. Reinstall Google USB Driver in SDK Manager.
  7. Update Nexus 4 driver in Device Manager.
  8. Everything works.

SQL left join vs multiple tables on FROM line?

I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.

Why do we need to use flatMap?

Here to show equivalent implementation of a flatMap using subscribes.

Without flatMap:

this.searchField.valueChanges.debounceTime(400)
.subscribe(
  term => this.searchService.search(term)
  .subscribe( results => {
      console.log(results);  
      this.result = results;
    }
  );
);

With flatMap:

this.searchField.valueChanges.debounceTime(400)
    .flatMap(term => this.searchService.search(term))
    .subscribe(results => {
      console.log(results);
      this.result = results;
    });

http://plnkr.co/edit/BHGmEcdS5eQGX703eRRE?p=preview

Hope it could help.

Olivier.

ListAGG in SQLSERVER

In SQL Server 2017 STRING_AGG is added:

SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1

Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016

Numbering rows within groups in a data frame

Use ave, ddply, dplyr or data.table:

df$num <- ave(df$val, df$cat, FUN = seq_along)

or:

library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))

or:

library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())

or (the most memory efficient, as it assigns by reference within DT):

library(data.table)
DT <- data.table(df)

DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]

get the titles of all open windows

Something like this:

using System.Diagnostics;

Process[] processlist = Process.GetProcesses();

foreach (Process process in processlist)
{
    if (!String.IsNullOrEmpty(process.MainWindowTitle))
    {
        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
    }
}

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

Java: How to convert String[] to List or Set

Arrays.asList() would do the trick here.

String[] words = {"ace", "boom", "crew", "dog", "eon"};   

List<String> wordList = Arrays.asList(words);  

For converting to Set, you can do as below

Set<T> mySet = new HashSet<T>(Arrays.asList(words)); 

How do I execute multiple SQL Statements in Access' Query Editor?

create a macro like this

Option Compare Database

Sub a()

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

End Sub

Count number of rows matching a criteria

grep command can be used

CA = mydata[grep("CA", mydata$sCode, ]

nrow(CA)

How to undo "git commit --amend" done instead of "git commit"

Simple Solution Solution Works Given: If your HEAD commit is in sync with remote commit.

  • Create one more branch in your local workspace, and keep it in sync with your remote branch.
  • Cherry pick the HEAD commit from the branch (where git commit --amend) was performed onto the newly created branch.

The cherry-picked commit will only contain your latest changes, not the old changes. You can now just rename this commit.

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

Assign width to half available screen width declaratively

Using constraints layout

  1. Add a Guideline
  2. Set the percentage to 50%
  3. Constrain your view to the Guideline and the parent.

enter image description here

If you are having trouble changing it to a percentage, then see this answer.

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    
</android.support.constraint.ConstraintLayout>

How to make a SIMPLE C++ Makefile

I suggest (note that the indent is a TAB):

tool: tool.o file1.o file2.o
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

or

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o

The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).

Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).

Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.

Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:

CFLAGS = -Wall
LDLIBS = -lm

One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:

CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)

The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:

override CPPFLAGS += -MMD
include $(wildcard *.d)

-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.

For sure, a well written Makefile should also include clean and distclean rules:

clean:
    $(RM) *.o *.d

distclean: clean
    $(RM) tool

Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.

The all rule is also appreciated. In order to work, it should be the first rule of your file:

all: tool

You may also add an install rule:

PREFIX = /usr/local
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.

One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).

So to summarise, your full Makefile should look like:

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)

all: tool
tool: tool.o file1.o file2.o
clean:
    $(RM) *.o *.d
distclean: clean
    $(RM) tool
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

Concatenating two std::vectors

vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

How do I update the GUI from another thread?

Fire and forget extension method for .NET 3.5+

using System;
using System.Windows.Forms;

public static class ControlExtensions
{
    /// <summary>
    /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="code"></param>
    public static void UIThread(this Control @this, Action code)
    {
        if (@this.InvokeRequired)
        {
            @this.BeginInvoke(code);
        }
        else
        {
            code.Invoke();
        }
    }
}

This can be called using the following line of code:

this.UIThread(() => this.myLabel.Text = "Text Goes Here");

Selenium Finding elements by class name in python

By.CLASS_NAME was not yet mentioned:

from selenium.webdriver.common.by import By

driver.find_element(By.CLASS_NAME, "content")

This is the list of attributes which can be used as locators in By:

CLASS_NAME
CSS_SELECTOR
ID
LINK_TEXT
NAME
PARTIAL_LINK_TEXT
TAG_NAME
XPATH

Android: How do I get string from resources using its name?

getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Remove border radius from Select tag in bootstrap 3

the class is called:

.form-control { border-radius: 0; }

be sure to insert the override after including bootstraps css.

If you ONLY want to remove the radius on select form-controls use

select.form-control { ... }

instead

EDIT: works for me on chrome, firefox, opera, and safari, IE9+ (all running on linux/safari & IE on playonlinux)

Convert a string representation of a hex dump to a byte array using Java?

The HexBinaryAdapter provides the ability to marshal and unmarshal between String and byte[].

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

public byte[] hexToBytes(String hexString) {
     HexBinaryAdapter adapter = new HexBinaryAdapter();
     byte[] bytes = adapter.unmarshal(hexString);
     return bytes;
}

That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Find out time it took for a python script to complete execution

import sys
import timeit

start = timeit.default_timer()

#do some nice things...

stop = timeit.default_timer()
total_time = stop - start

# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)

sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))

Why is __dirname not defined in node REPL?

As @qiao said, you can't use __dirname in the node repl. However, if you need need this value in the console, you can use path.resolve() or path.dirname(). Although, path.dirname() will just give you a "." so, probably not that helpful. Be sure to require('path').

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

When to use malloc for char pointers

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);

How to extract img src, title and alt from html using php?

Here is THE solution, in PHP:

Just download QueryPath, and then do as follows:

$doc= qp($myHtmlDoc);

foreach($doc->xpath('//img') as $img) {

   $src= $img->attr('src');
   $title= $img->attr('title');
   $alt= $img->attr('alt');

}

That's it, you're done !

Newline in string attribute

For those that have tried every answer to this question and are still scratching their heads as to why none of them work for you, you might have ran into a form of the issue I ran into.

My TextBlock.Text property was inside of a ToolTipService.ToolTip element and it was databound to a property of an object whose data was being pulled from a SQL stored procedure. Now the data from this particular property within the stored procedure was being pulled from a SQL function.

Since nothing had worked for me, I gave up my search and created the converter class below:

public class NewLineConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = string.Empty;

        if (value.IsNotNull())
        {
            s = value.ToString();

            if (s.Contains("\\r\\n"))
                s = s.Replace("\\r\\n", Environment.NewLine);

            if (s.Contains("\\n"))
                s = s.Replace("\\n", Environment.NewLine);

            if (s.Contains("&#x0a;&#x0d;"))
                s = s.Replace("&#x0a;&#x0d;", Environment.NewLine);

            if (s.Contains("&#x0a;"))
                s = s.Replace("&#x0a;", Environment.NewLine);

            if (s.Contains("&#x0d;"))
                s = s.Replace("&#x0d;", Environment.NewLine);

            if (s.Contains("&#10;&#13;"))
                s = s.Replace("&#10;&#13;", Environment.NewLine);

            if (s.Contains("&#10;"))
                s = s.Replace("&#10;", Environment.NewLine);

            if (s.Contains("&#13;"))
                s = s.Replace("&#13;", Environment.NewLine);

            if (s.Contains("<br />"))
                s = s.Replace("<br />", Environment.NewLine);

            if (s.Contains("<LineBreak />"))
                s = s.Replace("<LineBreak />", Environment.NewLine);
        }

        return s;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I ended up having to use the Enivornment.NewLine method from @dparker's answer. I instructed the converter to look for any possible textual representation of a newline and replace it with Environment.NewLine.

This worked!

However, I was still perplexed as to why none of the other methods worked with databound properties.

I left a comment on @BobKing's accepted answer:

@BobKing - This doesn't seem to work in the ToolTipService.ToolTip when binding to a field that has the line feeds embedded from a SQL sproc.

He replied with:

@CodeMaverick If you're binding to text with the new lines embedded, they should probably be real char 10 values (or 13's) and not the XML sentinels. This is only if you want to write literal new lines in XAML files.

A light bulb went off!

I went into my SQL function, replaced my textual representations of newlines with ...

CHAR( 13 ) + CHAR( 10 )

... removed the converter from my TextBlock.Text binding, and just like that ... it worked!

PHP cURL error code 60

First you have to download the certificate from this link

https://curl.haxx.se/ca/cacert.pem

and put it in a location you want the name of downloadable file is : cacert.pem So in my case I will put it under C:\wamp64\bin\php\cacert.pem

Then you have to specify the location of the php.ini file

For example, I am using php 7 the php.ini file is located at : C:\wamp64\bin\php\php7.0.10\php.ini

So access to that file and uncommit this line ;openssl.cafile

also update it to be looks like this openssl.cafile="C:\wamp64\bin\php\cacert.pem"

Finally restart your apache server and that's all

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

How do I remove duplicates from a C# array?

List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
    if (!myStringList.Contains(s))
    {
        myStringList.Add(s);
    }
}

This is O(n^2), which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection.

Triangle Draw Method

Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online

Reshaping data.frame from wide to long format

reshape() takes a while to get used to, just as melt/cast. Here is a solution with reshape, assuming your data frame is called d:

reshape(d, 
        direction = "long",
        varying = list(names(d)[3:7]),
        v.names = "Value",
        idvar = c("Code", "Country"),
        timevar = "Year",
        times = 1950:1954)

"Press Any Key to Continue" function in C

You can try more system indeppended method: system("pause");

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

MySQL SELECT LIKE or REGEXP to match multiple words in one record

you need to do something like this,

SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus.*2100';

or

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus)+.*(2100)+';

How does "FOR" work in cmd batch file?

It works for me, try it.

for /f "tokens=* delims=;" %g in ('echo %PATH%') do echo %g%

How to convert java.util.Date to java.sql.Date?

Method for comparing 2 dates (util.date or sql.date)

 public static boolean isSameDay(Date a, Date b) {
    Calendar calA = new GregorianCalendar();
    calA.setTime(a);

    Calendar calB = new GregorianCalendar();
    calB.setTime(b);

    final int yearA = calA.get(Calendar.YEAR);
    final int monthA = calA.get(Calendar.MONTH);
    final int dayA = calA.get(Calendar.DAY_OF_YEAR);

    final int yearB = calB.get(Calendar.YEAR);
    final int monthB = calB.get(Calendar.MONTH);
    final int dayB = calB.get(Calendar.DAY_OF_YEAR);

    return yearA == yearB && monthA == monthB && dayA == dayB;
}

How to Store Historical Data

I think you approach is correct. Historical table should be a copy of the main table without indexes, make sure you have update timestamp in the table as well.

If you try the other approach soon enough you will face problems:

  • maintenance overhead
  • more flags in selects
  • queries slowdown
  • growth of tables, indexes

SQL Server ON DELETE Trigger

Better to use:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

Select and trigger click event of a radio button in jquery

My solution is a bit different:

$( 'input[name="your_radio_input_name"]:radio:first' ).click();

How do I call paint event?

In a method of your Form or Control, you have 3 choices:

this.Invalidate();  // request a delayed Repaint by the normal MessageLoop system    
this.Update();      // forces Repaint of invalidated area 
this.Refresh();     // Combines Invalidate() and Update()

Normally, you would just call Invalidate() and let the system combine that with other Screen updates. If you're in a hurry you should call Refresh() but then you run the risk that it will be repainted several times consecutively because of other controls (especially the Parent) Invalidating.

The normal way Windows (Win32 and WinForms.Net) handles this is to wait for the MessageQueue to run empty and then process all invalidated screen areas. That is efficient because when something changes that usually cascades into other things (controls) changing as well.

The most common scenario for Update() is when you change a property (say, label1.Text, which will invalidate the Label) in a for-loop and that loop is temporarily blocking the Message-Loop. Whenever you use it, you should ask yourself if you shouldn't be using a Thread instead. But the answer is't always Yes.

Formatting a float to 2 decimal places

String.Format("{0:#,###.##}", value)

A more complex example from String Formatting in C#:

String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);

This will output “$1,240.00" if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

get dataframe row count based on conditions

For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

In [1]: import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))


In [2]: df.head()
Out[2]:
          A         B         C         D
0 -2.019868  1.227246 -0.489257  0.149053
1  0.223285 -0.087784 -0.053048 -0.108584
2 -0.140556 -0.299735 -1.765956  0.517803
3 -0.589489  0.400487  0.107856  0.194890
4  1.309088 -0.596996 -0.623519  0.020400

In [3]: %time sum((df['A']>0) & (df['B']>0))
CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
Wall time: 1.12 ms
Out[3]: 4

In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
Wall time: 1.42 ms
Out[4]: 4

Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

delete a column with awk or sed

This might work for you (GNU sed):

sed -i -r 's/\S+//3' file

If you want to delete the white space before the 3rd field:

sed -i -r 's/(\s+)?\S+//3' file

jquery beforeunload when closing (not leaving) the page?

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Is it possible to use pip to install a package from a private GitHub repository?

It also works with Bitbucket:

pip install git+ssh://[email protected]/username/projectname.git

Pip will use your SSH keys in this case.