Programs & Examples On #Django validation

django-validation refers to form and field validation tools provided by Django out of the box

What's the best way to store Phone number in Django models

Use CharField for phone field in the model and the localflavor app for form validation:

https://docs.djangoproject.com/en/1.7/topics/localflavor/

Origin null is not allowed by Access-Control-Allow-Origin

Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like

Origin null is not allowed by Access-Control-Allow-Origin.

Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;

--allow-file-access-from-files

More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;

C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

Hope this will help!

Pdf.js: rendering a pdf file using a base64 file source instead of url

from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js

/**
 * This is the main entry point for loading a PDF and interacting with it.
 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
 * is used, which means it must follow the same origin rules that any XHR does
 * e.g. No cross domain requests without CORS.
 *
 * @param {string|TypedAray|object} source Can be an url to where a PDF is
 * located, a typed array (Uint8Array) already populated with data or
 * and parameter object with the following possible fields:
 *  - url   - The URL of the PDF.
 *  - data  - A typed array with PDF data.
 *  - httpHeaders - Basic authentication headers.
 *  - password - For decrypting password-protected PDFs.
 *
 * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
 */

So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).

But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746

var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

tl;dr

var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)

'JSON' is undefined error in JavaScript in Internet Explorer

<!DOCTYPE html>

Otherwise IE8 is not acting right. Also you should use:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

Removing empty lines in Notepad++

There is a plugin that adds a menu entitled TextFX. This menu, which houses a dizzying array of quick text editing options, gives a person the ability to make quick coding changes. In this menu, you can find selections such as Drop Quotes, Delete Blank Lines as well as Unwrap and Rewrap Text

Do the following:

TextFX > TextFX Edit > Delete Blank Lines
TextFX > TextFX Edit > Delete Surplus Blank Lines

How do you set EditText to only accept numeric values in Android?

In code, you could do

ed_ins.setInputType(InputType.TYPE_CLASS_NUMBER);

Casting a number to a string in TypeScript

const page_number = 3;

window.location.hash = page_number as string; // Error

"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.

window.location.hash = (page_number as unknown) as string; // Correct way

Passing data through intent using Serializable

Don't forget to implement Serializable in every class your object will use like a list of objects. Else your app will crash.

Example:

public class City implements Serializable {

private List<House> house;

public List<House> getHouse() {
    return house;
}

public void setHouse(List<House> house) {
    this.house = house;
}}

Then House needs to implements Serializable as so :

public class House implements Serializable {

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}}

Then you can use:

Bundle bundle = new Bundle();
bundle.putSerializable("city", city);
intent.putExtras(bundle);

And retreive it with:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
City city =  (City)bundle.getSerializable("city");

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

Install dependencies globally and locally using package.json

All modules from package.json are installed to ./node_modules/

I couldn't find this explicitly stated but this is the package.json reference for NPM.

Populating VBA dynamic arrays

As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve. Brett suggested Mod to do this.

You can also use a user defined Type and Sub to do this. Consider my code below:

Public Type dsIntArrayType
   eElems() As Integer
   eSize As Integer
End Type

Public Sub PushBackIntArray( _
    ByRef dsIntArray As dsIntArrayType, _
    ByVal intValue As Integer)

    With dsIntArray
    If UBound(.eElems) < (.eSize + 1) Then
        ReDim Preserve .eElems(.eSize * 2 + 1)
    End If
    .eSize = .eSize + 1
    .eElems(.eSize) = intValue
    End With

End Sub

This calls ReDim Preserve only when the size has doubled. The member variable eSize keeps track of the actual data size of eElems. This approach has helped me improve performance when final array length is not known until run time.

Hope this helps others too.

How to echo xml file in php

This works:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>

How to remove/ignore :hover css style on touch devices

It was helpful for me: link

function hoverTouchUnstick() {
    // Check if the device supports touch events
    if('ontouchstart' in document.documentElement) {
        // Loop through each stylesheet
        for(var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
            var sheet = document.styleSheets[sheetI];
            // Verify if cssRules exists in sheet
            if(sheet.cssRules) {
                // Loop through each rule in sheet
                for(var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
                    var rule = sheet.cssRules[ruleI];
                    // Verify rule has selector text
                    if(rule.selectorText) {
                        // Replace hover psuedo-class with active psuedo-class
                        rule.selectorText = rule.selectorText.replace(":hover", ":active");
                    }
                }
            }
        }
    }
}

How can I solve ORA-00911: invalid character error?

I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT statement, I had some commented notes that included special characters. Removing the comments resolved the issue.

What is the best way to get the count/length/size of an iterator?

You will always have to iterate. Yet you can use Java 8, 9 to do the counting without looping explicitely:

Iterable<Integer> newIterable = () -> iter;
long count = StreamSupport.stream(newIterable.spliterator(), false).count();

Here is a test:

public static void main(String[] args) throws IOException {
    Iterator<Integer> iter = Arrays.asList(1, 2, 3, 4, 5).iterator();
    Iterable<Integer> newIterable = () -> iter;
    long count = StreamSupport.stream(newIterable.spliterator(), false).count();
    System.out.println(count);
}

This prints:

5

Interesting enough you can parallelize the count operation here by changing the parallel flag on this call:

long count = StreamSupport.stream(newIterable.spliterator(), *true*).count();

How to use "svn export" command to get a single file from the repository?

For the substition impaired here is a real example from GitHub.com to a local directory:

svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces
svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces /temp/SvnExport/Washburn

See: Download a single folder or directory from a GitHub repo for more details.

What does -XX:MaxPermSize do?

-XX:PermSize -XX:MaxPermSize are used to set size for Permanent Generation.

Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.

AWS : The config profile (MyName) could not be found

Working with profiles is little tricky. Documentation can be found at: https://docs.aws.amazon.com/cli/latest/topic/config-vars.html (But you need to pay attention on env variables like AWS_PROFILE)

Using profile with aws cli requires a config file (default at ~/.aws/config or set using AWS_CONFIG_FILE). A sample config file for reference: `

[profile PROFILE_NAME]
 output=json
 region=us-west-1
 aws_access_key_id=foo
 aws_secret_access_key=bar

`

Env variable AWS_PROFILE informs AWS cli about the profile to use from AWS config. It is not an alternate of config file like AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY are for ~/.aws/credentials.

Another interesting fact is if AWS_PROFILE is set and the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables are set, then the credentials provided by AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY will override the credentials located in the profile provided by AWS_PROFILE.

When & why to use delegates?

I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.

Let's assume an application downloads an XML, and then saves the XML to a database.

I have 2 projects here which build my solution: FTP and a SaveDatabase.

So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.

Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.

During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.

See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.

class FTP
{
    public void Begin()
    {
        string filePath = DownloadFileFromFtpAndReturnPathName();

        SaveDatabase sd = new SaveDatabase();
        sd.Begin(filePath, NotifyFtpComplete());
    }

    private void NotifyFtpComplete()
    {
        //Code to send file to FTP site
    }
}


class SaveDatabase
{
    private void Begin(string filePath, delegateType NotifyJobComplete())
    {
        SaveToTheDatabase(filePath);

        /* InvokeTheDelegate - 
         * here we can execute the NotifyJobComplete
         * method at our preferred moment in the application,
         * despite the method being private and belonging
         * to a different class.
         */
        NotifyJobComplete.Invoke();
    }
}

So, with that explained, we can do it for real now with this Console Application using C#

using System;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that 
    * the SaveToDatabase cannot have any knowledge of this Program class.
    */
    class Program
    {
        static void Main(string[] args)
        {
            //Note, this NotifyDelegate type is defined in the SaveToDatabase project
            NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);

            SaveToDatabase sd = new SaveToDatabase();            
            sd.Start(nofityDelegate);
            Console.ReadKey();
        }

        /* this is the method which will be delegated -
         * the only thing it has in common with the NofityDelegate
         * is that it takes 0 parameters and that it returns void.
         * However, it is these 2 which are essential.
         * It is really important to notice that it writes
         * a variable which, due to no constructor,
         * has not yet been called (so _notice is not initialized yet).
         */ 
    private static void NotifyIfComplete()
    {
        Console.WriteLine(_notice);
    }

    private static string _notice = "Notified";
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegate nd)
        {
            /* I shouldn't write to the console from here, 
             * just for demonstration purposes
             */
            Console.WriteLine("SaveToDatabase Complete");
            Console.WriteLine(" ");
            nd.Invoke();
        }
    }
    public delegate void NotifyDelegate();
}

I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.

However, lastly, we can make it more useful by changing the delegate type to include a parameter.

