Programs & Examples On #Matlab deployment

MATLAB is a high-level language and programming environment developed by MathWorks. This tag relates to the deployment of MATLAB algorithms and applications, including integration of MATLAB code with other languages such as C/C++, .NET and Java, and use of add-on products such as MATLAB Compiler, MATLAB Builder NE for .NET, MATLAB Builder JA for Java and MATLAB Builder EX for Excel.

filter items in a python dictionary where keys contain a specific string

Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.

If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:

I'm using iteritems() since you tagged your question with

results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])

Now the result will be in a list with some_function applied to each key/value pair of the dictionary, that has foo in its key.

If you just want to deal with the values and ignore the keys, just change the list comprehension:

results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])

some_function can be any callable, so a lambda would work as well:

results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])

The inner list is actually not required, as you can pass a generator expression to map as well:

>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]

Git merge reports "Already up-to-date" though there is a difference

Faced this scenario using Git Bash.

Our repository has multiple branches and each branch has a different commit cycle and merge happens once in a while. Old_Branch was used as a parent for New_Branch

Old_Branch was updated with some changes which required to be merged with New_Branch

Was using below pull command without any branch to get all sources from all branches.

git pull origin

Strangely this doesn't pull all the commits from all the branches. Had thought it so as the indicated shows almost all branches and tags.

So to fix this had checked out the Old_Branch pulled the latest using

git checkout Old_Branch

git pull origin Old_Branch

Now checked out New_Branch

git checkout New_Branch

Pulled it to be sure

git pull origin New_Branch

git merge Old_Branch

And viola got conflicts to fix from Old_Branch to New_Branch :) which was expected

pandas python how to count the number of records or rows in a dataframe

Simple method to get the records count:

df.count()[0]

How to work offline with TFS

There are couple of little visual studio extensions for this purpose:

  1. For VS2010 & TFS 2010, try this
  2. For VS2012 & TFS 2010, use this

In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.

Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.

An error occurred while collecting items to be installed (Access is denied)

On Windows 7, the Program Files directory is protected so apps can't automatically write there. The simplest solution I've heard is just to install Eclipse into a user-writable location instead. For example, C:\Java\Eclipse

You should be able to just move your entire eclipse directory, there's no registry entries or anything else that ties Eclipse to the place where you extracted it.

[Edit] Have you checked that the directory it is complaining about i actually writable? Other than that, I really don't have any ideas. I haven't worked on Windows in several years and never with Win7. My only other suggestion is to just download the latest Eclipse, install it to a new location (do NOT intall it over top of your existing Eclipse), and point it to your existing workspace.

Get specific line from text file using just shell script

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

MySQL Install: ERROR: Failed to build gem native extension

I had also forgotten to actually install MySQL in the first place. Following this guide helped a lot.

http://www.djangoapp.com/blog/2011/07/24/installation-of-mysql-server-on-mac-os-x-lion/

As well as adding these lines to my .profile:

export PATH="/usr/local/mysql/bin:$PATH"
alias mysql=/usr/local/mysql/bin/mysql
alias mysqladmin=/usr/local/mysql/bin/mysqladmin

Angularjs loading screen on ajax request

Include this in your "app.config":

 $httpProvider.interceptors.push('myHttpInterceptor');

And add this code:

app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
    $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
    var checker = function(parameters,status){
            //YOU CAN USE parameters.url TO IGNORE SOME URL
            if(status == "request"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
                $('#loading_view').show();
            }
            if(status == "response"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;

            }
            if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
                $rootScope.ActiveAjaxConectionsWithouthNotifications=0;
                $('#loading_view').hide();

            }


    };
return {
    'request': function(config) {
        checker(config,"request");
        return config;
    },
   'requestError': function(rejection) {
       checker(rejection.config,"request");
      return $q.reject(rejection);
    },
    'response': function(response) {
         checker(response.config,"response");
      return response;
    },
   'responseError': function(rejection) {
        checker(rejection.config,"response");
      return $q.reject(rejection);
    }
  };
});

How can I assign the output of a function to a variable using bash?

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

VAR=$(scan)

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () {
    local nl=$'\x0a';  # that's just \n
    echo "output${nl}${nl}" # 2 in the string + 1 by echo
}

# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"

echo "${VAR}---"

prints (3 newlines kept):

output


---

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

function scan3() {
    local -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

VAR="some prior value which will get overwritten"

# you pass the name of the variable. VAR will be modified.
scan3 VAR

# newlines are also preserved.
echo "${VAR}==="

prints:

output

===

This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

How can I clear the Scanner buffer in Java?

Try this:

in.nextLine();

This advances the Scanner to the next line.

How to display HTML tags as plain text

There is another way...

header('Content-Type: text/plain; charset=utf-8');

This makes the whole page served as plain text... better is htmlspecialchars...

Hope this helps...

What's the difference between .bashrc, .bash_profile, and .environment?

A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.

Iterating over Numpy matrix rows to apply a function each?

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

VB.NET - Remove a characters from a String

You can use the string.replace method

string.replace("character to be removed", "character to be replaced with")

Dim strName As String
strName.Replace("[", "")

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

OpenSSL: unable to verify the first certificate for Experian URL

I came across the same issue installing my signed certificate on an Amazon Elastic Load Balancer instance.

All seemed find via a browser (Chrome) but accessing the site via my java client produced the exception javax.net.ssl.SSLPeerUnverifiedException

What I had not done was provide a "certificate chain" file when installing my certificate on my ELB instance (see https://serverfault.com/questions/419432/install-ssl-on-amazon-elastic-load-balancer-with-godaddy-wildcard-certificate)

We were only sent our signed public key from the signing authority so I had to create my own certificate chain file. Using my browser's certificate viewer panel I exported each certificate in the signing chain. (The order of the certificate chain in important, see https://forums.aws.amazon.com/message.jspa?messageID=222086)

Mean filter for smoothing images in Matlab

and the convolution is defined through a multiplication in transform domain:

conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))

if one channel is considered... for more channels this has to be done every channel

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Calling startActivity() from outside of an Activity?

When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.

Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);

Hope this will help.

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Getting distance between two points based on latitude/longitude

For people (like me) coming here via search engine and just looking for a solution which works out of the box, I recommend installing mpu. Install it via pip install mpu --user and use it like this to get the haversine distance:

import mpu

# Point one
lat1 = 52.2296756
lon1 = 21.0122287

# Point two
lat2 = 52.406374
lon2 = 16.9251681

# What you were looking for
dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2))
print(dist)  # gives 278.45817507541943.

An alternative package is gpxpy.

If you don't want dependencies, you can use:

import math


def distance(origin, destination):
    """
    Calculate the Haversine distance.

    Parameters
    ----------
    origin : tuple of float
        (lat, long)
    destination : tuple of float
        (lat, long)

    Returns
    -------
    distance_in_km : float

    Examples
    --------
    >>> origin = (48.1372, 11.5756)  # Munich
    >>> destination = (52.5186, 13.4083)  # Berlin
    >>> round(distance(origin, destination), 1)
    504.2
    """
    lat1, lon1 = origin
    lat2, lon2 = destination
    radius = 6371  # km

    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
         math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
         math.sin(dlon / 2) * math.sin(dlon / 2))
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = radius * c

    return d


if __name__ == '__main__':
    import doctest
    doctest.testmod()

The other alternative package is [haversine][1]

from haversine import haversine, Unit

lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)

haversine(lyon, paris)
>> 392.2172595594006  # in kilometers

haversine(lyon, paris, unit=Unit.MILES)
>> 243.71201856934454  # in miles

# you can also use the string abbreviation for units:
haversine(lyon, paris, unit='mi')
>> 243.71201856934454  # in miles

haversine(lyon, paris, unit=Unit.NAUTICAL_MILES)
>> 211.78037755311516  # in nautical miles

They claim to have performance optimization for distances between all points in two vectors

from haversine import haversine_vector, Unit

lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
new_york = (40.7033962, -74.2351462)

haversine_vector([lyon, lyon], [paris, new_york], Unit.KILOMETERS)

>> array([ 392.21725956, 6163.43638211])

List directory tree structure in python?