using System.Text;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that the SaveToDatabase
     * cannot have any knowledge of this Program class.
     */
    class Program
    {
        static void Main(string[] args)
        {
            SaveToDatabase sd = new SaveToDatabase();
            /* Please note, that although NotifyIfComplete()
         * takes a string parameter, we do not declare it,
         * all we want to do is tell C# where the method is
         * so it can be referenced later,
         * we will pass the parameter later.
         */
            var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);

            sd.Start(notifyDelegateWithMessage );

            Console.ReadKey();
        }

        private static void NotifyIfComplete(string message)
        {
            Console.WriteLine(message);
        }
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegateWithMessage nd)
        {
                        /* To simulate a saving fail or success, I'm just going
         * to check the current time (well, the seconds) and
         * store the value as variable.
         */
            string message = string.Empty;
            if (DateTime.Now.Second > 30)
                message = "Saved";
            else
                message = "Failed";

            //It is at this point we pass the parameter to our method.
            nd.Invoke(message);
        }
    }

    public delegate void NotifyDelegateWithMessage(string message);
}

How do you convert a jQuery object into a string?

new String(myobj)

If you want to serialize the whole object to string, use JSON.

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

Maximum size of an Array in Javascript

Like @maerics said, your target machine and browser will determine performance.

But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:

console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
  • x=5e4 takes 16ms, good enough for 60fps
  • x=4e6 takes 250ms, which is noticeable but not a big deal
  • x=3e7 takes 1300ms, which is pretty bad
  • x=4e7 takes 11000ms and allocates an extra 2.5GB of memory

So around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.


EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1) you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.

How to check if memcache or memcached is installed for PHP?

You can look at phpinfo() or check if any of the functions of memcache is available. Ultimately, check whether the Memcache class exists or not.

e.g.

if(class_exists('Memcache')){
  // Memcache is enabled.
}

Eliminate space before \begin{itemize}

The way to fix this sort of problem is to redefine the relevant list environment. The enumitem package is my favourite way to do this sort of thing; it has many options and parameters that can be varied, either for all lists or for each list individually.

Here's how to do (something like) what it is I think you want:

\usepackage{enumitem}
\setlist{nolistsep}

or

\usepackage{enumitem}
\setlist{nosep}

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

Plotting in a non-blocking way with Matplotlib

A lot of these answers are super inflated and from what I can find, the answer isn't all that difficult to understand.

You can use plt.ion() if you want, but I found using plt.draw() just as effective

For my specific project I'm plotting images, but you can use plot() or scatter() or whatever instead of figimage(), it doesn't matter.

plt.figimage(image_to_show)
plt.draw()
plt.pause(0.001)

Or

fig = plt.figure()
...
fig.figimage(image_to_show)
fig.canvas.draw()
plt.pause(0.001)

If you're using an actual figure.
I used @krs013, and @Default Picture's answers to figure this out
Hopefully this saves someone from having launch every single figure on a separate thread, or from having to read these novels just to figure this out

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

How can I check if my python object is a number?

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

isinstance(n, numbers.Number)

Here it is in action with various kinds of numbers and one non-number:

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
...     print '%15s %s' % (n.__repr__(), isinstance(n, Number))
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

Pip install Matplotlib error with virtualenv

On OSX I was able to get matplotlib to install via:

pip install matplotlib==1.4.0

only after I ran:

brew install freetype

How do I print bytes as hexadecimal?

C:

static void print_buf(const char *title, const unsigned char *buf, size_t buf_len)
{
    size_t i = 0;
    fprintf(stdout, "%s\n", title);
    for(i = 0; i < buf_len; ++i)
    fprintf(stdout, "%02X%s", buf[i],
             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

}

C++:

void print_bytes(std::ostream& out, const char *title, const unsigned char *data, size_t dataLen, bool format = true) {
    out << title << std::endl;
    out << std::setfill('0');
    for(size_t i = 0; i < dataLen; ++i) {
        out << std::hex << std::setw(2) << (int)data[i];
        if (format) {
            out << (((i + 1) % 16 == 0) ? "\n" : " ");
        }
    }
    out << std::endl;
}

Foreach loop, determine which is the last iteration of the loop

How to convert foreach to react to the last element:

List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
    foreach (var current in myList)
    {
        Console.WriteLine(current);
    }
}
Console.WriteLine("equivalent that reacts to last element");
{
    var enumerator = myList.GetEnumerator();
    if (enumerator.MoveNext() == true) // Corner case: empty list.
    {
        while (true)
        {
            int current = enumerator.Current;

            // Handle current element here.
            Console.WriteLine(current);

            bool ifLastElement = (enumerator.MoveNext() == false);
            if (ifLastElement)
            {
                // Cleanup after last element
                Console.WriteLine("[last element]");
                break;
            }
        }
    }
    enumerator.Dispose();
}

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
    gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
    $(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

How to get IP address of running docker container

while read ctr;do
    sudo docker inspect --format "$ctr "'{{.Name}}{{ .NetworkSettings.IPAddress }}' $ctr
done < <(docker ps -a --filter status=running --format '{{.ID}}')

Running Python from Atom

Download and Install package here: https://atom.io/packages/script

To execute the python command in atom use the below shortcuts:

For Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B

If you're on Mac, press ? + I

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

Any difference between await Promise.all() and multiple await?

Generally, using Promise.all() runs requests "async" in parallel. Using await can run in parallel OR be "sync" blocking.

test1 and test2 functions below show how await can run async or sync.

test3 shows Promise.all() that is async.

jsfiddle with timed results - open browser console to see test results

Sync behavior. Does NOT run in parallel, takes ~1800ms:

const test1 = async () => {
  const delay1 = await Promise.delay(600); //runs 1st
  const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
  const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};

Async behavior. Runs in paralel, takes ~600ms:

const test2 = async () => {
  const delay1 = Promise.delay(600);
  const delay2 = Promise.delay(600);
  const delay3 = Promise.delay(600);
  const data1 = await delay1;
  const data2 = await delay2;
  const data3 = await delay3; //runs all delays simultaneously
}

Async behavior. Runs in parallel, takes ~600ms:

const test3 = async () => {
  await Promise.all([
  Promise.delay(600), 
  Promise.delay(600), 
  Promise.delay(600)]); //runs all delays simultaneously
};

TLDR; If you are using Promise.all() it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.

Template not provided using create-react-app

npx create-react-app@latest your-project-name

work for me after trying all the answers hope that can help someone in the future.

Can you force Vue.js to reload/re-render?

In order to reload/re-render/refresh component, stop the long codings. There is a Vue.JS way of doing that.

Just use :key attribute.

For example:

<my-component :key="unique" />

I am using that one in BS Vue Table Slot. Telling that I will do something for this component so make it unique.

Xpath: select div that contains class AND whose specific child element contains text

To find a div of a certain class that contains a span at any depth containing certain text, try:

//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]

That said, this solution looks extremely fragile. If the table happens to contain a span with the text you're looking for, the div containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-

  1. jQuery.dataTables.min.js
  2. dataTables.bootstrap.min.js
  3. dataTables.bootstrap.min.css
  4. bootstrap-datepicker.css
  5. bootstrap-datepicker.js

They are valid if you are using bootstrap in your project.

I hope this will help you. Regards, Vivek Singla

What does enctype='multipart/form-data' mean?

Set the method attribute to POST because file content can't be put inside a URL parameter using a form.

Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text of the form body that may be sent with them.

How to pass json POST data to Web API method as an object?

Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.

Here is my JavaScript (using AngluarJS):

$scope.updateUserActivity = function (_objuserActivity) {
        $http
        ({
            method: 'post',
            url: 'your url here',
            headers: { 'Content-Type': 'application/json'},
            data: JSON.stringify(_objuserActivity)
        })
        .then(function (response)
        {
            alert("success");
        })
        .catch(function (response)
        {
            alert("failure");
        })
        .finally(function ()
        {
        });

And here is my WebAPI Controller:

[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
    return "hello";
}

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

How to backup a local Git repository?

Found the simple official way after wading through the walls of text above that would make you think there is none.

Create a complete bundle with:

$ git bundle create <filename> --all

Restore it with:

$ git clone <filename> <folder>

This operation is atomic AFAIK. Check official docs for the gritty details.

Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.

No space left on device

You can execute the following commands

lsof / |grep deleted

kill the process id's, which free up the disk space.

How to resolve Unneccessary Stubbing exception

Replace

@RunWith(MockitoJUnitRunner.class)

with

@RunWith(MockitoJUnitRunner.Silent.class)

or remove @RunWith(MockitoJUnitRunner.class)

or just comment out the unwanted mocking calls (shown as unauthorised stubbing).

How to insert strings containing slashes with sed?

this line should work for your 3 examples:

sed -r 's#\?(page)=([^&]*)&#/\1/\2#g' a.txt
  • I used -r to save some escaping .
  • the line should be generic for your one, two three case. you don't have to do the sub 3 times

test with your example (a.txt):

kent$  echo "?page=one&
?page=two&
?page=three&"|sed -r 's#\?(page)=([^&]*)&#/\1/\2#g'
/page/one
/page/two
/page/three

How to send emails from my Android application?

This method work for me. It open Gmail app (if installed) and set mailto.

public void openGmail(Activity activity) {
    Intent emailIntent = new Intent(Intent.ACTION_VIEW);
    emailIntent.setType("text/plain");
    emailIntent.setType("message/rfc822");
    emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
    final PackageManager pm = activity.getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
    ResolveInfo best = null;
    for (final ResolveInfo info : matches)
        if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
            best = info;
    if (best != null)
        emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
    activity.startActivity(emailIntent);
}

why are there two different kinds of for loops in java?

Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.

deleting folder from java

I found this piece of code more understadable and working:

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete(); // The directory is empty now and can be deleted.
}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

How to get numeric value from a prompt box?

You can use parseInt() but, as mentioned, the radix (base) should be specified:

x = parseInt(x, 10);
y = parseInt(y, 10);

10 means a base-10 number.

See this link for an explanation of why the radix is necessary.

When to use pthread_exit() and when to use pthread_join() in Linux?

Both methods ensure that your process doesn't end before all of your threads have ended.

The join method has your thread of the main function explicitly wait for all threads that are to be "joined".

The pthread_exit method terminates your main function and thread in a controlled way. main has the particularity that ending main otherwise would be terminating your whole process including all other threads.

For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main function. The advantage of that method is that your main doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main doesn't know anything about.

Using "-Filter" with a variable

Try this:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

Two Decimal places using c#

Another way :

decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);

Android button with icon and text

To add an image to left, right, top or bottom, you can use attributes like this:

android:drawableLeft
android:drawableRight
android:drawableTop
android:drawableBottom

The sample code is given above. You can also achieve this using relative layout.

Android toolbar center title and custom font

Layout:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >

     <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>

Code:

    Toolbar mToolbar = parent.findViewById(R.id.toolbar_top);
    TextView mToolbarCustomTitle = parent.findViewById(R.id.toolbar_title);

    //setup width of custom title to match in parent toolbar
    mToolbar.postDelayed(new Runnable()
    {
        @Override
        public void run ()
        {
            int maxWidth = mToolbar.getWidth();
            int titleWidth = mToolbarCustomTitle.getWidth();
            int iconWidth = maxWidth - titleWidth;

            if (iconWidth > 0)
            {
                //icons (drawer, menu) are on left and right side
                int width = maxWidth - iconWidth * 2;
                mToolbarCustomTitle.setMinimumWidth(width);
                mToolbarCustomTitle.getLayoutParams().width = width;
            }
        }
    }, 0);

Get the distance between two geo points

you can get distance and time using google Map API Google Map API

just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's

void parseJSONForDurationAndKMS(String json) throws JSONException {

    Log.d(TAG, "called parseJSONForDurationAndKMS");
    JSONObject jsonObject = new JSONObject(json);
    String distance;
    String duration;
    distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");

    Log.d(TAG, "distance : " + distance);
    Log.d(TAG, "duration : " + duration);

    distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);


}

How to wait until an element is present in Selenium?

You need to call ignoring with exception to ignore while the WebDriver will wait.

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(200, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchElementException.class);

See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use

WebElement element = (new WebDriverWait(driver, 10))
   .until(ExpectedConditions.elementToBeClickable(By.id("someid")));

*Update for newer versions of Selenium:

withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)

So the code will look as such:

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30)
        .pollingEvery(Duration.ofMillis(200)
        .ignoring(NoSuchElementException.class);

Basic tutorial for waiting can be found here.

How to convert text to binary code in JavaScript?

this seems to be the simplified version

Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")

Saving and loading objects and using pickle

You didn't open the file in binary mode.

open("Fruits.obj",'rb')

Should work.

For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.

(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).

I tested your code, and it works.

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

How to determine the installed webpack version

Version Installed:

Using webpack CLI: (--version, -v Show version number [boolean])

webpack --version

or:

webpack -v

Using npm list command:

npm list webpack

Results in name@version-range:

<projectName>@<projectVersion> /path/to/project
+-- webpack@<version-range>

Using yarn list command:

yarn list webpack

How to do it programmatically?

Webpack 2 introduced Configuration Types.

Instead of exporting a configuration object, you may return a function which accepts an environment as argument. When running webpack, you may specify build environment keys via --env, such as --env.production or --env.platform=web.

We will use a build environment key called --env.version.

webpack --env.version $(webpack --version)

or:

webpack --env.version $(webpack -v)

For this to work we will need to do two things:

Change our webpack.config.js file and use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

-module.exports = {
+module.exports = function(env) {
+  return {
    plugins: [
      new webpack.DefinePlugin({
+        WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
      })
    ]
+  };
};

Now we can access the global constant like so:

console.log(WEBPACK_VERSION);

Latest version available:

Using npm view command will return the latest version available on the registry:

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]


For webpack use:

npm view webpack version

How to update gradle in android studio?

For those who still have this problem (for example to switch from 2.8.0 to 2.10.0), move to the file gradle-wrapper.properties and set distributionUrl like that.

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and don't forget to Sync after

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

Using NotNull Annotation in method argument

As mentioned above @NotNull does nothing on its own. A good way of using @NotNull would be using it with Objects.requireNonNull

public class Foo {
    private final Bar bar;

    public Foo(@NotNull Bar bar) {
        this.bar = Objects.requireNonNull(bar, "bar must not be null");
    }
}

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

Adjust list style image position?

I'm using something like this, seems pretty clean & simple for me:

ul { 
     list-style:  none;
     /* remove left padding, it's usually unwanted: */
     padding:  0;
}

li:before {
     content:  url(icon.png);
     display:  inline-block;
     vertical-align:  middle;

     /* If you want some space between icon and text: */
     margin-right:   1em;
}

The above code works as is in most of my cases.
For exact adjustment you can modify vertical-align, e.g.:

vertical-align:  top;

/* or */
vertical-align:  -10px;

/* or whatever you need instead of "middle" */

You may set list-style: none on li instead of ul if you prefer.

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \
      http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven't got any solution except the above solution.

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

AngularJS : The correct way of binding to a service properties

Late to the party, but for future Googlers - don't use the provided answer.

JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".

In above example, instead of binding attributes of a service, why don't we expose the service to the scope?

$scope.hello = HelloService;

This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.

And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.

Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.

In that particular demo code you supplied I would recommend you do:

 function TimerCtrl1($scope, Timer) {
   $scope.timer = Timer;
 }
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...

Edit:

As I mentioned above, you can control the behaviour of your service attributes using defineProperty

Example:

// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
  get: function() { return self.data.variable; },
  set: function(newValue) { 
         self.data.variable = newValue; 
         // let's update the database too to reflect changes in data-model !
         self.updateDatabaseWithNewData(data);
       },
  enumerable: true,
  configurable: true
});

Now in our controller if we do

$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';

our service will change the value of propertyWithSetter and also post the new value to database somehow!

Or we can take any approach we want.

Refer to the MDN documentation for defineProperty.

Convert DOS line endings to Linux line endings in Vim

You can use the following command:
:%s/^V^M//g
where the '^' means use CTRL key.

Pull request vs Merge request

They are the same feature

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we’ll refer to them as merge requests.

-- https://about.gitlab.com/2014/09/29/gitlab-flow/

Laravel 5: Display HTML with Blade

Please use

{!! $test !!} 

Only in case of HTML while if you want to render data, sting etc. use

{{ $test }}

This is because when your blade file is compiled

{{ $test }} is converted to <?php echo e($test) ?> while

{!! $test !!} is converted to <?php echo $test ?>

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

If you are using AutoMapper with Entity Framework on the same class, you might hit this problem. For instance if your class is

class A
{
    public ClassB ClassB { get; set; }
    public int ClassBId { get; set; }
}

AutoMapper.Map<A, A>(input, destination);

This will try to copy both properties. In this case, ClassBId is non Nullable. Since AutoMapper will copy destination.ClassB = input.ClassB; this will cause a problem.

Set your AutoMapper to Ignore ClassB property.

 cfg.CreateMap<A, A>()
     .ForMember(m => m.ClassB, opt => opt.Ignore()); // We use the ClassBId

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

HTML select form with option to enter custom value

jQuery Solution!

Demo: http://jsfiddle.net/69wP6/2/

Another Demo Below(updated!)

I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.

I am sharing the fiddle with all of you!

HTML

<div id="billdesc">
    <select id="test">
      <option class="non" value="option1">Option1</option>
      <option class="non" value="option2">Option2</option>
      <option class="editable" value="other">Other</option>
    </select>
    <input class="editOption" style="display:none;"></input>
</div>

CSS