On top of dhobbs answer above (https://stackoverflow.com/a/9728478/624597), here is an extra functionality of storing results to a file (I personally use it to copy and paste to FreeMind to have a nice overview of the structure, therefore I used tabs instead of spaces for indentation):

import os

def list_files(startpath):

    with open("folder_structure.txt", "w") as f_output:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = '\t' * 1 * (level)
            output_string = '{}{}/'.format(indent, os.path.basename(root))
            print(output_string)
            f_output.write(output_string + '\n')
            subindent = '\t' * 1 * (level + 1)
            for f in files:
                output_string = '{}{}'.format(subindent, f)
                print(output_string)
                f_output.write(output_string + '\n')

list_files(".")

Change Volley timeout duration

I ended up adding a method setCurrentTimeout(int timeout) to the RetryPolicy and it's implementation in DefaultRetryPolicy.

Then I added a setCurrentTimeout(int timeout) in the Request class and called it .

This seems to do the job.

Sorry for my laziness by the way and hooray for open source.

Python: Find index of minimum item in list of floats

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

Finding duplicate values in MySQL

Try using this query:

SELECT name, COUNT(*) value_count FROM company_master GROUP BY name HAVING value_count > 1;

SQL: Two select statements in one query

The UNION statement is your friend:

SELECT   a.playername, a.games, a.goals
FROM     tblMadrid as a
WHERE    a.playername = "ronaldo"
UNION
SELECT   b.playername, b.games, b.goals
FROM     tblBarcelona as b
WHERE    b.playername = "messi"
ORDER BY goals;

CKEditor automatically strips classes from div

Edit: this answer is for those who use ckeditor module in drupal.

I found a solution which doesn't require modifying ckeditor js file.

this answer is copied from here. all credits should goes to original author.

Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).

Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add config.allowedContent = true;.

enter image description here

Don't forget to flush the cache under "Performance tab."

Xcode 4: create IPA file instead of .xcarchive

Creating an IPA is done along the same way as creating an .xcarchive: Product -> Archive. After the Archive operation completes, go to the Organizer, select your archive, select Share and in the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution (which should match your ad hoc/app store provisioning profile for the project).

Chances are the "iOS App Store Package (.ipa)" option may be disabled. This happens when your build produces more than a single target: say, an app and a library. All of them end up in the build products folder and Xcode gets naïvely confused about how to package them both into an .ipa file, so it merely disables the option.

A way to solve this is as follows: go through build settings for each of the targets, except the application target, and set Skip Install flag to YES. Then do the Product -> Archive tango once again and go to the Organizer to select your new archive. Now, when clicking on the Share button, the .ipa option should be enabled.

I hope this helps.

How to get the selected radio button value using js

function getCheckedValue(radioObj, name) {

    for (j = 0; j < radioObj.rows.length; ++j) {
        for (k = 0; k < radioObj.cells.length; ++k) {
            var radioChoice = document.getElementById(name + "_" + k);
            if (radioChoice.checked) {
                return radioChoice.value;
            }
        }
    }
    return "";
}

Get current date in milliseconds

@JavaZava your solution is good, but if you want to have a 13 digit long value to be consistent with the time stamp formatting in Java or JavaScript (and other languages) use this method:

NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
long digits = (long)time; // this is the first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
long timestamp = (digits * 1000) + decimalDigits;

or (if you need a string):

NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Convert string to int array using LINQ

    public static int[] ConvertArray(string[] arrayToConvert)
    {
        int[] resultingArray = new int[arrayToConvert.Length];

        int itemValue;

        resultingArray = Array.ConvertAll<string, int>
            (
                arrayToConvert, 
                delegate(string intParameter) 
                {
                    int.TryParse(intParameter, out itemValue);
                    return itemValue;
                }
            );

        return resultingArray;
    }

Reference:

http://codepolice.net/convert-string-array-to-int-array-and-vice-versa-in-c/

Reading RFID with Android phones

A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.

It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.

Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.

They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.

How do I run Selenium in Xvfb?

If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY environment variable, and stop xvfb after all.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Ternary operator example.If the value of isFemale boolean variable is YES, print "GENDER IS FEMALE" otherwise "GENDER IS MALE"

? means = execute the codes before the : if the condition is true. 
: means = execute the codes after the : if the condition is false.

Objective-C

BOOL isFemale = YES;
NSString *valueToPrint = (isFemale == YES) ? @"GENDER IS FEMALE" : @"GENDER IS MALE";
NSLog(valueToPrint); //Result will be "GENDER IS FEMALE" because the value of isFemale was set to YES.

For Swift

let isFemale = false
let valueToPrint:String = (isFemale == true) ? "GENDER IS FEMALE" : "GENDER IS MALE"
print(valueToPrint) //Result will be  "GENDER IS MALE" because the isFemale value was set to false.

Does :before not work on img elements?

I tried and found a simpler method to do so. Here is the HTML:

    <img id="message_icon" src="messages2.png">
    <p id="empty_para"></p>

What I did was place an empty <p> tag after my image tag. Now I will use p::before to show the image and position it according to my needs. Here is the CSS:

#empty_para
{
    display:inline;
    font-size:40;
    background:orange;
    border:2px solid red;
    position:relative;
    top:-400px;
    left:100px;
}
#empty_para::before
{
    content: url('messages.png');
}

Try it.

How can I update window.location.hash without jumping the document?

I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:

if (history.pushState) {
    // IE10, Firefox, Chrome, etc.
    window.history.pushState(null, null, '#' + id);
} else {
    // IE9, IE8, etc
    window.location.hash = '#!' + id;
}

As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:

id = window.location.hash.replace(/^#!?/, '');

Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.

How to stop a vb script running in windows

Running scripts can be terminated from the Task Manager.

However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.

Self destruct script:

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True 
WshShell.Run "taskkill /f /im wscript.exe", , True  

Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.

type your shortcut key and all scripts end. Cheers

Bundler: Command not found

I did this (Ubuntu latest as of March 2013 [ I think :) ]):

sudo gem install bundler

Credit goes to Ray Baxter.

If you need gem, I installed Ruby this way (though this is chronically taxing):

mkdir /tmp/ruby && cd /tmp/ruby
wget http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p327.tar.gz
tar xfvz ruby-1.9.3-p327.tar.gz
cd ruby-1.9.3-p327
./configure
make
sudo make install

How to prevent form from being submitted?

To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:

<form onsubmit="return false;"></form>

Then wire up events using the onload or DOM ready if you're using a library.