body{
    background: blue;
}
#billdesc{
    padding-top: 50px;
}
#test{
    width: 100%;
    height: 30px;
}
option {
    height: 30px;
    line-height: 30px;
}

.editOption{
    width: 90%;
    height: 24px;
    position: relative;
    top: -30px

}

jQuery

var initialText = $('.editable').val();
$('.editOption').val(initialText);

$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();

if(selected == "editable"){
  $('.editOption').show();


  $('.editOption').keyup(function(){
      var editText = $('.editOption').val();
      $('.editable').val(editText);
      $('.editable').html(editText);
  });

}else{
  $('.editOption').hide();
}
});

Edit : Added some simple touches design wise, so people can clearly see where the input ends!

JS Fiddle : http://jsfiddle.net/69wP6/4/

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

java.lang.IllegalAccessError: tried to access method

This happens when accessing a package scoped method of a class that is in the same package but is in a different jar and classloader.

This was my source, but the link is now broken. Following is full text from google cache:

Packages (as in package access) are scoped per ClassLoader.

You state that the parent ClassLoader loads the interface and the child ClassLoader loads the implementation. This won't work because of the ClassLoader-specific nature of package scoping. The interface isn't visible to the implementation class because, even though it's the same package name, they're in different ClassLoaders.

I only skimmed the posts in this thread, but I think you've already discovered that this will work if you declare the interface to be public. It would also work to have both interface and implementation loaded by the same ClassLoader.

Really, if you expect arbitrary folks to implement the interface (which you apparently do if the implementation is being loaded by a different ClassLoader), then you should make the interface public.

The ClassLoader-scoping of package scope (which applies to accessing package methods, variables, etc.) is similar to the general ClassLoader-scoping of class names. For example, I can define two classes, both named com.foo.Bar, with entirely different implementation code if I define them in separate ClassLoaders.

Joel

What is the difference between & and && in Java?

Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100

Repeat each row of data.frame the number of times specified in a column

Another dplyr alternative with slice where we repeat each row number freq times

library(dplyr)

df %>%  
  slice(rep(seq_len(n()), freq)) %>% 
  select(-freq)

#  var1 var2
#1    a    d
#2    b    e
#3    b    e
#4    c    f
#5    c    f
#6    c    f

seq_len(n()) part can be replaced with any of the following.

df %>% slice(rep(1:nrow(df), freq)) %>% select(-freq)
#Or
df %>% slice(rep(row_number(), freq)) %>% select(-freq)
#Or
df %>% slice(rep(seq_len(nrow(.)), freq)) %>% select(-freq)

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Android load from URL to Bitmap

fun getBitmap(url : String?) : Bitmap? {
    var bmp : Bitmap ? = null
    Picasso.get().load(url).into(object : com.squareup.picasso.Target {
        override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
            bmp =  bitmap
        }

        override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}

        override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
    })
    return bmp
}

Try this with picasso

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Android Studio emulator does not come with Play Store for API 23

Go to http://opengapps.org/ and download the pico version of your platform and android version. Unzip the downloaded folder to get
1. GmsCore.apk
2. GoogleServicesFramework.apk
3. GoogleLoginService.apk
4. Phonesky.apk

Then, locate your emulator.exe. You will probably find it in
C:\Users\<YOUR_USER_NAME>\AppData\Local\Android\sdk\tools

Run the command:
emulator -avd <YOUR_EMULATOR'S_NAME> -netdelay none -netspeed full -no-boot-anim -writable-system

Note: Use -writable-system to start your emulator with writable system image.

Then,
adb root
adb remount
adb push <PATH_TO GmsCore.apk> /system/priv-app
adb push <PATH_TO GoogleServicesFramework.apk> /system/priv-app
adb push <PATH_TO GoogleLoginService.apk> /system/priv-app
adb push <PATH_TO Phonesky.apk> /system/priv-app

Then, reboot the emulator
adb shell stop
adb shell start

To verify run,
adb shell pm list packages and you will find com.google.android.gms package for google

Environment variable substitution in sed

Actually, the simplest thing (in GNU sed, at least) is to use a different separator for the sed substitution (s) command. So, instead of s/pattern/'$mypath'/ being expanded to s/pattern//my/path/, which will of course confuse the s command, use s!pattern!'$mypath'!, which will be expanded to s!pattern!/my/path!. I’ve used the bang (!) character (or use anything you like) which avoids the usual, but-by-no-means-your-only-choice forward slash as the separator.

Multiple lines of input in <input type="text" />

You can't. At the time of writing, the only HTML form element that's designed to be multi-line is <textarea>.

make bootstrap twitter dialog modal draggable

In my case I am enabling draggable. It works.

var bootstrapDialog = new BootstrapDialog({
    title: 'Message',
    draggable: true,
    closable: false,
    size: BootstrapDialog.SIZE_WIDE,
    message: 'Hello World',
    buttons: [{
         label: 'close',
         action: function (dialogRef) {
             dialogRef.close();
         }
     }],
});
bootstrapDialog.open();

Might be it helps you.

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

"for" vs "each" in Ruby

This is the only difference:

each:

irb> [1,2,3].each { |x| }
  => [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
    from (irb):2
    from :0

for:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.

Other than that, for is just syntax sugar for the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

Do Java arrays have a maximum size?

Arrays are non-negative integer indexed , so maximum array size you can access would be Integer.MAX_VALUE. The other thing is how big array you can create. It depends on the maximum memory available to your JVM and the content type of the array. Each array element has it's size, example. byte = 1 byte, int = 4 bytes, Object reference = 4 bytes (on a 32 bit system)

So if you have 1 MB memory available on your machine, you could allocate an array of byte[1024 * 1024] or Object[256 * 1024].

Answering your question - You can allocate an array of size (maximum available memory / size of array item).

Summary - Theoretically the maximum size of an array will be Integer.MAX_VALUE. Practically it depends on how much memory your JVM has and how much of that has already been allocated to other objects.

Filtering a pyspark dataframe using isin by exclusion

It looks like the ~ gives the functionality that I need, but I am yet to find any appropriate documentation on it.

df.filter(~col('bar').isin(['a','b'])).show()



+---+---+
| id|bar|
+---+---+
|  4|  c|
|  5|  d|
+---+---+

In python, how do I cast a class object to a dict

There is no magic method that will do what you want. The answer is simply name it appropriately. asdict is a reasonable choice for a plain conversion to dict, inspired primarily by namedtuple. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.

Other answers suggest using __iter__, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.

How to upload (FTP) files to server in a bash script?

#/bin/bash
# $1 is the file name
# usage: this_script  <filename>
IP_address="xx.xxx.xx.xx"
username="username"
domain=my.ftp.domain
password=password

echo "
 verbose
 open $IP_address
 USER $username $password
 put $1
 bye
" | ftp -n > ftp_$$.log

How do I find out what version of Sybase is running

Try running below command (Works on both windows and linux)

isql -v

Xcode 6: Keyboard does not show up in simulator

Simple way is just Press command + k

MySQL update CASE WHEN/THEN/ELSE

That's because you missed ELSE.

"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)

Is an entity body allowed for an HTTP DELETE request?

Roy Fielding on the HTTP mailing list clarifies that on the http mailing list https://lists.w3.org/Archives/Public/ietf-http-wg/2020JanMar/0123.html and says:

GET/DELETE body are absolutely forbidden to have any impact whatsoever on the processing or interpretation of the request

This means that the body must not modify the behavior of the server. Then he adds:

aside from the necessity to read and discard the bytes received in order to maintain the message framing.

And finally the reason for not forbidding the body:

The only reason we didn't forbid sending a body is because that would lead to lazy implementations assuming no body would be sent.

So while clients can send the payload body, servers should drop it and APIs should not define a semantic for the payload body on those requests.

Create nice column output in python

Transposing the columns like that is a job for zip:

>>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> list(zip(*a))
[('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]

To find the required length of each column, you can use max:

>>> trans_a = zip(*a)
>>> [max(len(c) for c in b) for b in trans_a]
[10, 10, 1]

Which you can use, with suitable padding, to construct strings to pass to print:

>>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
>>> padding = ' ' # You might want more
>>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
'a          b          c'

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

Double border with different color

Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:

_x000D_
_x000D_
body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
  padding: 2em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
  background: none;_x000D_
  border: 4px solid #fff;_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  left: 4px;_x000D_
  right: 4px;_x000D_
  bottom: 4px;_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow declarations (separated by commas) to do so:

_x000D_
_x000D_
body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
  box-shadow:_x000D_
    inset 0 0 0 4px #eee,_x000D_
    inset 0 0 0 8px #ddd,_x000D_
    inset 0 0 0 12px #ccc,_x000D_
    inset 0 0 0 16px #bbb,_x000D_
    inset 0 0 0 20px #aaa,_x000D_
    inset 0 0 0 20px #999,_x000D_
    inset 0 0 0 20px #888;_x000D_
  /* And so on and so forth, if you want border-ception */_x000D_
  margin: 0 auto;_x000D_
  padding: 3em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can a shell script set environment variables of the calling shell?

Other than writings conditionals depending on what $SHELL/$TERM is set to, no. What's wrong with using Perl? It's pretty ubiquitous (I can't think of a single UNIX variant that doesn't have it), and it'll spare you the trouble.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

How to return history of validation loss in Keras

The following simple code works great for me:

    seqModel =model.fit(x_train, y_train,
          batch_size      = batch_size,
          epochs          = num_epochs,
          validation_data = (x_test, y_test),
          shuffle         = True,
          verbose=0, callbacks=[TQDMNotebookCallback()]) #for visualization

Make sure you assign the fit function to an output variable. Then you can access that variable very easily

# visualizing losses and accuracy
train_loss = seqModel.history['loss']
val_loss   = seqModel.history['val_loss']
train_acc  = seqModel.history['acc']
val_acc    = seqModel.history['val_acc']
xc         = range(num_epochs)

plt.figure()
plt.plot(xc, train_loss)
plt.plot(xc, val_loss)

Hope this helps. source: https://keras.io/getting-started/faq/#how-can-i-record-the-training-validation-loss-accuracy-at-each-epoch

Conda command not found

For Conda > 4.4 follow this:

$ echo ". /home/ubuntu/miniconda2/etc/profile.d/conda.sh" >> ~/.bashrc

then you need to reload user bash so you need to log out:

exit

and then log again.

Where can I find the API KEY for Firebase Cloud Messaging?

STEP 1: Go to Firebase Console

STEP 2: Select your Project

STEP 3: Click on Settings icon and select Project Settings

Select Project Setting

STEP 4: Select CLOUD MESSAGING tab

enter image description here

Git copy file preserving history

Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.

The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).

So in git this is not a matter of how you commit your changes but how you look at the committed changes later.

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

Disable/Enable Submit Button until all forms have been filled

I just posted this on Disable Submit button until Input fields filled in. Works for me.

Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.

http://www.w3schools.com/jsref/event_form_onsubmit.asp

<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
   ...
</form>

function validateCreditCardForm(){
    var result = false;
    if (($('#billing-cc-exp').val().length > 0) &&
        ($('#billing-cvv').val().length  > 0) &&
        ($('#billing-cc-number').val().length > 0)) {
            result = true;
    }
    return result;
}

Twitter Bootstrap - how to center elements horizontally or vertically

For future visitors to this question:

If you are trying to center an image in a div but the image won't center, this could describe your problem:

jsFiddle DEMO of the problem

<div class="col-sm-4 text-center">
    <img class="img-responsive text-center" src="myPic.jpg" />
</div>

The img-responsive class adds a display:block instruction to the image tag, which stops text-align:center (text-center class) from working.

SOLUTION:

<div class="col-sm-4">
    <img class="img-responsive center-block" src="myPic.jpg" />
</div>

jsFiddle of the solution

Adding the center-block class overrides the display:block instruction put in by using the img-responsive class.

Without the img-responsive class, the image would center just by adding text-center class


Update:

Also, you should know the basics of flexbox and how to use it, since Bootstrap4 now uses it natively.

Here is an excellent, fast-paced video tutorial by Brad Schiff

Here is a great cheat sheet

How to hide a status bar in iOS?

I am supporting iOS 5, 6, & 7. My app is iPad only. I needed to use all of the following:

[[UIApplication sharedApplication] setStatusBarHidden:YES];

View Controller:

- (BOOL)prefersStatusBarHidden{ return YES; }

Info.plist

    <key>UIStatusBarHidden</key>
    <string>YES</string>

    <key>UIStatusBarHidden~ipad</key>
    <true/>

    <key>UIViewControllerBasedStatusBarAppearance</key>
    <string>NO</string>

100% width in React Native Flexbox

Noted: Try to fully understanding about flex concept.

       <View style={{
          flex: 2,
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          <View style ={{
              flex: 1,
              alignItems: 'center, 
              height: 50, 
              borderWidth: 1, 
              borderColor: '#000' 
          }}>
               <Text>Welcome to React Nativ</Text>
           </View>
           <View style={{
              flex: 1,
              alignItems: 'center,
              borderWidth: 1, 
              borderColor: 'red ', 
              height: 50
            }}
            >
              <Text> line 1 </Text>
            </View>
          <View style={{
            flex: 1,
            alignItems: 'center, 
            height: 50, 
            borderWidth: 1,                     
            borderColor: '#000'
          }}>
             <Text>
              Press Cmd+R to reload,{'\n'}
              Cmd+D or shake for dev menu
             </Text>
           </View>
       </View>

Python - Extracting and Saving Video Frames

This is Function which will convert most of the video formats to number of frames there are in the video. It works on Python3 with OpenCV 3+

import cv2
import time
import os

def video_to_frames(input_loc, output_loc):
    """Function to extract frames from input video file
    and save them as separate frames in an output directory.
    Args:
        input_loc: Input video file.
        output_loc: Output directory to save the frames.
    Returns:
        None
    """
    try:
        os.mkdir(output_loc)
    except OSError:
        pass
    # Log the time
    time_start = time.time()
    # Start capturing the feed
    cap = cv2.VideoCapture(input_loc)
    # Find the number of frames
    video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print ("Number of frames: ", video_length)
    count = 0
    print ("Converting video..\n")
    # Start converting the video
    while cap.isOpened():
        # Extract the frame
        ret, frame = cap.read()
        # Write the results back to output location.
        cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
        count = count + 1
        # If there are no more frames left
        if (count > (video_length-1)):
            # Log the time again
            time_end = time.time()
            # Release the feed
            cap.release()
            # Print stats
            print ("Done extracting frames.\n%d frames extracted" % count)
            print ("It took %d seconds forconversion." % (time_end-time_start))
            break

if __name__=="__main__":

    input_loc = '/path/to/video/00009.MTS'
    output_loc = '/path/to/output/frames/'
    video_to_frames(input_loc, output_loc)

It supports .mts and normal files like .mp4 and .avi. Tried and Tested on .mts files. Works like a Charm.

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

HTML5 Audio Looping

To add some more advice combining the suggestions of @kingjeffrey and @CMS: You can use loop where it is available and fall back on kingjeffrey's event handler when it isn't. There's a good reason why you want to use loop and not write your own event handler: As discussed in the Mozilla bug report, while loop currently doesn't loop seamlessly (without a gap) in any browser I know of, it's certainly possible and likely to become standard in the future. Your own event handler will never be seamless in any browser (since it has to pump around through the JavaScript event loop). Therefore, it's best to use loop where possible instead of writing your own event. As CMS pointed out in a comment on Anurag's answer, you can detect support for loop by querying the loop variable -- if it is supported it will be a boolean (false), otherwise it will be undefined, as it currently is in Firefox.

Putting these together:

myAudio = new Audio('someSound.ogg'); 
if (typeof myAudio.loop == 'boolean')
{
    myAudio.loop = true;
}
else
{
    myAudio.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);
}
myAudio.play();

How to access to a child method from the parent in vue.js

You can use ref.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

Code of component.

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

Unique Key constraints for multiple columns in Entity Framework

With Entity Framework 6.1, you can now do this:

[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }

[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }

The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN

Add CSS box shadow around the whole DIV

You're offsetting the shadow, so to get it to uniformly surround the box, don't offset it:

-moz-box-shadow: 0 0 3px #ccc;
-webkit-box-shadow: 0 0 3px #ccc;
box-shadow: 0 0 3px #ccc;

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

invalidate cache in android studio will resolve this issue. Go to file-> click on invalidate cache/restart option.

SQL Query - Using Order By in UNION

The second table cannot include the table name in the ORDER BY clause.

So...

SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1

Does not throw an exception

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

Proper use of 'yield return'

I would have used version 2 of the code in this case. Since you have the full-list of products available and that's what expected by the "consumer" of this method call, it would be required to send the complete information back to the caller.

If caller of this method requires "one" information at a time and the consumption of the next information is on-demand basis, then it would be beneficial to use yield return which will make sure the command of execution will be returned to the caller when a unit of information is available.

Some examples where one could use yield return is:

  1. Complex, step-by-step calculation where caller is waiting for data of a step at a time
  2. Paging in GUI - where user might never reach to the last page and only sub-set of information is required to be disclosed on current page

To answer your questions, I would have used the version 2.

'POCO' definition

In Java land typically "PO" means "plain old". The rest can be tricky, so I'm guessing that your example (in the context of Java) is "plain old class object".

some other examples

  • POJO (plain old java object)
  • POJI (plain old java interface)

What is the strict aliasing rule?

The best explanation I have found is by Mike Acton, Understanding Strict Aliasing. It's focused a little on PS3 development, but that's basically just GCC.

From the article:

"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"

So basically if you have an int* pointing to some memory containing an int and then you point a float* to that memory and use it as a float you break the rule. If your code does not respect this, then the compiler's optimizer will most likely break your code.

The exception to the rule is a char*, which is allowed to point to any type.

How do I move a file from one location to another in Java?

myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

Pull all images from a specified directory and then display them

In case anyone is looking for recursive.

<?php

echo scanDirectoryImages("images");

/**
 * Recursively search through directory for images and display them
 * 
 * @param  array  $exts
 * @param  string $directory
 * @return string
 */
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }
    $html = '';
    if (
        is_readable($directory)
        && (file_exists($directory) || is_dir($directory))
    ) {
        $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);
                    }
                    if (
                        is_file($path)
                        && in_array(end(explode('.', end(explode('/', $path)))), $exts)
                    ) {
                        $html .= '<a href="' . $path . '"><img src="' . $path
                            . '" style="max-height:100px;max-width:100px" /></a>';
                    }
                }
            }
        }
        closedir($directoryList);
    }
    return $html;
}