_x000D_
_x000D_
$(function() {_x000D_
    var $form = $('#my-form');_x000D_
    $form.removeAttr('onsubmit');_x000D_
    $form.submit(function(ev) {_x000D_
        // quick validation example..._x000D_
        $form.children('input[type="text"]').each(function(){_x000D_
            if($(this).val().length == 0) {_x000D_
                alert('You are missing a field');_x000D_
                ev.preventDefault();_x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});
_x000D_
label {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
#my-form > input[type="text"] {_x000D_
    background: cyan;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">_x000D_
    <label>Your first name</label>_x000D_
    <input type="text" name="first-name"/>_x000D_
    <label>Your last name</label>_x000D_
    <input type="text" name="last-name" /> <br />_x000D_
    <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.

How to view method information in Android Studio?

Yes, you can. Go to File -> Settings -> Editor -> Show quick documentation on mouse move

Or, in Mac OS X, go to Android Studio - > Preferences -> Editor - > General > Show quick documentation on mouse move.

How to create the branch from specific commit in different branch

You can do this locally as everyone mentioned using

git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in github itself, follow the steps:

1- In the repository, click on the Commits.

2- on the commit you want to branch from, click on <> to browse the repository at this point in the history.

commits history

3- Click on the tree: xxxxxx in the upper left. Just type in a new branch name there click Create branch xxx as shown below.

create new branch

Now you can fetch the changes from that branch locally and continue from there.

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

How to detect when cancel is clicked on file input?

This is hacky at best, but here is a working example of my solution to detect whether or not a user has uploaded a file, and only allowing them to proceed if they have uploaded a file.

Basically hide the Continue, Save, Proceed or whatever your button is. Then in the JavaScript you grab the file name. If the file name does not have a value, then do not show the Continue button. If it does have a value, then show the button. This also works if they at first upload a file and then they try to upload a different file and click cancel.

Here is the code.

HTML:

<div class="container">
<div class="row">
    <input class="file-input" type="file" accept="image/*" name="fileUpload" id="fileUpload" capture="camera">
    <label for="fileUpload" id="file-upload-btn">Capture or Upload Photo</label>
</div>
<div class="row padding-top-two-em">
    <input class="btn btn-success hidden" id="accept-btn" type="submit" value="Accept & Continue"/>
    <button class="btn btn-danger">Back</button>
</div></div>

JavaScript:

$('#fileUpload').change(function () {
    var fileName = $('#fileUpload').val();
    if (fileName != "") {
        $('#file-upload-btn').html(fileName);
        $('#accept-btn').removeClass('hidden').addClass('show');
    } else {
        $('#file-upload-btn').html("Upload File");
        $('#accept-btn').addClass('hidden');
    }
});

CSS:

.file-input {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1; 
}

.file-input + label {
    font-size: 1.25em;
    font-weight: normal;
    color: white;
    background-color: blue;
    display: inline-block;
    padding: 5px;
}

.file-input:focus + label,
.file-input + label:hover {
    background-color: red;
}

.file-input + label {
    cursor: pointer;
}

.file-input + label * {
    pointer-events: none;
}

For the CSS a lot of this is to make the website and button accessible for everyone. Style your button to whatever you like.

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

MongoDB what are the default user and password?

By default mongodb has no enabled access control, so there is no default user or password.

To enable access control, use either the command line option --auth or security.authorization configuration file setting.

You can use the following procedure or refer to Enabling Auth in the MongoDB docs.

Procedure

  1. Start MongoDB without access control.

    mongod --port 27017 --dbpath /data/db1
    
  2. Connect to the instance.

    mongo --port 27017
    
  3. Create the user administrator.

    use admin
    db.createUser(
      {
        user: "myUserAdmin",
        pwd: "abc123",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      }
    )
    
  4. Re-start the MongoDB instance with access control.

    mongod --auth --port 27017 --dbpath /data/db1
    
  5. Authenticate as the user administrator.

    mongo --port 27017 -u "myUserAdmin" -p "abc123" \
      --authenticationDatabase "admin"
    

Getting ssh to execute a command in the background on target machine

You can do this without nohup:

ssh user@host 'myprogram >out.log 2>err.log &'

Is there any use for unique_ptr with array?

I faced a case where I had to use std::unique_ptr<bool[]>, which was in the HDF5 library (A library for efficient binary data storage, used a lot in science). Some compilers (Visual Studio 2015 in my case) provide compression of std::vector<bool> (by using 8 bools in every byte), which is a catastrophe for something like HDF5, which doesn't care about that compression. With std::vector<bool>, HDF5 was eventually reading garbage because of that compression.

Guess who was there for the rescue, in a case where std::vector didn't work, and I needed to allocate a dynamic array cleanly? :-)

How do you clear the console screen in C?

For portability, try this:

#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif

Then simply call clrscr(). On Windows, it will use conio.h's clrscr(), and on Linux, it will use ANSI escape codes.

If you really want to do it "properly", you can eliminate the middlemen (conio, printf, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void ClearScreen()
{
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
}

#else // !_WIN32
#include <unistd.h>
#include <term.h>

void ClearScreen()
{
  if (!cur_term)
  {
     int result;
     setupterm( NULL, STDOUT_FILENO, &result );
     if (result <= 0) return;
  }

   putp( tigetstr( "clear" ) );
}
#endif

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

How to specify more spaces for the delimiter using cut?

One way around this is to go:

$ps axu | grep jboss | sed 's/\s\+/ /g' | cut -d' ' -f3

to replace multiple consecutive spaces with a single one.

How to get the absolute path to the public_html folder?

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/

C char* to int conversion

Use atoi() from <stdlib.h>

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

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

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

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

In Addition to Ben's Answer, You can try Below Queries as per your need

USE {database-name};  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 1 MB.  
DBCC SHRINKFILE ({database-file-name}, 1);  
GO  
-- Reset the database recovery model.  
ALTER DATABASE {database-name}
SET RECOVERY FULL;  
GO 

Update Credit @cema-sp

To find database file names use below query

select * from sys.database_files;

How do I increase modal width in Angular UI Bootstrap?

I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.

CSS

@media(min-width: 1400px){
    .my-modal > .modal-lg {
        width: 1308px;
    }
}

JS is the same:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal'
});

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

IntelliJ Organize Imports

In addition to Optimize Imports and Auto Import, which were pointed out by @dave-newton and @ryan-stewart in earlier answers, go to:

  • IDEA <= 13: File menu > Settings > Code Style > Java > Imports
  • IDEA >= 14: File menu > Settings > Editor > Code Style > Java > Imports (thanks to @mathias-bader for the hint!) Settings dialog

There you can fine tune the grouping and order or imports, "Class count to use import with '*'", etc.

Note:
since IDEA 13 you can configure the project default settings from the IDEA "start page": Configure > Project defaults > Settings > .... Then every new project will have those default settings: enter image description here

How to select first parent DIV using jQuery?

This gets parent if it is a div. Then it gets class.

var div = $(this).parent("div");
var _class = div.attr("class");

how to change directory using Windows command line

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

Hide Spinner in Input Number - Firefox 29

/* for chrome */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;}             


/* for mozilla */  
   input[type=number] {-moz-appearance: textfield;}

How do I add a newline to a TextView in Android?

I think this has something to do with your HTM.fromHtml(subTitle) call: a "\n" doesn't mean bupkis to HTML. Try <br/> instead of "\n".

Referring to the null object in Python

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

How can I detect window size with jQuery?

You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:

$(window).resize(function() {
  // This will execute whenever the window is resized
  $(window).height(); // New height
  $(window).width(); // New width
});

You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em units and percentages and min-width and max-width in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Disabling Use command-line client from the settings on IntelliJ Ultimate 14.0.3 works for me.

I checked IDEA's document, IDEA don't need a SVN client software anymore. see below description from https://www.jetbrains.com/idea/help/using-subversion-integration.html

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

Prerequisites

IntelliJ IDEA comes bundled with Subversion plugin. This plugin is turned on by default. If it is not, make sure that the plugin is enabled. IntelliJ IDEA's Subversion integration does not require a standalone Subversion client. All you need is an account in your Subversion repository. Subversion integration is enabled for the current project root or directory.

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

How can I compile a Java program in Eclipse without running it?

You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.

How to set recurring schedule for xlsm file using Windows Task Scheduler

I found a much easier way and I hope it works for you. (using Windows 10 and Excel 2016)

Create a new module and enter the following code: Sub auto_open() 'Macro to be run (doesn't have to be in this module, just in this workbook End Sub

Set up a task through the Task Scheduler and set the "program to be run as" Excel (found mine at C:\Program Files (x86)\Microsoft Office\root\Office16). Then set the "Add arguments (optional): as the file path to the macro-enabled workbook. Remember that both the path to Excel and the path to the workbook should be in double quotes.

*See example from Rich, edited by Community, for an image of the windows scheduler screen.

Remove URL parameters without refreshing page

Running this js for me cleared any params on the current url without refreshing the page.

window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Copy table to a different database on a different SQL Server

Create the database, with Script Database as... CREATE To

Within SSMS on the source server, use the export wizard with the destination server database as the destination.

  • Source instance > YourDatabase > Tasks > Export data
  • Data Soure = SQL Server Native Client
    • Validate/enter Server & Database
  • Destination = SQL Server Native Client
    • Validate/enter Server & Database
  • Follow through wizard

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

S3 Static Website Hosting Route All Paths to Index.html

It's tangential, but here's a tip for those using Rackt's React Router library with (HTML5) browser history who want to host on S3.

Suppose a user visits /foo/bear at your S3-hosted static web site. Given David's earlier suggestion, redirect rules will send them to /#/foo/bear. If your application's built using browser history, this won't do much good. However your application is loaded at this point and it can now manipulate history.

Including Rackt history in our project (see also Using Custom Histories from the React Router project), you can add a listener that's aware of hash history paths and replace the path as appropriate, as illustrated in this example:

import ReactDOM from 'react-dom';

/* Application-specific details. */
const route = {};

import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const history = useRouterHistory(createHistory)();

history.listen(function (location) {
  const path = (/#(\/.*)$/.exec(location.hash) || [])[1];
  if (path) history.replace(path);
});

ReactDOM.render(
  <Router history={history} routes={route}/>,
  document.body.appendChild(document.createElement('div'))
);

To recap:

  1. David's S3 redirect rule will direct /foo/bear to /#/foo/bear.
  2. Your application will load.
  3. The history listener will detect the #/foo/bear history notation.
  4. And replace history with the correct path.

Link tags will work as expected, as will all other browser history functions. The only downside I've noticed is the interstitial redirect that occurs on initial request.

This was inspired by a solution for AngularJS, and I suspect could be easily adapted to any application.

How to get the value from the GET parameters?

I made a function that does this:

var getUrlParams = function (url) {
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(function (pair) {
    pair = (pair + '=').split('=').map(decodeURIComponent);
    if (pair[0].length) {
      params[pair[0]] = pair[1];
    }
  });
  return params;
};

Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):

const getUrlParams = url => `${url}?`.split('?')[1]
  .split('&').reduce((params, pair) =>
    ((key, val) => key ? {...params, [key]: val} : params)
    (...`${pair}=`.split('=').map(decodeURIComponent)), {});

Some tests:

console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}

Update 3/26/2018, here is a Typescript implementation:

const getUrlParams = (search: string) => `${search}?`
  .split('?')[1]
  .split('&')
  .reduce(
    (params: object, pair: string) => {
      const [key, value] = `${pair}=`
        .split('=')
        .map(decodeURIComponent)

      return key.length > 0 ? { ...params, [key]: value } : params
    },
    {}
  )

Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.

interface IParams { [key: string]: string }

const paramReducer = (params: IParams, pair: string): IParams => {
  const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)

  return key.length > 0 ? { ...params, [key]: value } : params
}

const getUrlParams = (search: string): IParams =>
  `${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})

What is the difference between Digest and Basic Authentication?

Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.

Digest Access Authentication uses the hashing methodologies to generate the cryptographic result

How do I pass a command line argument while starting up GDB in Linux?

Try

gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

C# "as" cast vs classic cast

With the "classic" method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

Note:

The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

Split value from one field to two

I had a column where the first and last name were both were in one column. The first and last name were separated by a comma. The code below worked. There is NO error checking/correction. Just a dumb split. Used phpMyAdmin to execute the SQL statement.

UPDATE tblAuthorList SET AuthorFirst = SUBSTRING_INDEX(AuthorLast,',',-1) , AuthorLast = SUBSTRING_INDEX(AuthorLast,',',1);

13.2.10 UPDATE Syntax

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

The difference between "require(x)" and "import x"

Let me give an example for Including express module with require & import

-require

var express = require('express');

-import

import * as  express from 'express';

So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,

var app = express(); 

So we use 'require' with 'CommonJS' and 'import' with 'ES6'.

For more info on 'require' & 'import', read through below links.

require - Requiring modules in Node.js: Everything you need to know

import - An Update on ES6 Modules in Node.js

How to do a HTTP HEAD request from the windows command line?

1) See the headers that come back from a GET request

wget --server-response -O /dev/null http://....

1a) Save the headers that come back from a GET request

wget --server-response -o headers -O /dev/null http://....

2) See the headers that come back from GET HEAD request

wget --server-response --spider http://....

2a) Save the headers that come back from a GET HEAD request

wget --server-response --spider -o headers http://....
  • David

Shell Script — Get all files modified after <date>

You can get a list of files last modified later than x days ago with:

find . -mtime -x

Then you just have to tar and zip files in the resulting list, e.g.:

tar czvf mytarfile.tgz `find . -mtime -30`

for all files modified during last month.

Git: force user and password prompt

With git config -l, I now see I have a credential.helper=osxkeychain option

That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")

You can disable that option entirely, or only for a single repo.

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

I get conflicting provisioning settings error when I try to archive to submit an iOS app

This worked perfectly for me.

Step 1:

Select the Project Target-- > Build Settings. Search PROVISIONING_PROFILE and delete whatever nonsense is there.

Step 2:

Uncheck "Automatically manage signing", then check it again and reselect the Team. Xcode then fix whatever was causing the issue on its own.

enter image description here

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

AngularJs: Reload page

You can use the reload method of the $route service. Inject $route in your controller and then create a method reloadRoute on your $scope.

$scope.reloadRoute = function() {
   $route.reload();
}

Then you can use it on the link like this:

<a ng-click="reloadRoute()" class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

This method will cause the current route to reload. If you however want to perform a full refresh, you could inject $window and use that:

$scope.reloadRoute = function() {
   $window.location.reload();
}


Later edit (ui-router):

As mentioned by JamesEddyEdwards and Dunc in their answers, if you are using angular-ui/ui-router you can use the following method to reload the current state / route. Just inject $state instead of $route and then you have:

$scope.reloadRoute = function() {
    $state.reload();
};

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

Pass variables from servlet to jsp

Use

request.setAttribute("attributeName");

and then

getServletContext().getRequestDispatcher("/file.jsp").forward();

Then it will be accessible in the JSP.

As a side note - in your jsp avoid using java code. Use JSTL.

How do I share variables between different .c files?

  1. Try to avoid globals. If you must use a global, see the other answers.
  2. Pass it as an argument to a function.

How to convert minutes to hours/minutes and add various time values together using jQuery?

As the above answer of ConnorLuddy can be slightly improved, there are a minor change to formula to convert minutes to hours:mins format

const convertMinsToHrsMins = (mins) => {
  let h = Math.floor(mins / 60);
  let m = Math.round(mins % 60);
  h = (h < 10) ? ('0' + h) : (h);
  m = (m < 10) ? ('0' + m) : (m);
  return `${h}:${m}`;
}

My theory is that we can not predict that `mins` value will always be an integer.
The added `Math.round` to function will correct the output.
For example: when the minutes=125.3245, the output will be 02:05 with this fix, and 02:05.3245000000000005 without the fix.

Hope that someone need this!

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

How can I convert a DateTime to an int?

Do you want an 'int' that looks like 20110425171213? In which case you'd be better off ToString with the appropriate format (something like 'yyyyMMddHHmmss') and then casting the string to an integer (or a long, unsigned int as it will be way more than 32 bits).

If you want an actual numeric value (the number of seconds since the year 0) then that's a very different calculation, e.g.

result = second
result += minute * 60
result += hour * 60 * 60
result += day * 60 * 60 * 24 

etc.

But you'd be better off using Ticks.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

We faced this issue, when the windowsuser detaching the database and windowsuser attaching the database are different. When the windowsuser detaching the database, tried to attach it, it worked fine without issues.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

I had trouble with the web installer not "finding the product"

The stand alone installer is located here:

https://www.microsoft.com/en-us/download/details.aspx?id=41532

The release/installation notes can be found at

http://www.asp.net/visual-studio/overview/2012/aspnet-and-web-tools-20131-for-visual-studio-2012

Dependency:

  • .NET 4.5
  • You need to select this version of the framework when creating a new project in order to view the MVC 5 project templates.

Included:

  • MVC5
  • Entity Framework 6
  • Web API 2
  • Bootstrap
  • Razor
  • Nuget 2.7

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

/** and /* in Java Comments

Java supports two types of comments:

  • /* multiline comment */ : The compiler ignores everything from /* to */. The comment can span over multiple lines.

  • // single line : The compiler ignores everything from // to the end of the line.

Some tool such as javadoc use a special multiline comment for their purpose. For example /** doc comment */ is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.

Ruby Hash to array of values

Also, a bit simpler....

>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]

Ruby doc here

How to install mongoDB on windows?

Installing MongoDB on Windows is bit tricky compared to other Executable files.. Got a good reference after long search i got Installing MongoDB in Windows

After Installing open command prompt and type "mongod", then keep the window minimized and open another command prompt window and type "mongo" and you will find the success message of connecting to the test database

Laravel redirect back to original destination after login

       // Also place this code into base controller in contract function,            because ever controller extends base  controller
 if(Auth::id) {
  //here redirect your code or function
 }
if (Auth::guest()) {
       return Redirect::guest('login');
}

Postgresql: password authentication failed for user "postgres"

In my case, its Password was longer than 100 characters. Setting it to a smaller character password worked.

Actually I am wondering is there a reference somewhere to that.

Rank function in MySQL

Here is a generic solution that assigns dense rank over partition to rows. It uses user variables:

CREATE TABLE person (
    id INT NOT NULL PRIMARY KEY,
    firstname VARCHAR(10),
    gender VARCHAR(1),
    age INT
);

INSERT INTO person (id, firstname, gender, age) VALUES
(1,  'Adams',  'M', 33),
(2,  'Matt',   'M', 31),
(3,  'Grace',  'F', 25),
(4,  'Harry',  'M', 20),
(5,  'Scott',  'M', 30),
(6,  'Sarah',  'F', 30),
(7,  'Tony',   'M', 30),
(8,  'Lucy',   'F', 27),
(9,  'Zoe',    'F', 30),
(10, 'Megan',  'F', 26),
(11, 'Emily',  'F', 20),
(12, 'Peter',  'M', 20),
(13, 'John',   'M', 21),
(14, 'Kate',   'F', 35),
(15, 'James',  'M', 32),
(16, 'Cole',   'M', 25),
(17, 'Dennis', 'M', 27),
(18, 'Smith',  'M', 35),
(19, 'Zack',   'M', 35),
(20, 'Jill',   'F', 25);

SELECT person.*, @rank := CASE
    WHEN @partval = gender AND @rankval = age THEN @rank
    WHEN @partval = gender AND (@rankval := age) IS NOT NULL THEN @rank + 1
    WHEN (@partval := gender) IS NOT NULL AND (@rankval := age) IS NOT NULL THEN 1
END AS rnk
FROM person, (SELECT @rank := NULL, @partval := NULL, @rankval := NULL) AS x
ORDER BY gender, age;

Notice that the variable assignments are placed inside the CASE expression. This (in theory) takes care of order of evaluation issue. The IS NOT NULL is added to handle datatype conversion and short circuiting issues.

PS: It can easily be converted to row number over partition by by removing all conditions that check for tie.

| id | firstname | gender | age | rank |
|----|-----------|--------|-----|------|
| 11 | Emily     | F      | 20  | 1    |
| 20 | Jill      | F      | 25  | 2    |
| 3  | Grace     | F      | 25  | 2    |
| 10 | Megan     | F      | 26  | 3    |
| 8  | Lucy      | F      | 27  | 4    |
| 6  | Sarah     | F      | 30  | 5    |
| 9  | Zoe       | F      | 30  | 5    |
| 14 | Kate      | F      | 35  | 6    |
| 4  | Harry     | M      | 20  | 1    |
| 12 | Peter     | M      | 20  | 1    |
| 13 | John      | M      | 21  | 2    |
| 16 | Cole      | M      | 25  | 3    |
| 17 | Dennis    | M      | 27  | 4    |
| 7  | Tony      | M      | 30  | 5    |
| 5  | Scott     | M      | 30  | 5    |
| 2  | Matt      | M      | 31  | 6    |
| 15 | James     | M      | 32  | 7    |
| 1  | Adams     | M      | 33  | 8    |
| 18 | Smith     | M      | 35  | 9    |
| 19 | Zack      | M      | 35  | 9    |

Demo on db<>fiddle

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Simply go to your root folder and run this command:

chmod a+rw .git/FETCH_HEAD

Modelling an elevator using Object-Oriented Analysis and Design

See:

Lu Luo, A UML Documentation for a Elevator System
Distributed Embedded Systems, Fall 2000
Ph.D. Project Report
Carneghie Mellon University

link

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I setup everything correctly in the Storyboard and did a clean build but kept getting the error " must register a nib or a class for the identifier or connect a prototype cell in a storyboard"

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

Corrected the error but i'm still at a loss. I'm not using a 'custom cell', just a view with a tableview embeded. I have declared the viewcontroller as delegate and datasource and made sure the cell identifier matches in file. whats going on here?

Test if object implements interface

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

Getting a link to go to a specific section on another page

I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID attribute. To support older browsers, you'll need to change:

<div id="timeline" name="timeline" ...>

To the old format:

<a name="timeline" />

You'll then be able to navigate to /academics/page.html#timeline and jump right to that section.

Also, check out this similar question.

increment date by one month

I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:

function add_months($months, DateTime $dateObject) 
    {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function endCycle($d1, $months)
    {
        $date = new DateTime($d1);

        // call second function to add the months
        $newDate = $date->add(add_months($months, $date));

        // goes back 1 day from date, remove if you want same day of month
        $newDate->sub(new DateInterval('P1D')); 

        //formats final date to Y-m-d form
        $dateReturned = $newDate->format('Y-m-d'); 

        return $dateReturned;
    }

Example:

$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02

Create an array or List of all dates between two dates

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
    }

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.

Convert ASCII TO UTF-8 Encoding

Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:

public static function ToAscii($string) {
    $strlen = strlen($string);
    $charCode = array();
    for ($i = 0; $i < $strlen; $i++) {
        $charCode[] = ord(substr($string, $i, 1));
    }
    $result = json_encode($charCode);
    return $result;
}

public static function fromAscii($string) {
    $charCode = json_decode($string);
    $result = '';
    foreach ($charCode as $code) {
        $result .= chr($code);
    };
    return $result;
}

Are there inline functions in java?

so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:

    assert false : new com.google.common.base.Function<Void,String>(){
        @Override public String apply(Void input) {
            //your complex code go here
            return "weird message";
        }}.apply(null);

yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

How to show hidden divs on mouseover?

There is a really simple way to do this in a CSS only way.

Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.

_x000D_
_x000D_
#mouse_over {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

pandas dataframe columns scaling with sklearn

df = pd.DataFrame(scale.fit_transform(df.values), columns=df.columns, index=df.index)

This should work without depreciation warnings.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Here are some more tests

True if string is not empty:

[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"

True if string is empty:

[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"

changing textbox border colour using javascript

If the users enter an incorrect value, apply a 1px red color border to the input field:

document.getElementById('fName').style.border ="1px solid red";

If the user enters a correct value, remove the border from the input field:

document.getElementById('fName').style.border ="";

PHP check whether property exists in object or class

Just putting my 2 cents here.

Given the following class:

class Foo
{
  private $data;

  public function __construct(array $data)
  {
    $this->data = $data;
  }

  public function __get($name)
  {
    return $data[$name];
  }

  public function __isset($name)
  {
    return array_key_exists($name, $this->data);
  }
}

the following will happen:

$foo = new Foo(['key' => 'value', 'bar' => null]);

var_dump(property_exists($foo, 'key'));  // false
var_dump(isset($foo->key));  // true
var_dump(property_exists($foo, 'bar'));  // false
var_dump(isset($foo->bar));  // true, although $data['bar'] == null

Hope this will help anyone

How to extract one column of a csv file

You could use awk for this. Change '$2' to the nth column you want.

awk -F "\"*,\"*" '{print $2}' textfile.csv

Display a float with two decimal places in Python

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

How can I discover the "path" of an embedded resource?

I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:

ProjectNamespace.Properties.Resources.file

Use the IDE's resource manager to add resources.

C++: what regex library should I use?

In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.

Converting ArrayList to Array in java

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki"); 
String names[]=list.toArray(new String[0]);

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

Convert unsigned int to signed int C

@Mysticial got it. A short is usually 16-bit and will illustrate the answer:

int main()  
{
    unsigned int x = 65529;
    int y = (int) x;
    printf("%d\n", y);

    unsigned short z = 65529;
    short zz = (short)z;
    printf("%d\n", zz);
}

65529
-7
Press any key to continue . . .


A little more detail. It's all about how signed numbers are stored in memory. Do a search for twos-complement notation for more detail, but here are the basics.

So let's look at 65529 decimal. It can be represented as FFF9h in hexadecimal. We can also represent that in binary as:

11111111 11111001

When we declare short zz = 65529;, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1, so it is treated as a negative number. That's why it prints out -7.

For an unsigned short, we don't care about sign since it's unsigned. So when we print it out using %d, we use all 16 bits, so it's interpreted as 65529.

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

What's the difference between xsd:include and xsd:import?

Use xsd:include to bring in an XSD from the same or no namespace.

Use xsd:import to bring in an XSD from a different namespace.

Regex to match URL end-of-line or "/" character

In Ruby and Bash, you can use $ inside parentheses.

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|$)

(This solution is similar to Pete Boughton's, but preserves the usage of $, which means end of line, rather than using \z, which means end of string.)

How to create websockets server in PHP

I've searched the minimal solution possible to do PHP + WebSockets during hours, until I found this article:

Super simple PHP WebSocket example

It doesn't require any third-party library.

Here is how to do it: create a index.html containing this:

<html>
<body>
    <div id="root"></div>
    <script>
        var host = 'ws://<<<IP_OF_YOUR_SERVER>>>:12345/websockets.php';
        var socket = new WebSocket(host);
        socket.onmessage = function(e) {
            document.getElementById('root').innerHTML = e.data;
        };
    </script>
</body>
</html>

and open it in the browser, just after you have launched php websockets.php in the command-line (yes, it will be an event loop, constantly running PHP script), with this websockets.php file.

changing source on html5 video tag

Just put a div and update the content...

<script>
function setvideo(src) {
    document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style="height: 100px; width: 100px;"><source src="'+src+'" type="video/mp4"></video>';
    document.getElementById('video_ctrl').play();
}
</script>
<button onClick="setvideo('video1.mp4');">Video1</button>
<div id="div_video"> </div>

Set up Python 3 build system with Sublime Text 3

Version for Linux. Create a file ~/.config/sublime-text-3/Packages/User/Python3.sublime-build with the following.

{
 "cmd": ["/usr/bin/python3", "-u", "$file"],
 "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
 "selector": "source.python"
}

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

How to create a Java / Maven project that works in Visual Studio Code?

Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-

  1. Download VS Code and Apache Maven and install both.
  2. Install the Visual Studio extension pack for Java - e.g. by pasting this URL into a web browser: vscode:extension/vscjava.vscode-java-pack and then clicking on the green Install button after it opens in VS Code.
  3. NOTE: See the comment from ADTC for an "Easier GUI version of step 3...(Skip step 4)." If necessary, the Maven quick start archetype could be used to generate a new Maven project in an appropriate local folder: mvn archetype:generate -DgroupId=com.companyname.appname-DartifactId=appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname and src/main/test/com/companyname/appname to begin with and a sample "Hello World!" Java file named appname.java and associated unit test named appnameTest.java).*
  4. Open the Maven project folder in VS Code via File menu -> Open Folder... and select the appname folder.
  5. Open the Command Palette (via the View menu or by right-clicking) and type in and select Tasks: Configure task then select Create tasks.json from template.
  6. Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:

    {
        "label": "compile",
        "type": "shell",
        "command": "mvn -B compile",
        "group": "build"
    },
    
  7. Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target folder at the same level as the src folder with the compiled class files in the target\classes folder.


Addendum: How to run/debug a class

Following a question in the comments, here are some steps for running/debugging:-

  1. Show the Debug view if it is not already shown (via View menu - Debug or CtrlShiftD).
  2. Click on the green arrow in the Debug view and select "Java".
  3. Assuming it hasn't already been created, a message "launch.json is needed to start the debugger. Do you want to create it now?" will appear - select "Yes" and then select "Java" again.
  4. Enter the fully qualified name of the main class (e.g. com.companyname.appname.App) in the value for "mainClass" and save the file.
  5. Click on the green arrow in the Debug view again.

Android Webview - Webpage should fit the device screen

You can use this

    WebView browser = (WebView) findViewById(R.id.webview);
    browser.getSettings().setLoadWithOverviewMode(true);
    browser.getSettings().setUseWideViewPort(true);

this fixes size based on screen size.

How to count string occurrence in string?

Answer for Leandro Batista : just a problem with the regex expression.

_x000D_
_x000D_
 "use strict";_x000D_
 var dataFromDB = "testal";_x000D_
 _x000D_
  $('input[name="tbInput"]').on("change",function(){_x000D_
 var charToTest = $(this).val();_x000D_
 var howManyChars = charToTest.length;_x000D_
 var nrMatches = 0;_x000D_
 if(howManyChars !== 0){_x000D_
  charToTest = charToTest.charAt(0);_x000D_
  var regexp = new RegExp(charToTest,'gi');_x000D_
  var arrMatches = dataFromDB.match(regexp);_x000D_
  nrMatches = arrMatches ? arrMatches.length : 0;_x000D_
 }_x000D_
  $('#result').html(nrMatches.toString());_x000D_
_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="main">_x000D_
What do you wanna count <input type="text" name="tbInput" value=""><br />_x000D_
Number of occurences = <span id="result">0</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I implement a tree in Python?

I've implemented trees using nested dicts. It is quite easy to do, and it has worked for me with pretty large data sets. I've posted a sample below, and you can see more at Google code

  def addBallotToTree(self, tree, ballotIndex, ballot=""):
    """Add one ballot to the tree.

    The root of the tree is a dictionary that has as keys the indicies of all 
    continuing and winning candidates.  For each candidate, the value is also
    a dictionary, and the keys of that dictionary include "n" and "bi".
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.

    If candidate c is a winning candidate, then that portion of the tree is
    expanded to indicate the breakdown of the subsequently ranked candidates.
    In this situation, additional keys are added to the tree[c] dictionary
    corresponding to subsequently ranked candidates.
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
    tree[c][d]["n"] is the number of ballots that rank c first and d second.
    tree[c][d]["bi"] is a list of the corresponding ballot indices.

    Where the second ranked candidates is also a winner, then the tree is 
    expanded to the next level.  

    Losing candidates are ignored and treated as if they do not appear on the 
    ballots.  For example, tree[c][d]["n"] is the total number of ballots
    where candidate c is the first non-losing candidate, c is a winner, and
    d is the next non-losing candidate.  This will include the following
    ballots, where x represents a losing candidate:
    [c d]
    [x c d]
    [c x d]
    [x c x x d]

    During the count, the tree is dynamically updated as candidates change
    their status.  The parameter "tree" to this method may be the root of the
    tree or may be a sub-tree.
    """

    if ballot == "":
      # Add the complete ballot to the tree
      weight, ballot = self.b.getWeightedBallot(ballotIndex)
    else:
      # When ballot is not "", we are adding a truncated ballot to the tree,
      # because a higher-ranked candidate is a winner.
      weight = self.b.getWeight(ballotIndex)

    # Get the top choice among candidates still in the running
    # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
    # we are looking for the top choice over a truncated ballot.
    for c in ballot:
      if c in self.continuing | self.winners:
        break # c is the top choice so stop
    else:
      c = None # no candidates left on this ballot

    if c is None:
      # This will happen if the ballot contains only winning and losing
      # candidates.  The ballot index will not need to be transferred
      # again so it can be thrown away.
      return

    # Create space if necessary.
    if not tree.has_key(c):
      tree[c] = {}
      tree[c]["n"] = 0
      tree[c]["bi"] = []

    tree[c]["n"] += weight

    if c in self.winners:
      # Because candidate is a winner, a portion of the ballot goes to
      # the next candidate.  Pass on a truncated ballot so that the same
      # candidate doesn't get counted twice.
      i = ballot.index(c)
      ballot2 = ballot[i+1:]
      self.addBallotToTree(tree[c], ballotIndex, ballot2)
    else:
      # Candidate is in continuing so we stop here.
      tree[c]["bi"].append(ballotIndex)

How to set a JavaScript breakpoint from code in Chrome?

You can also use debug(function), to break when function is called.

Command Line API Reference: debug

How do I concatenate strings in Swift?

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

The VMware Authorization Service is not running

1.Click Start and then type Run (or Windows button + R)

2.Type services.msc and click OK

3.Find all VMware services.

4.For each, click Start the service, unless the service is showing a status of Started.

  • If "Start the service" is disappear, please do these things before:

    1. Click Start and then type Run (or Windows button + R)
    2. Type msconfig and click OK
    3. In Services tab, find then check all VMware services checkboxes.
    4. Click Apply then OK.

Calling Member Functions within Main C++

On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))

Can't connect to local MySQL server through socket homebrew

just to complete this thread. therefore MAMP (PRO) is used pretty often

the path here is

/Applications/MAMP/tmp/mysql/mysql.sock

How to open a local disk file with JavaScript?

You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.

You'll have to upload the files you want.

CSS Pseudo-classes with inline styles

Rather than needing inline you could use Internal CSS

<a href="http://www.google.com" style="hover:text-decoration:none;">Google</a>

You could have:

<a href="http://www.google.com" id="gLink">Google</a>
<style>
  #gLink:hover {
     text-decoration: none;
  }
</style>

Is it possible to assign numeric value to an enum in Java?

Yes, and then some, example from documentation:

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    // in kilograms
    private final double mass;
    // in meters
    private final double radius;
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational 
    // constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

Using GPU from a docker container?

We just released an experimental GitHub repository which should ease the process of using NVIDIA GPUs inside Docker containers.

Set iframe content height to auto resize dynamically

Simple solution:

<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>

This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

No == operator found while comparing structs in C++

Comparison doesn't work on structs in C or C++. Compare by fields instead.

How to list all Git tags?

git tag

should be enough. See git tag man page


You also have:

git tag -l <pattern>

List tags with names that match the given pattern (or all if no pattern is given).
Typing "git tag" without arguments, also lists all tags.


More recently ("How to sort git tags?", for Git 2.0+)

git tag --sort=<type>

Sort in a specific order.

Supported type is:

  • "refname" (lexicographic order),
  • "version:refname" or "v:refname" (tag names are treated as versions).

Prepend "-" to reverse sort order.


That lists both:

  • annotated tags: full objects stored in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).
  • lightweight tags: simple pointer to an existing commit

Note: the git ready article on tagging disapproves of lightweight tag.

Without arguments, git tag creates a “lightweight” tag that is basically a branch that never moves.
Lightweight tags are still useful though, perhaps for marking a known good (or bad) version, or a bunch of commits you may need to use in the future.
Nevertheless, you probably don’t want to push these kinds of tags.

Normally, you want to at least pass the -a option to create an unsigned tag, or sign the tag with your GPG key via the -s or -u options.


That being said, Charles Bailey points out that a 'git tag -m "..."' actually implies a proper (unsigned annotated) tag (option '-a'), and not a lightweight one. So you are good with your initial command.


This differs from:

git show-ref --tags -d

Which lists tags with their commits (see "Git Tag list, display commit sha1 hashes").
Note the -d in order to dereference the annotated tag object (which have their own commit SHA1) and display the actual tagged commit.

Similarly, git show --name-only <aTag> would list the tag and associated commit.

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

For me, I accidentally included my local database name inside the SQL query, hence the access denied issue came up when I deployed.

I removed the database name from the SQL query and it got fixed.

Python object.__repr__(self) should be an expression?

To see how the repr works within a class, run the following code, first with and then without the repr method.

class Coordinate (object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just accessing an attribute directly
        return self.x
    def getY(self):

        # Getter method for a Coordinate object's y coordinate
        return self.y

    def __repr__(self):  #remove this and the next line and re-run
        return 'Coordinate(' + str(self.getX()) + ',' + str(self.getY()) + ')' 

>>>c = Coordinate(2,-8)
>>>print(c)

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:

  • References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)
  • The MSI package (which, as has already been noted, will need to target either x86 or x64)
  • Any custom .NET Installer Class-based actions in your MSI package

The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:

<Reference Include="Filename, ..., processorArchitecture=x86">
  <HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>

Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:

<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
   <Reference ...>....</Reference>
</ItemGroup>

Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:

<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
  <Reference Include="Filename, ..., processorArchitecture=AMD64">
     <HintPath>C:\path\to\x64\DLL</HintPath>
   </Reference>
</ItemGroup>

After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.

Solving the MSI issue is up next, and unfortunately this will require a non-VS.NET tool: I prefer Caphyon's Advanced Installer for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well.

You can probably achieve the same results using other tools or the Windows Installer XML (WiX) toolset, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.

One thing you may still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.

This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.


Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...


Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):

<ItemGroup Condition="'$(Platform)' == 'x86'">
    <Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
    <Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>

The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.

Get the row(s) which have the max value in groups using groupby

You can sort the dataFrame by count and then remove duplicates. I think it's easier:

df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])

java get file size efficiently

In response to rgrig's benchmark, the time taken to open/close the FileChannel & RandomAccessFile instances also needs to be taken into account, as these classes will open a stream for reading the file.

After modifying the benchmark, I got these results for 1 iterations on a 85MB file:

file totalTime: 48000 (48 us)
raf totalTime: 261000 (261 us)
channel totalTime: 7020000 (7 ms)

For 10000 iterations on same file:

file totalTime: 80074000 (80 ms)
raf totalTime: 295417000 (295 ms)
channel totalTime: 368239000 (368 ms)

If all you need is the file size, file.length() is the fastest way to do it. If you plan to use the file for other purposes like reading/writing, then RAF seems to be a better bet. Just don't forget to close the file connection :-)

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class FileSizeBench
{    
    public static void main(String[] args) throws Exception
    {
        int iterations = 1;
        String fileEntry = args[0];

        Map<String, Long> times = new HashMap<String, Long>();
        times.put("file", 0L);
        times.put("channel", 0L);
        times.put("raf", 0L);

        long fileSize;
        long start;
        long end;
        File f1;
        FileChannel channel;
        RandomAccessFile raf;

        for (int i = 0; i < iterations; i++)
        {
            // file.length()
            start = System.nanoTime();
            f1 = new File(fileEntry);
            fileSize = f1.length();
            end = System.nanoTime();
            times.put("file", times.get("file") + end - start);

            // channel.size()
            start = System.nanoTime();
            channel = new FileInputStream(fileEntry).getChannel();
            fileSize = channel.size();
            channel.close();
            end = System.nanoTime();
            times.put("channel", times.get("channel") + end - start);

            // raf.length()
            start = System.nanoTime();
            raf = new RandomAccessFile(fileEntry, "r");
            fileSize = raf.length();
            raf.close();
            end = System.nanoTime();
            times.put("raf", times.get("raf") + end - start);
        }

        for (Map.Entry<String, Long> entry : times.entrySet()) {
            System.out.println(entry.getKey() + " totalTime: " + entry.getValue() + " (" + getTime(entry.getValue()) + ")");
        }
    }

    public static String getTime(Long timeTaken)
    {
        if (timeTaken < 1000) {
            return timeTaken + " ns";
        } else if (timeTaken < (1000*1000)) {
            return timeTaken/1000 + " us"; 
        } else {
            return timeTaken/(1000*1000) + " ms";
        } 
    }
}

Can jQuery check whether input content has changed?

I had to use this kind of code for a scanner that pasted stuff into the field

$(document).ready(function() {
  var tId,oldVal;
  $("#fieldId").focus(function() {
     oldVal = $("#fieldId").val();
     tId=setInterval(function() { 
      var newVal = $("#fieldId").val(); 
      if (oldVal!=newVal) oldVal=newVal;
      someaction() },100);
  });
  $("#fieldId").blur(function(){ clearInterval(tId)});
});

Not tested...

Export a list into a CSV or TXT file in R

You can simply wrap your list as a data.frame (data.frame is in fact a special kind of list). Here is an example:

mylist = list() 
mylist[["a"]] = 1:10 
mylist[["b"]] = letters[1:10]
write.table(as.data.frame(mylist),file="mylist.csv", quote=F,sep=",",row.names=F)

or alternatively you can use write.csv (a wrapper around write.table). For the conversion of the list , you can use both as.data.frame(mylist) and data.frame(mylist).

To help in making a reproducible example, you can use functions like dput on your data.

How to check if any flags of a flag combination are set?

You could just check if the value is not zero.

if ((Int32)(letter & Letters.AB) != 0) { }

But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

[Flags]
enum Letters
{
    None = 0,
    A    = 1,
    B    = 2,
    C    = 4,
    AB   =  A | B,
    All  = AB | C
}

if (letter != Letters.None) { }

UPDATE

Missread the question - fixed the first suggestion and just ignore the second suggestion.

How to see docker image contents

We can try a simpler one as follows:

docker image inspect image_id

This worked in Docker version:

DockerVersion": "18.05.0-ce"

How can I make SQL case sensitive string comparison on MySQL?

The good news is that if you need to make a case-sensitive query, it is very easy to do:

SELECT *  FROM `table` WHERE BINARY `column` = 'value'

Dialog to pick image from gallery or from camera

I think that's up to you to show that dialog for choosing. For Gallery you'll use that code, and for Camera try this.

How to convert an OrderedDict into a regular dict in python3

If somehow you want a simple, yet different solution, you can use the {**dict} syntax:

from collections import OrderedDict

ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

POST: sending a post request in a url itself

You can post data to a url with JavaScript & Jquery something like that:

$.post("www.abc.com/details", {
    json_string: JSON.stringify({name:"John", phone number:"+410000000"})
});

if A vs if A is not None:

if A: will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Android Google Maps API V2 Zoom to Current Location

Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin

locationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let {
                val position = CameraPosition.Builder()
                        .target(LatLng(it.latitude, it.longitude))
                        .zoom(15.0f)
                        .build()
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
            }
        }

Error: Unexpected value 'undefined' imported by the module

Make sure you should not import a module/component like this:

import { YOUR_COMPONENT } from './';

But it should be

import { YOUR_COMPONENT } from './YOUR_COMPONENT.ts';

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

warning: LF will be replaced by CRLF.

Depending on the editor you are using, a text file with LF wouldn't necessary be saved with CRLF: recent editors can preserve eol style. But that git config setting insists on changing those...

Simply make sure that (as I recommend here):

git config --global core.autocrlf false

That way, you avoid any automatic transformation, and can still specify them through a .gitattributes file and core.eol directives.


windows git "LF will be replaced by CRLF"
Is this warning tail backward?

No: you are on Windows, and the git config help page does mention

Use this setting if you want to have CRLF line endings in your working directory even though the repository does not have normalized line endings.

As described in "git replacing LF with CRLF", it should only occur on checkout (not commit), with core.autocrlf=true.

       repo
    /        \ 
crlf->lf    lf->crlf 
 /              \    

As mentioned in XiaoPeng's answer, that warning is the same as:

warning: (If you check it out/or clone to another folder with your current core.autocrlf configuration,) LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.

As mentioned in git-for-windows/git issue 1242:

I still feel this message is confusing, the message could be extended to include a better explanation of the issue, for example: "LF will be replaced by CRLF in file.json after removing the file and checking it out again".

Note: Git 2.19 (Sept 2018), when using core.autocrlf, the bogus "LF will be replaced by CRLF" warning is now suppressed.


As quaylar rightly comments, if there is a conversion on commit, it is to LF only.

That specific warning "LF will be replaced by CRLF" comes from convert.c#check_safe_crlf():

if (checksafe == SAFE_CRLF_WARN)
  warning("LF will be replaced by CRLF in %s.
           The file will have its original line endings 
           in your working directory.", path);
else /* i.e. SAFE_CRLF_FAIL */
  die("LF would be replaced by CRLF in %s", path);

It is called by convert.c#crlf_to_git(), itself called by convert.c#convert_to_git(), itself called by convert.c#renormalize_buffer().

And that last renormalize_buffer() is only called by merge-recursive.c#blob_unchanged().

So I suspect this conversion happens on a git commit only if said commit is part of a merge process.


Note: with Git 2.17 (Q2 2018), a code cleanup adds some explanation.

See commit 8462ff4 (13 Jan 2018) by Torsten Bögershausen (tboegi).
(Merged by Junio C Hamano -- gitster -- in commit 9bc89b1, 13 Feb 2018)

convert_to_git(): safe_crlf/checksafe becomes int conv_flags

When calling convert_to_git(), the checksafe parameter defined what should happen if the EOL conversion (CRLF --> LF --> CRLF) does not roundtrip cleanly.
In addition, it also defined if line endings should be renormalized (CRLF --> LF) or kept as they are.

checksafe was an safe_crlf enum with these values:

SAFE_CRLF_FALSE:       do nothing in case of EOL roundtrip errors
SAFE_CRLF_FAIL:        die in case of EOL roundtrip errors
SAFE_CRLF_WARN:        print a warning in case of EOL roundtrip errors
SAFE_CRLF_RENORMALIZE: change CRLF to LF
SAFE_CRLF_KEEP_CRLF:   keep all line endings as they are

Note that a regression introduced in 8462ff4 ("convert_to_git(): safe_crlf/checksafe becomes int conv_flags", 2018-01-13, Git 2.17.0) back in Git 2.17 cycle caused autocrlf rewrites to produce a warning message despite setting safecrlf=false.

See commit 6cb0912 (04 Jun 2018) by Anthony Sottile (asottile).
(Merged by Junio C Hamano -- gitster -- in commit 8063ff9, 28 Jun 2018)

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

How do I use the CONCAT function in SQL Server 2008 R2?

Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.

Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.

Selecting multiple classes with jQuery

This should work:

$('.myClass, .myOtherClass').removeClass('theclass');

You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.

It's the same as you would do in CSS.

Is there a way to use PhantomJS in Python?

Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium.

I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't provided these features earlier, but as of v1.9, it very much does so.

  1. Install PhantomJS (http://phantomjs.org/download.html) (If you are on Linux, following instructions will help https://stackoverflow.com/a/14267295/382630)
  2. Install Selenium using pip.

Now you can use like this

import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing

driver.quit()

Disabling and enabling a html input button

$(".btncancel").button({ disabled: true });

Here 'btncancel' is the class name of the button.

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

css width: calc(100% -100px); alternative using jquery

I think this may be another way

    var width=  $('#elm').width();

    $('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

how to rotate a bitmap 90 degrees

I would simplify comm1x's Kotlin extension function even more:

fun Bitmap.rotate(degrees: Float) =
    Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)

tsconfig.json: Build:No inputs were found in config file

If you don't want TypeScript compilation, disable it in your .csproj file, according to this post.

Just add the following line to your .csproj file:

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

How to get All input of POST in Laravel

You should use the facade rather than Illuminate\Http\Request. Import it at the top:

use Request;

And make sure it doesn't conflict with the other class.

Edit: This answer was written a few years ago. I now favour the approach suggested by shuvrow below.

Calculating distance between two points, using latitude longitude?

The Java code given by Dommer above gives slightly incorrect results but the small errors add up if you are processing say a GPS track. Here is an implementation of the Haversine method in Java which also takes into account height differences between two points.

/**
 * Calculate distance between two points in latitude and longitude taking
 * into account height difference. If you are not interested in height
 * difference pass 0.0. Uses Haversine method as its base.
 * 
 * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
 * el2 End altitude in meters
 * @returns Distance in Meters
 */
public static double distance(double lat1, double lat2, double lon1,
        double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}

Phone Number Validation MVC

You don't have a validator on the page. Add something like this to show the validation message.

@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

How to update SQLAlchemy row entry?

I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model

def update_state(chat_id, state):
    try:
        value = Users.query.filter(Users.chat_id == str(chat_id)).first()
        value.state = str(state)
        db.session.flush()
        db.session.commit()
        #db.session.close()
    except:
        print('Error in def update_state')

Why use db.session.flush()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?

How to make a <div> appear in front of regular text/tables

It moves table down because there is no much space, try to decrease/increase width of certain elements so that it finds some space and does not push the table down. Also you may want to use absolute positioning to position the div at exactly the place you want, for example:

<style>
 #div_id
 {
   position:absolute;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

If you want to appear it over something, you also need to give it z-index, so it might look like this:

<style>
 #div_id
 {
   position:absolute;
   z-index:999;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

Python: Get relative path from comparing two absolute paths

Edit : See jme's answer for the best way with Python3.

Using pathlib, you have the following solution :

Let's say we want to check if son is a descendant of parent, and both are Path objects. We can get a list of the parts in the path with list(parent.parts). Then, we just check that the begining of the son is equal to the list of segments of the parent.

>>> lparent = list(parent.parts)
>>> lson = list(son.parts)
>>> if lson[:len(lparent)] == lparent:
>>> ... #parent is a parent of son :)

If you want to get the remaining part, you can just do

>>> ''.join(lson[len(lparent):])

It's a string, but you can of course use it as a constructor of an other Path object.

Easy way to get a test file into JUnit

You can try doing:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');