How to auto-reload files in Node.js?

node-dev works great. npm install node-dev

It even gives a desktop notification when the server is reloaded and will give success or errors on the message.

start your app on command line with:

node-dev app.js

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

How to install PostgreSQL's pg gem on Ubuntu?

Try this

sudo apt-get install postgresql postgresql-contrib libpq-dev

You should install PG Database server in the first place to install clients. Afterwards, you install clients.

See this blog post to know about setting up PostGresSQL for the first time for Ruby on Rails development.

Remove characters before character "."

You can use the IndexOf method and the Substring method like so:

string output = input.Substring(input.IndexOf('.') + 1);

The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.

Get query from java.sql.PreparedStatement

This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString(). I.e.

System.out.println(preparedStatement);

To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx() methods and finally populates a SQL string on toString() based on the logged information. For example Log4jdbc or P6Spy.

Can I call a function of a shell script from another shell script?

You can't directly call a function in another shell script.

You can move your function definitions into a separate file and then load them into your script using the . command, like this:

. /path/to/functions.sh

This will interpret functions.sh as if it's content were actually present in your file at this point. This is a common mechanism for implementing shared libraries of shell functions.

Total width of element (including padding and border) in jQuery

looks like outerWidth is broken in the latest version of jquery.

The discrepancy happens when

the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"

How to completely remove Python from a Windows machine?

I had window 7 (64 bit) and Python 2.7.12, I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

Difference between DataFrame, Dataset, and RDD in Spark

First thing is DataFrame was evolved from SchemaRDD.

depreated method toSchemaRDD

Yes.. conversion between Dataframe and RDD is absolutely possible.

Below are some sample code snippets.

  • df.rdd is RDD[Row]

Below are some of options to create dataframe.

  • 1) yourrddOffrow.toDF converts to DataFrame.

  • 2) Using createDataFrame of sql context

    val df = spark.createDataFrame(rddOfRow, schema)

where schema can be from some of below options as described by nice SO post..
From scala case class and scala reflection api

import org.apache.spark.sql.catalyst.ScalaReflection
val schema = ScalaReflection.schemaFor[YourScalacaseClass].dataType.asInstanceOf[StructType]

OR using Encoders

import org.apache.spark.sql.Encoders
val mySchema = Encoders.product[MyCaseClass].schema

as described by Schema can also be created using StructType and StructField

val schema = new StructType()
  .add(StructField("id", StringType, true))
  .add(StructField("col1", DoubleType, true))
  .add(StructField("col2", DoubleType, true)) etc...

image description

In fact there Are Now 3 Apache Spark APIs..

enter image description here

  1. RDD API :

The RDD (Resilient Distributed Dataset) API has been in Spark since the 1.0 release.

The RDD API provides many transformation methods, such as map(), filter(), and reduce() for performing computations on the data. Each of these methods results in a new RDD representing the transformed data. However, these methods are just defining the operations to be performed and the transformations are not performed until an action method is called. Examples of action methods are collect() and saveAsObjectFile().

RDD Example:

rdd.filter(_.age > 21) // transformation
   .map(_.last)// transformation
.saveAsObjectFile("under21.bin") // action

Example: Filter by attribute with RDD

rdd.filter(_.age > 21)
  1. DataFrame API

Spark 1.3 introduced a new DataFrame API as part of the Project Tungsten initiative which seeks to improve the performance and scalability of Spark. The DataFrame API introduces the concept of a schema to describe the data, allowing Spark to manage the schema and only pass data between nodes, in a much more efficient way than using Java serialization.

The DataFrame API is radically different from the RDD API because it is an API for building a relational query plan that Spark’s Catalyst optimizer can then execute. The API is natural for developers who are familiar with building query plans

Example SQL style :

df.filter("age > 21");

Limitations : Because the code is referring to data attributes by name, it is not possible for the compiler to catch any errors. If attribute names are incorrect then the error will only detected at runtime, when the query plan is created.

Another downside with the DataFrame API is that it is very scala-centric and while it does support Java, the support is limited.

For example, when creating a DataFrame from an existing RDD of Java objects, Spark’s Catalyst optimizer cannot infer the schema and assumes that any objects in the DataFrame implement the scala.Product interface. Scala case class works out the box because they implement this interface.

  1. Dataset API

The Dataset API, released as an API preview in Spark 1.6, aims to provide the best of both worlds; the familiar object-oriented programming style and compile-time type-safety of the RDD API but with the performance benefits of the Catalyst query optimizer. Datasets also use the same efficient off-heap storage mechanism as the DataFrame API.

When it comes to serializing data, the Dataset API has the concept of encoders which translate between JVM representations (objects) and Spark’s internal binary format. Spark has built-in encoders which are very advanced in that they generate byte code to interact with off-heap data and provide on-demand access to individual attributes without having to de-serialize an entire object. Spark does not yet provide an API for implementing custom encoders, but that is planned for a future release.

Additionally, the Dataset API is designed to work equally well with both Java and Scala. When working with Java objects, it is important that they are fully bean-compliant.

Example Dataset API SQL style :

dataset.filter(_.age < 21);

Evaluations diff. between DataFrame & DataSet : enter image description here

Catalist level flow..(Demystifying DataFrame and Dataset presentation from spark summit) enter image description here

Further reading... databricks article - A Tale of Three Apache Spark APIs: RDDs vs DataFrames and Datasets

Recursion or Iteration?

Loops may achieve a performance gain for your program. Recursion may achieve a performance gain for your programmer. Choose which is more important in your situation!

Spring REST Service: how to configure to remove null objects in json response

Since Jackson is being used, you have to configure that as a Jackson property. In the case of Spring Boot REST services, you have to configure it in application.properties or application.yml:

spring.jackson.default-property-inclusion = NON_NULL

source

How do I calculate a point on a circle’s circumference?

Here is my implementation in C#:

    public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
    {
        // Convert from degrees to radians via multiplication by PI/180        
        float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
        float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;

        return new PointF(x, y);
    }

What is the most effective way for float and double comparison?

My class based on previously posted answers. Very similar to Google's code but I use a bias which pushes all NaN values above 0xFF000000. That allows a faster check for NaN.

This code is meant to demonstrate the concept, not be a general solution. Google's code already shows how to compute all the platform specific values and I didn't want to duplicate all that. I've done limited testing on this code.

typedef unsigned int   U32;
//  Float           Memory          Bias (unsigned)
//  -----           ------          ---------------
//   NaN            0xFFFFFFFF      0xFF800001
//   NaN            0xFF800001      0xFFFFFFFF
//  -Infinity       0xFF800000      0x00000000 ---
//  -3.40282e+038   0xFF7FFFFF      0x00000001    |
//  -1.40130e-045   0x80000001      0x7F7FFFFF    |
//  -0.0            0x80000000      0x7F800000    |--- Valid <= 0xFF000000.
//   0.0            0x00000000      0x7F800000    |    NaN > 0xFF000000
//   1.40130e-045   0x00000001      0x7F800001    |
//   3.40282e+038   0x7F7FFFFF      0xFEFFFFFF    |
//   Infinity       0x7F800000      0xFF000000 ---
//   NaN            0x7F800001      0xFF000001
//   NaN            0x7FFFFFFF      0xFF7FFFFF
//
//   Either value of NaN returns false.
//   -Infinity and +Infinity are not "close".
//   -0 and +0 are equal.
//
class CompareFloat{
public:
    union{
        float     m_f32;
        U32       m_u32;
    };
    static bool   CompareFloat::IsClose( float A, float B, U32 unitsDelta = 4 )
                  {
                      U32    a = CompareFloat::GetBiased( A );
                      U32    b = CompareFloat::GetBiased( B );

                      if ( (a > 0xFF000000) || (b > 0xFF000000) )
                      {
                          return( false );
                      }
                      return( (static_cast<U32>(abs( a - b ))) < unitsDelta );
                  }
    protected:
    static U32    CompareFloat::GetBiased( float f )
                  {
                      U32    r = ((CompareFloat*)&f)->m_u32;

                      if ( r & 0x80000000 )
                      {
                          return( ~r - 0x007FFFFF );
                      }
                      return( r + 0x7F800000 );
                  }
};

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

"A lambda expression with a statement body cannot be converted to an expression tree"

Is objects a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database. Try this

Arr[] myArray = objects.Select(o => new Obj() { 
    Var1 = o.someVar,
    Var2 = o.var2 
}).ToArray();

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Browsers can block access to window.top due to same origin policy. IE bugs also take place. Here's the working code:

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

top and self are both window objects (along with parent), so you're seeing if your window is the top window.

Converting a double to an int in C#

Casting will ignore anything after the decimal point, so 8.6 becomes 8.

Convert.ToInt32(8.6) is the safe way to ensure your double gets rounded to the nearest integer, in this case 9.

How do I set the size of an HTML text box?

Your textbox code:

<input type="text" class="textboxclass" />

Your CSS code:

input[type="text"] {
height: 10px;
width: 80px;
}

or

.textboxclass {
height: 10px;
width: 80px;
}

So, first you select your element with attributes (look at first example) or classes(look last example). Later, you assign height and width values to your element.

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

HTML-Tooltip position relative to mouse pointer

One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:

http://codepen.io/c0un7z3r0/pen/LZWXEw

Note that the span that contains the tooltip content is relative to the parent li. The magic is here:

ul#list_of_thrones li > span{
  display:none;
}
ul#list_of_thrones li:hover > span{
  position: absolute;
  display:block;
  ...
}

As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.

I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.

Getting indices of True values in a boolean list

Use enumerate, list.index returns the index of first match found.

>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]

For huge lists, it'd be better to use itertools.compress:

>>> from itertools import compress
>>> list(compress(xrange(len(t)), t))
[4, 5, 7]
>>> t = t*1000
>>> %timeit [i for i, x in enumerate(t) if x]
100 loops, best of 3: 2.55 ms per loop
>>> %timeit list(compress(xrange(len(t)), t))
1000 loops, best of 3: 696 µs per loop

What is the best way to calculate a checksum for a file that is on my machine?

On MySQL.com, MD5s are listed alongside each file that you can download. For instance, MySQL "Windows Essentials" 5.1 is 528c89c37b3a6f0bd34480000a56c372.

You can download md5 (md5.exe), a command line tool that will calculate the MD5 of any file that you have locally. MD5 is just like any other cryptographic hash function, which means that a given array of bytes will always produce the same hash. That means if your downloaded MySQL zip file (or whatever) has the same MD5 as they post on their site, you have the exact same file.

Javascript use variable as object name

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

Essentially, it's using a global variable (attached to the function object)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

jQuery Cross Domain Ajax

You just have to parse the string using JSON.parse like this :

var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};

var parsed = JSON.parse(json_result.AuthenticateUserResult);
console.log(parsed);

Here you will have something like this :

Designation
null

FirstName
"Miqdad"

LastName
"Kumar"

PKPersonId
1234

PhotoPath
"/UploadFiles/"

Profile
""

Salutation
null

And for the request, don't forget to set dataType:'jsonp' and to add a file in the root directory of your site called crossdomain.xml and containing :

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->

<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>

<!-- Least restrictive policy: -->
<!--
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
-->
</cross-domain-policy>

EDIT to take care of Sanjay Kumar POST

So you can set the callback function to be called in the JSONP using jsonpCallback!

$.Ajax({
    jsonpCallback : 'your_function_name',
    //OR with anonymous function
    jsonpCallback : function(data) {
        //do stuff
    },
    ...
});

Convert RGB values to Integer

int rgb = new Color(r, g, b).getRGB();

How to use a class from one C# project with another C# project

If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes. While Creating the object for that the requried class. Call the Method which you want.

FirstProject:

class FirstClass()
{
   public string Name()
   {
      return "James";
   }
}

Here add reference to the Second Project

SecondProject:

class SeccondClass
{
    FirstProject.FirstClass obj=new FirstProject.FirstClass();
    obj.Name();
}

CSS: Truncate table cells, but fit as much as possible

I had the same issue, but I needed to display multiple lines (where text-overflow: ellipsis; fails). I solve it using a textarea inside a TD and then style it to behave like a table cell.

    textarea {
        margin: 0;
        padding: 0;
        width: 100%;
        border: none;
        resize: none;

        /* Remove blinking cursor (text caret) */
        color: transparent;
        display: inline-block;
        text-shadow: 0 0 0 black; /* text color is set to transparent so use text shadow to draw the text */
        &:focus {
            outline: none;
        }
    }

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

Computational complexity of Fibonacci Sequence

There's a very nice discussion of this specific problem over at MIT. On page 5, they make the point that, if you assume that an addition takes one computational unit, the time required to compute Fib(N) is very closely related to the result of Fib(N).

As a result, you can skip directly to the very close approximation of the Fibonacci series:

Fib(N) = (1/sqrt(5)) * 1.618^(N+1) (approximately)

and say, therefore, that the worst case performance of the naive algorithm is

O((1/sqrt(5)) * 1.618^(N+1)) = O(1.618^(N+1))

PS: There is a discussion of the closed form expression of the Nth Fibonacci number over at Wikipedia if you'd like more information.

D3.js: How to get the computed width and height for an arbitrary element?

Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:

function computeDimensions(selection) {
  var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGGraphicsElement) { // check if node is svg element
    dimensions = node.getBBox();
  } else { // else is html element
    dimensions = node.getBoundingClientRect();
  }
  console.log(dimensions);
  return dimensions;
}

Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.

_x000D_
_x000D_
var svg = d3.select('svg')
  .attr('width', 50)
  .attr('height', 50);

function computeDimensions(selection) {
    var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGElement) {
    dimensions = node.getBBox();
  } else {
    dimensions = node.getBoundingClientRect();
  }
  console.clear();
  console.log(dimensions);
  return dimensions;
}

var circle = svg
    .append("circle")
    .attr("r", 20)
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("fill", "red")
    .on("click", function() { computeDimensions(circle); });
    
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  background: #ffd;
}

.div {
  display: inline-block;
  background-color: blue;
  margin-right: 30px;
  width: 30px;
  height: 30px;
}
_x000D_
<h3>
  Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

psql: FATAL: Peer authentication failed for user "dev"

When you specify:

psql -U user

it connects via UNIX Socket, which by default uses peer authentication, unless specified in pg_hba.conf otherwise.

You can specify:

host    database             user             127.0.0.1/32       md5
host    database             user             ::1/128            md5

to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database and user.

After changes you have to restart postgres or reload it's configuration. Restart that should work in modern RHEL/Debian based distros:

service postgresql restart

Reload should work in following way:

pg_ctl reload

but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.

Then you can use:

psql -h localhost -U user -d database

to login with that user to specified database over TCP/IP. md5 stands for encrypted password, while you can also specify password for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.

Important note: Definition order in pg_hba.conf matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:

host    all             all             127.0.0.1/32            ident

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Anaconda site-packages

Run this inside python shell:

from distutils.sysconfig import get_python_lib
print(get_python_lib())

React onClick and preventDefault() link refresh/redirect?

just like pure js do preventdefault : in class you should like this create a handler method :

handler(event) {
    event.preventDefault();
    console.log(event);
}

Customizing Bootstrap CSS template

The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :

  1. Clone bootstrap in your root folder : git clone https://github.com/twbs/bootstrap.git
  2. Rename it "bootstrap"
  3. Create a package.json file : https://gist.github.com/jide/8440609
  4. Create a Gruntfile.js : https://gist.github.com/jide/8440502
  5. Create a "less" folder
  6. Copy bootstrap/less/variables.less into the "less" folder
  7. Change the font path : @icon-font-path: "../bootstrap/fonts/";
  8. Create a custom style.less file in the "less" folder which imports bootstrap.less and your custom variables.less file : https://gist.github.com/jide/8440619
  9. Run npm install
  10. Run grunt watch

Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !

EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate

What HTTP status response code should I use if the request is missing a required parameter?

In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.

HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.

Reference: w3.org/Protocols/

So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.

Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.

In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

How to wait for async method to complete?

The following snippet shows a way to ensure the awaited method completes before returning to the caller. HOWEVER, I wouldn't say it's good practice. Please edit my answer with explanations if you think otherwise.

public async Task AnAsyncMethodThatCompletes()
{
    await SomeAsyncMethod();
    DoSomeMoreStuff();
    await Task.Factory.StartNew(() => { }); // <-- This line here, at the end
}

await AnAsyncMethodThatCompletes();
Console.WriteLine("AnAsyncMethodThatCompletes() completed.")

How to remove duplicate values from a multi-dimensional array in PHP

Another way. Will preserve keys as well.

function array_unique_multidimensional($input)
{
    $serialized = array_map('serialize', $input);
    $unique = array_unique($serialized);
    return array_intersect_key($input, $unique);
}

node and Error: EMFILE, too many open files

I did installing watchman, changing limit etc. and it didn't work in Gulp.

Restarting iterm2 actually helped though.

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

Order of execution of tests in TestNG

If I understand your question correctly in that you want to run tests in a specified order, TestNG IMethodInterceptor can be used. Take a look at http://beust.com/weblog2/archives/000479.html on how to leverage them.

If you want run some preinitialization, take a look at IHookable http://testng.org/javadoc/org/testng/IHookable.html and associated thread http://groups.google.com/group/testng-users/browse_thread/thread/42596505990e8484/3923db2f127a9a9c?lnk=gst&q=IHookable#3923db2f127a9a9c

Best practices to test protected methods with PHPUnit

I'm going to throw my hat into the ring here:

I've used the __call hack with mixed degrees of success. The alternative I came up with was to use the Visitor pattern:

1: generate a stdClass or custom class (to enforce type)

2: prime that with the required method and arguments

3: ensure that your SUT has an acceptVisitor method which will execute the method with the arguments specified in the visiting class

4: inject it into the class you wish to test

5: SUT injects the result of operation into the visitor

6: apply your test conditions to the Visitor's result attribute

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

Return Index of an Element in an Array Excel VBA

Is this what you are looking for?

public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer

dim i as integer

 for i=lbound(ialist) to ubound(ialist)
  if iInteger=ialist(i) then
   GetIndex=i
   exit for
  end if
 next i

end function

Descending order by date filter in AngularJs

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
            result.push(val);_x000D_
        });_x000D_
        return result;_x000D_
    };_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
        _x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
  <h4>Descending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
  <br>_x000D_
  _x000D_
  _x000D_
  <h4>Ascending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Filtering Pandas DataFrames on dates

I'm not allowed to write any comments yet, so I'll write an answer, if somebody will read all of them and reach this one.

If the index of the dataset is a datetime and you want to filter that just by (for example) months, you can do following:

df.loc[df.index.month == 3]

That will filter the dataset for you by March.

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

Observable.of is not a function

My silly mistake was that I forgot to add /add when requiring the observable.

Was:

import { Observable } from 'rxjs/Observable';
import 'rxjs/observable/of';

Which visually looks OK becasue rxjs/observable/of file, in fact, exists.

Should be:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

Visual Studio 2015 installer hangs during install?

I had the same problem on a different context. After trying to repair, uninstall, and reinstall with no solution, I decided to wipe out all Visual Studio remnant by using TotalUninstaller by follower the steps by steps on the link below:

https://github.com/Microsoft/VisualStudioUninstaller/releases

Once everything is removed, I was able to successfully install the software.

Be aware that TotalUninstaller will remove everything related to Visual Studio 2013 to 2015. Earlier version will still be preserved.

I added this solution in case someone has the exact same problem.

Accessing MP3 metadata with Python

I used tinytag 1.3.1 because

  1. It is actively supported:
1.3.0 (2020-03-09):
added option to ignore encoding errors ignore_errors #73
Improved text decoding for many malformed files
  1. It supports the major formats:
MP3 (ID3 v1, v1.1, v2.2, v2.3+)
Wave/RIFF
OGG
OPUS
FLAC
WMA
MP4/M4A/M4B
  1. The code WORKED in just a few minutes of development.
from tinytag import TinyTag

fileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3
0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3
1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3
5c706f3c-eea4-4882-887a-4ff71326d284.mp3
'''.split()

for fn in fileNameL:
    fpath = './data/'+fn
    tag = TinyTag.get(fpath)
    print()
    print('"artist": "%s",' % tag.artist)
    print('"album": "%s",' % tag.album)
    print('"title": "%s",' % tag.title)
    print('"duration(secs)": "%s",' % tag.duration)

  • RESULT
JoeTagPj>python joeTagTest.py

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "17. Thomas Middleditch and Ben Schwartz",
"duration(secs)": "3565.1829583532785",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Are you ready to make friends?",
"duration(secs)": "417.71840447045264",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Introducing Conan’s new podcast",
"duration(secs)": "327.22187551899646",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "19. Ray Romano",
"duration(secs)": "3484.1986772305863",

C:\1d\PodcastPjs\JoeTagPj>

How to create radio buttons and checkbox in swift (iOS)?

Checkbox

You can create your own CheckBox control extending UIButton with Swift:

import UIKit

class CheckBox: UIButton {
    // Images
    let checkedImage = UIImage(named: "ic_check_box")! as UIImage
    let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
    
    // Bool property
    var isChecked: Bool = false {
        didSet {
            if isChecked == true {
                self.setImage(checkedImage, for: UIControl.State.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControl.State.normal)
            }
        }
    }
        
    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
        self.isChecked = false
    }
        
    @objc func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}

And then add it to your views with Interface Builder:

enter image description here

Radio Buttons

Radio Buttons can be solved in a similar way.

For example, the classic gender selection Woman - Man:

enter image description here

import UIKit

class RadioButton: UIButton {
    var alternateButton:Array<RadioButton>?
    
    override func awakeFromNib() {
        self.layer.cornerRadius = 5
        self.layer.borderWidth = 2.0
        self.layer.masksToBounds = true
    }
    
    func unselectAlternateButtons() {
        if alternateButton != nil {
            self.isSelected = true
            
            for aButton:RadioButton in alternateButton! {
                aButton.isSelected = false
            }
        } else {
            toggleButton()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        unselectAlternateButtons()
        super.touchesBegan(touches, with: event)
    }
    
    func toggleButton() {
        self.isSelected = !isSelected
    }
    
    override var isSelected: Bool {
        didSet {
            if isSelected {
                self.layer.borderColor = Color.turquoise.cgColor
            } else {
                self.layer.borderColor = Color.grey_99.cgColor
            }
        }
    }
}

You can init your radio buttons like this:

    override func awakeFromNib() {
        self.view.layoutIfNeeded()
        
        womanRadioButton.selected = true
        manRadioButton.selected = false
    }
    
    override func viewDidLoad() {
        womanRadioButton?.alternateButton = [manRadioButton!]
        manRadioButton?.alternateButton = [womanRadioButton!]
    }

Hope it helps.

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

How can I limit possible inputs in a HTML5 "number" element?

<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />

or if you want to be able enter nothing

<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />

How to call a function in shell Scripting?

#!/bin/bash  
# functiontest.sh a sample to call the function in the shell script  

choice="true"  
function process_install  
{  
  commands...
}  

function process_exit  
{
  commands...  
}  

function main  
{  
  if [[ "$choice" == "true" ]]; then  
      process_install
  elif [[ "$choice" == "false" ]]; then  
      process_exit  
  fi  
}  

main "$@"  

it will start from the main function

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

How to print all key and values from HashMap in Android?

you can use this code:

for (Object variableName: mapName.keySet()){
    variableKey += variableName + "\n";
    variableValue += mapName.get(variableName) + "\n";
}
System.out.println(variableKey + variableValue);

this code will make sure that all the keys are stored in a variable and then printed!

Regular expression to extract URL from an HTML link

If you're only looking for one:

import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
    print(match.group(1))

If you have a long string, and want every instance of the pattern in it:

import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))

Where s is the string that you're looking for matches in.

Quick explanation of the regexp bits:

r'...' is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\ especially -- in a raw string a \ is just a \. In a regular string you'd have to do \\ every time, and that gets old in regexps.)

"href=[\'"]?" says to match "href=", possibly followed by a ' or ". "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.

Enclosing the next bit in "()" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in."

"[^\'" >]+" says to match any characters that aren't ', ", >, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.

The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.

It's pretty easy to do:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
    print(tag['href'])

Once you've installed BeautifulSoup, anyway.

Convert Pixels to Points

Height lines converted into points and pixel (my own formula). Here is an example with a manual entry of 213.67 points in the Row Height field:

213.67  Manual Entry    
  0.45  Add 0.45    
214.12  Subtotal    
213.75  Round to a multiple of 0.75 
213.00  Subtract 0.75 provides manual entry converted by Excel  
284.00  Divide by 0.75 gives the number of pixels of height

Here the manual entry of 213.67 points gives 284 pixels.
Here the manual entry of 213.68 points gives 285 pixels.

(Why 0.45? I do not know but it works.)