Programs & Examples On #Netui

Floating Div Over An Image

you might consider using the Relative and Absolute positining.

`.container {  
position: relative;  
}  
.tag {     
position: absolute;   
}`  

I have tested it there, also if you want it to change its position use this as its margin:

top: 20px;
left: 10px;

It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

What is the difference between #include <filename> and #include "filename"?

the " < filename > " searches in standard C library locations

whereas "filename" searches in the current directory as well.

Ideally, you would use <...> for standard C libraries and "..." for libraries that you write and are present in the current directory.

Can I grep only the first n lines of a file?

head -10 log.txt | grep -A 2 -B 2 pattern_to_search

-A 2: print two lines before the pattern.

-B 2: print two lines after the pattern.

head -10 log.txt # read the first 10 lines of the file.

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

How to restart adb from root to user mode?

This is a very common issue.

One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.

Just go to Window Task Manager to kill adb process and restart Eclipse.

Will work perfect :)

What is this date format? 2011-08-12T20:17:46.384Z

The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:

SimpleDateFormat format = new SimpleDateFormat(
    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Or using Joda Time, you can use ISODateTimeFormat.dateTime().

PHP Checking if the current date is before or after a set date

if(strtotime($db_date) > time()) {
  echo $db_date;
} else {
  echo 'go ahead';
}

How to select all records from one table that do not exist in another table?

Here's what worked best for me.

SELECT *
FROM @T1
EXCEPT
SELECT a.*
FROM @T1 a
JOIN @T2 b ON a.ID = b.ID

This was more than twice as fast as any other method I tried.

Setting default value in select drop-down using Angularjs

You can do it with following code(track by),

<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>

How to print the values of slices

For a []string, you can use strings.Join():

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

How can I find the current OS in Python?

Something along the lines:

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

How to get first and last day of previous month (with timestamp) in SQL Server

You can get first and last day of previous month (with timestamp) in SQL Server by executing

--select dateadd(dd,-datepart(dd,getdate())+1,dateadd(mm,-1,getdate())) --first day of previous month 
--select dateadd(dd,-datepart(dd,getdate()),getdate()) -- last day of previous month**

How to commit to remote git repository

git push

or

git push server_name master

should do the trick, after you have made a commit to your local repository.

What does the C++ standard state the size of int, long type to be?

As mentioned the size should reflect the current architecture. You could take a peak around in limits.h if you want to see how your current compiler is handling things.

Converting float to char*

typedef union{
    float a;
    char b[4];
} my_union_t;

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai

jQuery-- Populate select from json

$(JSON.parse(response)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');

Can't find @Nullable inside javax.annotation.*

In the case of Android projects, you can fix this error by changing the project/module gradle file (build.gradle) as follows:

dependencies { implementation 'com.android.support:support-annotations:24.2.0' }

For more informations, please refer here.

FormData.append("key", "value") is not working

you can see it you need to use console.log(formData.getAll('your key')); watch the https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

When to use React "componentDidUpdate" method?

Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.

How to find substring inside a string (or how to grep a variable)?

LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
  echo "matched";
else
  echo "no match";
fi

How to change the colors of a PNG image easily?

Photoshop - right click layer -> blending options -> color overlay change color and save

How do I get a file extension in PHP?

I found that the pathinfo() and SplFileInfo solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a # (fragment identifiers) and/or ? (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.

I found this was a reliable way to use pathinfo() on a URL after first parsing it to strip out the unnecessary clutter after the file extension:

$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()

vi/vim editor, copy a block (not usual action)

Keyboard shortcuts to that are:

  1. For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p

  2. For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p

If two cells match, return value from third

All you have to do is write an IF condition in the column d like this:

=IF(A1=C1;B1;" ")

After that just apply this formula to all rows above that one.

assigning column names to a pandas series

If you have a pd.Series object x with index named 'Gene', you can use reset_index and supply the name argument:

df = x.reset_index(name='count')

Here's a demo:

x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'

df = x.reset_index(name='count')

print(df)

   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

Reading specific XML elements from XML file

This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties

    class Word
    {
        public string Base { get; set; }
        public string Category { get; set; }
        public string Id { get; set; }
    }

load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .

    XDocument doc = XDocument.Parse(INPUT_DATA);
    XElement lex = doc.Element("lexicon");

make sure there is a value and use linq to extract the word elements from it . . .

    Word[] catWords = null;
    if (lex != null)
    {
        IEnumerable<XElement> words = lex.Elements("word");
        catWords = (from itm in words
                    where itm.Element("category") != null
                        && itm.Element("category").Value == "verb"
                        && itm.Element("id") != null
                        && itm.Element("base") != null
                    select new Word() 
                    {
                        Base = itm.Element("base").Value,
                        Category = itm.Element("category").Value,
                        Id = itm.Element("id").Value,
                    }).ToArray<Word>();
    }

The where statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .

The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.

Then print it to get . . .

[Found]
 Id: E0006429
 Base: abandon
 Category: verb

[Found]
 Id: E0006524
 Base: abolish
 Category: verb

Full Source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test
{
    class Program
    {

        class Word
        {
            public string Base { get; set; }
            public string Category { get; set; }
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(INPUT_DATA);
            XElement lex = doc.Element("lexicon");
            Word[] catWords = null;
            if (lex != null)
            {
                IEnumerable<XElement> words = lex.Elements("word");
                catWords = (from itm in words
                            where itm.Element("category") != null
                                && itm.Element("category").Value == "verb"
                                && itm.Element("id") != null
                                && itm.Element("base") != null
                            select new Word() 
                            {
                                Base = itm.Element("base").Value,
                                Category = itm.Element("category").Value,
                                Id = itm.Element("id").Value,
                            }).ToArray<Word>();
            }

            //print it
            if (catWords != null)
            {
                Console.WriteLine("Words with <category> and value verb:\n");
                foreach (Word itm in catWords)
                    Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n", 
                        itm.Id, itm.Base, itm.Category);
            }
        }

        const string INPUT_DATA =
        @"<?xml version=""1.0""?>
        <lexicon>
        <word>
          <base>a</base>
          <category>determiner</category>
          <id>E0006419</id>
        </word>
        <word>
          <base>abandon</base>
          <category>verb</category>
          <id>E0006429</id>
          <ditransitive/>
          <transitive/>
        </word>
        <word>
          <base>abbey</base>
          <category>noun</category>
          <id>E0203496</id>
        </word>
        <word>
          <base>ability</base>
          <category>noun</category>
          <id>E0006490</id>
        </word>
        <word>
          <base>able</base>
          <category>adjective</category>
          <id>E0006510</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abnormal</base>
          <category>adjective</category>
          <id>E0006517</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abolish</base>
          <category>verb</category>
          <id>E0006524</id>
          <transitive/>
        </word>
        </lexicon>";

    }
}

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

Android translate animation - permanently move View to new position using AnimationListener

You can try this way -

ObjectAnimator.ofFloat(view, "translationX", 100f).apply {
    duration = 2000
    start()
}

Note - view is your view where you want animation.

Java division by zero doesnt throw an ArithmeticException - why?

There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.

If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.

Hex to ascii string conversion

Few characters like alphabets i-o couldn't be converted into respective ASCII chars . like in string '6631653064316f30723161' corresponds to fedora . but it gives fedra

Just modify hex_to_int() function a little and it will work for all characters. modified function is

int hex_to_int(char c)
{
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;
}

Now try it will work for all characters.

How to represent empty char in Java Character class

An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.

You say you want to "replace a character without leaving a space".

If you are dealing with a char[], then you would create a new char[] with that element removed.

If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.

Here are some samples of how you could remove a char:

public static void main(String[] args) throws Exception {

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}

What's the right way to pass form element state to sibling/parent elements?

  1. The right thing to do is to have the state in the parent component, to avoid ref and what not
  2. An issue is to avoid constantly updating all children when typing into a field
  3. Therefore, each child should be a Component (as in not a PureComponent) and implement shouldComponentUpdate(nextProps, nextState)
  4. This way, when typing into a form field, only that field updates

The code below uses @bound annotations from ES.Next babel-plugin-transform-decorators-legacy of BabelJS 6 and class-properties (the annotation sets this value on member functions similar to bind):

/*
© 2017-present Harald Rudell <[email protected]> (http://www.haraldrudell.com)
All rights reserved.
*/
import React, {Component} from 'react'
import {bound} from 'class-bind'

const m = 'Form'

export default class Parent extends Component {
  state = {one: 'One', two: 'Two'}

  @bound submit(e) {
    e.preventDefault()
    const values = {...this.state}
    console.log(`${m}.submit:`, values)
  }

  @bound fieldUpdate({name, value}) {
    this.setState({[name]: value})
  }

  render() {
    console.log(`${m}.render`)
    const {state, fieldUpdate, submit} = this
    const p = {fieldUpdate}
    return (
      <form onSubmit={submit}> {/* loop removed for clarity */}
        <Child name='one' value={state.one} {...p} />
        <Child name='two' value={state.two} {...p} />
        <input type="submit" />
      </form>
    )
  }
}

class Child extends Component {
  value = this.props.value

  @bound update(e) {
    const {value} = e.target
    const {name, fieldUpdate} = this.props
    fieldUpdate({name, value})
  }

  shouldComponentUpdate(nextProps) {
    const {value} = nextProps
    const doRender = value !== this.value
    if (doRender) this.value = value
    return doRender
  }

  render() {
    console.log(`Child${this.props.name}.render`)
    const {value} = this.props
    const p = {value}
    return <input {...p} onChange={this.update} />
  }
}

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Typing Greek letters etc. in Python plots

Python 3.x: small greek letters are coded from 945 to 969 so,alpha is chr(945), omega is chr(969) so just type

print(chr(945))

the list of small greek letters in a list:

greek_letterz=[chr(code) for code in range(945,970)]

print(greek_letterz)

And now, alpha is greek_letterz[0], beta is greek_letterz[1], a.s.o

RegEx to match stuff between parentheses

Use this expression:

/\(([^()]+)\)/g

e.g:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}

Is there an easy way to reload css without reloading the page?

On the "edit" page, instead of including your CSS in the normal way (with a <link> tag), write it all to a <style> tag. Editing the innerHTML property of that will automatically update the page, even without a round-trip to the server.

<style type="text/css" id="styles">
    p {
        color: #f0f;
    }
</style>

<textarea id="editor"></textarea>
<button id="preview">Preview</button>

The Javascript, using jQuery:

jQuery(function($) {
    var $ed = $('#editor')
      , $style = $('#styles')
      , $button = $('#preview')
    ;
    $ed.val($style.html());
    $button.click(function() {
        $style.html($ed.val());
        return false;
    });
});

And that should be it!

If you wanted to be really fancy, attach the function to the keydown on the textarea, though you could get some unwanted side-effects (the page would be changing constantly as you type)

Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: http://jsbin.com/owapi

How do I change the figure size for a seaborn plot?

The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.

Size changes both the height and width, maintaining the aspect ratio.

Aspect only changes the width, keeping the height constant.

You can always get your desired size by playing with these two parameters.

Credit: https://stackoverflow.com/a/28765059/3901029

Best way to track onchange as-you-type in input type="text"?

"input" worked for me.

var searchBar  = document.getElementById("searchBar");
searchBar.addEventListener("input", PredictSearch, false);

Client to send SOAP request and receive response

I wrote a more general helper class which accepts a string-based dictionary of custom parameters, so that they can be set by the caller without having to hard-code them. It goes without saying that you should only use such method when you want (or need) to manually issue a SOAP-based web service: in most common scenarios the recommended approach would be using the Web Service WSDL together with the Add Service Reference Visual Studio feature instead.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;

namespace Ryadel.Web.SOAP
{
    /// <summary>
    /// Helper class to send custom SOAP requests.
    /// </summary>
    public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        {
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var xmlStr = (useSOAP12)
                ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                      xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                      xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                      <soap12:Body>
                        <{0} xmlns=""{1}"">{2}</{0}>
                      </soap12:Body>
                    </soap12:Envelope>"
                : @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <soap:Body>
                           <{0} xmlns=""{1}"">{2}</{0}>
                        </soap:Body>
                    </soap:Envelope>";
            string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
            soapEnvelopeXml.LoadXml(s);

            // Create the web request
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction ?? url);
            webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
            webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
            webRequest.Method = "POST";

            // Insert SOAP envelope
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            // Send request and retrieve result
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
    }
}

For additional info & details regarding this class you can also read this post on my blog.

How can I initialise a static Map?

There are some good answers here, but I do want to offer one more.

Create your own static method to create and initialize a Map. I have my own CollectionUtils class in a package that I use across projects with various utilities that I use regularly that are easy for me to write and avoids the need for a dependency on some larger library.

Here's my newMap method:

public class CollectionUtils {
    public static Map newMap(Object... keyValuePairs) {
        Map map = new HashMap();
        if ( keyValuePairs.length % 2 == 1 ) throw new IllegalArgumentException("Must have even number of arguments");
        for ( int i=0; i<keyValuePairs.length; i+=2 ) {
            map.put(keyValuePairs[i], keyValuePairs[i + 1]);
        }
        return map;
    }
}

Usage:

import static CollectionUtils.newMap;
// ...
Map aMap = newMap("key1", 1.23, "key2", 2.34);
Map bMap = newMap(objKey1, objVal1, objKey2, objVal2, objKey3, objVal3);
// etc...

It doesn't make use of generics, but you can typecast the map as you wish (just be sure you typecast it correctly!)

Map<String,Double> aMap = (Map<String,Double>)newMap("key1", 1.23, "key2", 2.34);

Maven: best way of linking custom external JAR to my project?

The Maven manual says to do this:

mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar

SQL: Alias Column Name for Use in CASE Statement

I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

With localView1 as (
 select c1,
        c2,
        c3,
        c4,
        ((c2-c4)*(3))+c1 as "complex"
   from realTable1) 
   , localView2 as (
 select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
        complex * complex as formula2    
   from localView1)
select *
from localView2

Error: Uncaught SyntaxError: Unexpected token <

Typically this happens when you are trying to load a non-html resource (e.g the jquery library script file as type text/javascript) and the server, instead of returning the expected JS resource, returns HTML instead - typically a 404 page.

The browser then attempts to parse the resource as JS, but since what was actually returned was an HTML page, the parsing fails with a syntax error, and since an HTML page will typically start with a < character, this is the character that is highlighted in the syntax error exception.

Display calendar to pick a date in java

The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.

Fair disclosure: I'm the primary developer.

Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.

The most commonly used date formats are automatically supported, and additional date formats can be added if desired.

To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.

Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.

The library can be installed into your Java project from the project release page.

The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .


DateTimePicker screenshot


DateTimePicker examples


Demo screenshot

How to sort a list of lists by a specific index of the inner list?

More easy to understand (What is Lambda actually doing):

ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
    #return the third item of the list
    return ls[2]
#Sort according to what the thirdItem function return 
ls2.sort(key=thirdItem)

How to compare dates in Java?

Use getTime() to get the numeric value of the date, and then compare using the returned values.

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

How to import image (.svg, .png ) in a React Component

If the images are inside the src/assets folder you can use require with the correct path in the require statement,

var Diamond = require('../../assets/linux_logo.jpg');

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

(HTML) Download a PDF file instead of opening them in browser when clicked

The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

Generate insert script for selected records?

I created the following procedure:

if object_id('tool.create_insert', 'P') is null
begin
  exec('create procedure tool.create_insert as');
end;
go

alter procedure tool.create_insert(@schema    varchar(200) = 'dbo',
                                   @table     varchar(200),
                                   @where     varchar(max) = null,
                                   @top       int = null,
                                   @insert    varchar(max) output)
as
begin
  declare @insert_fields varchar(max),
          @select        varchar(max),
          @error         varchar(500),
          @query         varchar(max);

  declare @values table(description varchar(max));

  set nocount on;

  -- Get columns
  select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
         @select = case type_name(c.system_type_id)
                      when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
                      when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
                      else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
                    end
    from sys.columns c with(nolock)
         inner join sys.tables t with(nolock) on t.object_id = c.object_id
         inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
   where s.name = @schema
     and t.name = @table;

  -- If there's no columns...
  if @insert_fields is null or @select is null
  begin
    set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
    raiserror(@error, 16, 1);
    return;
  end;

  set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';

  if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
  begin
    set @where = 'where ' + @where;
  end
  else
  begin
    set @where = '';
  end;

  set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;

  insert into @values(description)
  exec(@query);

  set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);

  select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
    from @values v
   where isnull(v.description, '') <> '';
end;
go

Then you can use it that way:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'myTable',
                        @where  = 'Fk_CompanyId = 1',
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

The output would be something like that:

--DBO.MYTABLE
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(1, 'AMX', 1, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(2, 'ABC', 1, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(3, 'APEX', 1, 12.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(4, 'AMX', 1, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(5, 'ABC', 1, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(6, 'APEX', 1, 12.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(7, 'AMX', 2, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(8, 'ABC', 2, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(9, 'APEX', 2, 12.00);
go

If you just want to get a range of rows, use the @top parameter as bellow:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'myTable',
                        @top    = 100,
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Angular : Manual redirect to route

You should inject Router in your constructor like this;

constructor(private router: Router) { }

then you can do this anywhere you want;

this.router.navigate(['/product-list']);

jQuery-UI datepicker default date

If you want to update the highlighted day to a different day based on some server time, you can override the Date Picker code to allow for a new custom option named localToday or whatever you'd like to name it.

A small tweak to the selected answer in jQuery UI DatePicker change highlighted "today" date

// Get users 'today' date
var localToday = new Date();
localToday.setDate(tomorrow.getDate()+1); // tomorrow

// Pass the today date to datepicker
$( "#datepicker" ).datepicker({
    showButtonPanel: true,
    localToday: localToday    // This option determines the highlighted today date
});

I've overridden 2 datepicker methods to conditionally use a new setting for the "today" date instead of a new Date(). The new setting is called localToday.

Override $.datepicker._gotoToday and $.datepicker._generateHTML like this:

$.datepicker._gotoToday = function(id) {
    /* ... */
    var date = inst.settings.localToday || new Date()
    /* ... */
}

$.datepicker._generateHTML = function(inst) {
    /* ... */
    tempDate = inst.settings.localToday || new Date()
    /* ... */
}

Here's a demo which shows the full code and usage: http://jsfiddle.net/NAzz7/5/

What is the difference between `let` and `var` in swift?

var value can be change, after initialize. But let value is not be change, when it is intilize once.

In case of var

  function variable() {
     var number = 5, number = 6;
     console.log(number); // return console value is 6
   }
   variable();

In case of let

   function abc() {
      let number = 5, number = 6;
      console.log(number); // TypeError: redeclaration of let number
   }
   abc();

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

How do I UPDATE from a SELECT in SQL Server?

The below solution works for a MySQL database:

UPDATE table1 a , table2 b 
SET a.columname = 'some value' 
WHERE b.columnname IS NULL ;

React: Expected an assignment or function call and instead saw an expression

Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.

// eslint-disable-next-line @typescript-eslint/no-unused-expressions

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Closing a Userform with Unload Me doesn't work

Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.

Make sure that you don't have the "me" in brackets.

Also if you can post the full code for the userform it would help massively.

Decoding JSON String in Java

Well your jsonString is wrong.

String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";

use this jsonString and if you use the same JSONParser and ContainerFactory in the example you will see that it will be encoded/decoded.

Additionally if you want to print your string after stat here it goes:

     try{
        Map json = (Map)parser.parse(jsonString, containerFactory);
        Iterator iter = json.entrySet().iterator();
        System.out.println("==iterate result==");
        Object entry = json.get("stat");
        System.out.println(entry);
      }

And about the json libraries, there are a lot of them. Better you check this.

HTML checkbox onclick called in Javascript

How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 

function toggleCheckbox(element)
 {
   element.checked = !element.checked;
 }

This will additionally catch users using a keyboard to toggle the check box, something onclick would not.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

clear data inside text file in c++

If you simply open the file for writing with the truncate-option, you'll delete the content.

std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();

http://www.cplusplus.com/reference/fstream/ofstream/open/

Printing with sed or awk a line following a matching pattern

If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.

sed '/pattern/ { N; s/.*\n//; q }; d'

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

Make anchor link go some pixels above where it's linked to

The easiest solution:

CSS

#link {
    top:-120px; /* -(some pixels above) */
    position:relative;
    z-index:5;
}

HTML

<body>
    <a href="#link">Link</a>
    <div>
        <div id="link"></div> /*this div should placed inside a target div in the page*/
        text
        text
        text
    <div>
</body>

Output single character in C

char variable = 'x';  // the variable is a char whose value is lowercase x

printf("<%c>", variable); // print it with angle brackets around the character

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

In-place type conversion of a NumPy array

Use this:

In [105]: a
Out[105]: 
array([[15, 30, 88, 31, 33],
       [53, 38, 54, 47, 56],
       [67,  2, 74, 10, 16],
       [86, 33, 15, 51, 32],
       [32, 47, 76, 15, 81]], dtype=int32)

In [106]: float32(a)
Out[106]: 
array([[ 15.,  30.,  88.,  31.,  33.],
       [ 53.,  38.,  54.,  47.,  56.],
       [ 67.,   2.,  74.,  10.,  16.],
       [ 86.,  33.,  15.,  51.,  32.],
       [ 32.,  47.,  76.,  15.,  81.]], dtype=float32)

How do I generate a random int number?

Random rand = new Random();
int name = rand.Next()

Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

apt-get for Cygwin?

Update: you can read the more complex answer, which contains more methods and information.

There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).


apt-cyg

The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.


Cygwin’s setup.exe

It has also command line mode. Moreover it allows you to upgrade all installed packages at once.

setup.exe-x86_64.exe -q --packages=bash,vim

Example use:

setup.exe-x86_64.exe -q --packages="bash,vim"

You can create an alias for easier use, for example:

alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"

Then you can for example install the Vim package with:

cyg-get vim

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

How to: Install Plugin in Android Studio

As far as installing a custom plugin there is a good walkthrough on GitHub for the rest2mobile library that could be used for any plugin.

Basically the steps are as follows:

  1. Run Android Studio.
  2. From the menu bar, select Android Studio > Preferences.
  3. Under IDE Settings, click Plugins and then click Install plugin from disk.
  4. Navigate to the folder where you downloaded the plugin and double-click it.
  5. Restart Android Studio.

Java word count program

you should make your code more generic by considering other word separators as well.. such as "," ";" etc.

public class WordCounter{
    public int count(String input){
        int count =0;
        boolean incrementCounter = false;
        for (int i=0; i<input.length(); i++){
            if (isValidWordCharacter(input.charAt(i))){
                incrementCounter = true;
            }else if (incrementCounter){
                count++;
                incrementCounter = false;
            }
        }
        if (incrementCounter) count ++;//if string ends with a valid word
        return count;
    }
    private boolean isValidWordCharacter(char c){
        //any logic that will help you identify a valid character in a word
        // you could also have a method which identifies word separators instead of this
        return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z'); 
    }
}

How do I do top 1 in Oracle?

You could use ROW_NUMBER() with a ORDER BY clause in sub-query and use this column in replacement of TOP N. This can be explained step-by-step.

See the below table which have two columns NAME and DT_CREATED.

enter image description here

If you need to take only the first two dates irrespective of NAME, you could use the below query. The logic has been written inside query

-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
    -- Generates numbers in a column in sequence in the order of date
    SELECT ROW_NUMBER() OVER (ORDER BY DT_CREATED) AS RNO,
    NAME,DT_CREATED
    FROM DEMOTOP
)TAB
WHERE RNO<3;

RESULT

enter image description here

In some situations, we need to select TOP N results respective to each NAME. In such case we can use PARTITION BY with an ORDER BY clause in sub-query. Refer the below query.

-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
  --Generates numbers in a column in sequence in the order of date for each NAME
    SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY DT_CREATED) AS RNO,
    NAME,DT_CREATED
    FROM DEMOTOP
)TAB
WHERE RNO<3;

RESULT

enter image description here

How to programmatically set the SSLContext of a JAX-WS client?

I had problems trusting a self signed certificate when setting up the trust manager. I used the SSLContexts builder of the apache httpclient to create a custom SSLSocketFactory

SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStoreFile, "keystorePassword.toCharArray(), keyPassword.toCharArray())
        .loadTrustMaterial(trustStoreFile, "password".toCharArray(), new TrustSelfSignedStrategy())
        .build();
SSLSocketFactory customSslFactory = sslcontext.getSocketFactory()
bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, customSslFactory);

and passing in the new TrustSelfSignedStrategy() as an argument in the loadTrustMaterial method.

git am error: "patch does not apply"

I faced same error. I reverted the commit version while creating patch. it worked as earlier patch was in reverse way.

[mrdubey@SNF]$ git log 65f1d63 commit 65f1d6396315853f2b7070e0e6d99b116ba2b018 Author: Dubey Mritunjaykumar

Date: Tue Jan 22 12:10:50 2019 +0530

commit e377ab50081e3a8515a75a3f757d7c5c98a975c6 Author: Dubey Mritunjaykumar Date: Mon Jan 21 23:05:48 2019 +0530

Earlier commad used: git diff new_commit_id..prev_commit_id > 1 diff

Got error: patch failed: filename:40

working one: git diff prev_commit_id..latest_commit_id > 1.diff

Assign an initial value to radio button as checked

If you are using react-redux for your application and if you want to show data which is in the redux store, you can set "checked" option as below.

<label>Male</label>

 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "0"}
 />



 <label>Female</label>
 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "1"}
 />

How to print GETDATE() in SQL Server with milliseconds in time?

Try Following

DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime

call javascript function onchange event of dropdown list

using jQuery

 $("#ddl").change(function () {
                alert($(this).val());
            });

jsFiddle

Reading a file line by line in Go

In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner. Here is a simple example that reads lines from a file:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

This is the cleanest way to read from a Reader line by line.

There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read().

How to add a progress bar to a shell script?

I have built on the answer provided by fearside

This connects to an Oracle database to retrieve the progress of an RMAN restore.

#!/bin/bash

 # 1. Create ProgressBar function
 # 1.1 Input is currentState($1) and totalState($2)
 function ProgressBar {
 # Process data
let _progress=(${1}*100/${2}*100)/100
let _done=(${_progress}*4)/10
let _left=40-$_done
# Build progressbar string lengths
_fill=$(printf "%${_done}s")
_empty=$(printf "%${_left}s")

# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:
# 1.2.1.1 Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"

}

function rman_check {
sqlplus -s / as sysdba <<EOF
set heading off
set feedback off
select
round((sofar/totalwork) * 100,0) pct_done
from
v\$session_longops
where
totalwork > sofar
AND
opname NOT LIKE '%aggregate%'
AND
opname like 'RMAN%';
exit
EOF
}

# Variables
_start=1

# This accounts as the "totalState" variable for the ProgressBar function
_end=100

_rman_progress=$(rman_check)
#echo ${_rman_progress}

# Proof of concept
#for number in $(seq ${_start} ${_end})

while [ ${_rman_progress} -lt 100 ]
do

for number in _rman_progress
do
sleep 10
ProgressBar ${number} ${_end}
done

_rman_progress=$(rman_check)

done
printf '\nFinished!\n'

Delete item from array and shrink array

I have created this function, or class. Im kinda new but my friend needed this also so I created this:

public String[] name(int index, String[] z ){
    if(index > z.length){
        return z;
    } else {
        String[] returnThis = new String[z.length - 1];
        int newIndex = 0;
        for(int i = 0; i < z.length; i++){
            if(i != index){
                returnThis[newIndex] = z[i];
                newIndex++;
            }
        }
        return returnThis; 
    }
}

Since its pretty revelant, I thought I would post it here.

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

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.

How to change the status bar color in Android?

One more solution:

final View decorView = w.getDecorView();
View view = new View(BaseControllerActivity.this);
final int statusBarHeight = UiUtil.getStatusBarHeight(ContextHolder.get());
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight));
view.setBackgroundColor(colorValue);
((ViewGroup)decorView).addView(view);

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.

How can I create download link in HTML?

There's one more subtlety that can help here.

I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn't work all the time because the browser's compulsion to play the or display the file is still very strong.

BUT.. this is based on examining the extension on the URL's filename!You don't want to fiddle with the server's extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download's rename feature to fix the name.

_x000D_
_x000D_
<a target="_blank" download="realname.mp3" href="realname.UNKNOWN">Download it</a>_x000D_
<a target="_blank" href="realname.mp3">Play it</a>
_x000D_
_x000D_
_x000D_

I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn't.

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

You are passing a target array of shape (x-dim, y-dim) while using as loss categorical_crossentropy. categorical_crossentropy expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

from keras.utils import to_categorical
y_binary = to_categorical(y_int)

Alternatively, you can use the loss function sparse_categorical_crossentropy instead, which does expect integer targets.

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

Remove by _id in MongoDB console

If you would like to remove by a list of IDs this works great.

db.CollectionName.remove({
    "_id": {
        $in: [
            ObjectId("0930292929292929292929"),
            ObjectId("0920292929292929292929")
        ]
     }
}) 

annotation to make a private method public only for test classes

You can't do this, since then how could you even compile your tests? The compiler won't take the annotation into account.

There are two general approaches to this

The first is to use reflection to access the methods anyway

The second is to use package-private instead of private, then have your tests in the same package (but in a different module). They will essentially be private to other code, but your tests will still be able to access them.

Of course, if you do black-box testing, you shouldn't be accessing the private members anyway.

Java Object Null Check for method

If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value:

public static double calculateInventoryTotal(Book[] books)
{
if(books == null) return 0;
    double total = 0;
    for (int i = 0; i < books.length; i++)
    {
        total += books[i].getPrice();
    }
    return total;
}

It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).

convert ArrayList<MyCustomClass> to JSONArray

With kotlin and Gson we can do it more easily:

  1. First, add Gson dependency:

implementation "com.squareup.retrofit2:converter-gson:2.3.0"

  1. Create a separate kotlin file, add the following methods
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun <T> Gson.convertToJsonString(t: T): String {
    return toJson(t).toString()
}

fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
    return try {
        fromJson(jsonString, cls)
    } catch (e: Exception) {
        null
    }
}

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)

Note: Do not add declare class, just add these methods, everything will work fine.

  1. Now to call:

create a reference of gson:

val gson=Gson()

To convert array to json string, call:

val jsonString=gson.convertToJsonString(arrayList)

To get array from json string, call:

val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)

To convert a model to json string, call:

val jsonString=gson.convertToJsonString(model)

To convert json string to model, call:

val model=gson.convertToModel(jsonString, YourModelClassName::class.java)

What is a "static" function in C?

static functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).

EDIT: For those who thought, that the author of the questions meant a 'class method': As the question is tagged C he means a plain old C function. For (C++/Java/...) class methods, static means that this method can be called on the class itself, no instance of that class necessary.

How to compare two List<String> to each other?

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

if (a1.SequenceEqual(a2))

See it working online: ideone

How to include a class in PHP

  1. require('/yourpath/yourphp.php');

    http://php.net/manual/en/function.require.php

  2. require_once('/yourpath/yourphp.php');

    http://php.net/manual/en/function.require-once.php

  3. include '/yourpath/yourphp.php';

    http://www.php.net/manual/en/function.include.php

  4. use \Yourapp\Yourname

    http://php.net/manual/fa/language.namespaces.importing.php

Notes:

Avoid using require_once because it is slow: Why is require_once so bad to use?

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

What does ENABLE_BITCODE do in xcode 7?

Since the exact question is "what does enable bitcode do", I'd like to give a few thin technical details I've figured out thus far. Most of this is practically impossible to figure out with 100% certainty until Apple releases the source code for this compiler

First, Apple's bitcode does not appear to be the same thing as LLVM bytecode. At least, I've not been able to figure out any resemblance between them. It appears to have a proprietary header (always starts with "xar!") and probably some link-time reference magic that prevents data duplications. If you write out a hardcoded string, this string will only be put into the data once, rather than twice as would be expected if it was normal LLVM bytecode.

Second, bitcode is not really shipped in the binary archive as a separate architecture as might be expected. It is not shipped in the same way as say x86 and ARM are put into one binary (FAT archive). Instead, they use a special section in the architecture specific MachO binary named "__LLVM" which is shipped with every architecture supported (ie, duplicated). I assume this is a short coming with their compiler system and may be fixed in the future to avoid the duplication.

C code (compiled with clang -fembed-bitcode hi.c -S -emit-llvm):

#include <stdio.h>

int main() {
    printf("hi there!");
    return 0;
}

LLVM IR output:

; ModuleID = '/var/folders/rd/sv6v2_f50nzbrn4f64gnd4gh0000gq/T/hi-a8c16c.bc'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"

@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
@llvm.embedded.module = appending constant [1600 x i8] c"\DE\C0\17\0B\00\00\00\00\14\00\00\00$\06\00\00\07\00\00\01BC\C0\DE!\0C\00\00\86\01\00\00\0B\82 \00\02\00\00\00\12\00\00\00\07\81#\91A\C8\04I\06\1029\92\01\84\0C%\05\08\19\1E\04\8Bb\80\10E\02B\92\0BB\84\102\148\08\18I\0A2D$H\0A\90!#\C4R\80\0C\19!r$\07\C8\08\11b\A8\A0\A8@\C6\F0\01\00\00\00Q\18\00\00\C7\00\00\00\1Bp$\F8\FF\FF\FF\FF\01\90\00\0D\08\03\82\1D\CAa\1E\E6\A1\0D\E0A\1E\CAa\1C\D2a\1E\CA\A1\0D\CC\01\1E\DA!\1C\C8\010\87p`\87y(\07\80p\87wh\03s\90\87ph\87rh\03xx\87tp\07z(\07yh\83r`\87th\07\80\1E\E4\A1\1E\CA\01\18\DC\E1\1D\DA\C0\1C\E4!\1C\DA\A1\1C\DA\00\1E\DE!\1D\DC\81\1E\CAA\1E\DA\A0\1C\D8!\1D\DA\A1\0D\DC\E1\1D\DC\A1\0D\D8\A1\1C\C2\C1\1C\00\C2\1D\DE\A1\0D\D2\C1\1D\CCa\1E\DA\C0\1C\E0\A1\0D\DA!\1C\E8\01\1D\00s\08\07v\98\87r\00\08wx\876p\87pp\87yh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \E6\81\1E\C2a\1C\D6\A1\0D\E0A\1E\DE\81\1E\CAa\1C\E8\E1\1D\E4\A1\0D\C4\A1\1E\CC\C1\1C\CAA\1E\DA`\1E\D2A\1F\CA\01\C0\03\80\A0\87p\90\87s(\07zh\83q\80\87z\00\C6\E1\1D\E4\A1\1C\E4\00 \E8!\1C\E4\E1\1C\CA\81\1E\DA\C0\1C\CA!\1C\E8\A1\1E\E4\A1\1C\E6\01X\83y\98\87y(\879`\835\18\07|\88\03;`\835\98\87y(\076X\83y\98\87r\90\036X\83y\98\87r\98\03\80\A8\07w\98\87p0\87rh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \EAa\1E\CA\A1\0D\E6\E1\1D\CC\81\1E\DA\C0\1C\D8\E1\1D\C2\81\1E\00s\08\07v\98\87r\006\C8\88\F0\FF\FF\FF\FF\03\C1\0E\E50\0F\F3\D0\06\F0 \0F\E50\0E\E90\0F\E5\D0\06\E6\00\0F\ED\10\0E\E4\00\98C8\B0\C3<\94\03@\B8\C3;\B4\819\C8C8\B4C9\B4\01<\BCC:\B8\03=\94\83<\B4A9\B0C:\B4\03@\0F\F2P\0F\E5\00\0C\EE\F0\0Em`\0E\F2\10\0E\EDP\0Em\00\0F\EF\90\0E\EE@\0F\E5 \0FmP\0E\EC\90\0E\ED\D0\06\EE\F0\0E\EE\D0\06\ECP\0E\E1`\0E\00\E1\0E\EF\D0\06\E9\E0\0E\E60\0Fm`\0E\F0\D0\06\ED\10\0E\F4\80\0E\809\84\03;\CCC9\00\84;\BCC\1B\B8C8\B8\C3<\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F3@\0F\E10\0E\EB\D0\06\F0 \0F\EF@\0F\E50\0E\F4\F0\0E\F2\D0\06\E2P\0F\E6`\0E\E5 \0Fm0\0F\E9\A0\0F\E5\00\E0\01@\D0C8\C8\C39\94\03=\B4\C18\C0C=\00\E3\F0\0E\F2P\0Er\00\10\F4\10\0E\F2p\0E\E5@\0Fm`\0E\E5\10\0E\F4P\0F\F2P\0E\F3\00\AC\C1<\CC\C3<\94\C3\1C\B0\C1\1A\8C\03>\C4\81\1D\B0\C1\1A\CC\C3<\94\03\1B\AC\C1<\CCC9\C8\01\1B\AC\C1<\CCC9\CC\01@\D4\83;\CCC8\98C9\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F50\0F\E5\D0\06\F3\F0\0E\E6@\0Fm`\0E\EC\F0\0E\E1@\0F\809\84\03;\CCC9\00\00I\18\00\00\02\00\00\00\13\82`B \00\00\00\89 \00\00\0D\00\00\002\22\08\09 d\85\04\13\22\A4\84\04\13\22\E3\84\A1\90\14\12L\88\8C\0B\84\84L\100s\04H*\00\C5\1C\01\18\94`\88\08\AA0F7\10@3\02\00\134|\C0\03;\F8\05;\A0\836\08\07x\80\07v(\876h\87p\18\87w\98\07|\88\038p\838\80\037\80\83\0DeP\0Em\D0\0Ez\F0\0Em\90\0Ev@\07z`\07t\D0\06\E6\80\07p\A0\07q \07x\D0\06\EE\80\07z\10\07v\A0\07s \07z`\07t\D0\06\B3\10\07r\80\07:\0FDH #EB\80\1D\8C\10\18I\00\00@\00\00\C0\10\A7\00\00 \00\00\00\00\00\00\00\868\08\10\00\02\00\00\00\00\00\00\90\05\02\00\00\08\00\00\002\1E\98\0C\19\11L\90\8C\09&G\C6\04C\9A\22(\01\0AM\D0i\10\1D]\96\97C\00\00\00y\18\00\00\1C\00\00\00\1A\03L\90F\02\134A\18\08&PIC Level\13\84a\D80\04\C2\C05\08\82\83c+\03ab\B2j\02\B1+\93\9BK{s\03\B9q\81q\81\01A\19c\0Bs;k\B9\81\81q\81q\A9\99q\99I\D9\10\14\8D\D8\D8\EC\DA\5C\DA\DE\C8\EA\D8\CA\5C\CC\D8\C2\CE\E6\A6\04C\1566\BB6\974\B227\BA)A\01\00y\18\00\002\00\00\003\08\80\1C\C4\E1\1Cf\14\01=\88C8\84\C3\8CB\80\07yx\07s\98q\0C\E6\00\0F\ED\10\0E\F4\80\0E3\0CB\1E\C2\C1\1D\CE\A1\1Cf0\05=\88C8\84\83\1B\CC\03=\C8C=\8C\03=\CCx\8Ctp\07{\08\07yH\87pp\07zp\03vx\87p \87\19\CC\11\0E\EC\90\0E\E10\0Fn0\0F\E3\F0\0E\F0P\0E3\10\C4\1D\DE!\1C\D8!\1D\C2a\1Ef0\89;\BC\83;\D0C9\B4\03<\BC\83<\84\03;\CC\F0\14v`\07{h\077h\87rh\077\80\87p\90\87p`\07v(\07v\F8\05vx\87w\80\87_\08\87q\18\87r\98\87y\98\81,\EE\F0\0E\EE\E0\0E\F5\C0\0E\EC\00q \00\00\05\00\00\00&`<\11\D2L\85\05\10\0C\804\06@\F8\D2\14\01\00\00a \00\00\0B\00\00\00\13\04A,\10\00\00\00\03\00\00\004#\00dC\19\020\18\83\01\003\11\CA@\0C\83\11\C1\00\00#\06\04\00\1CB\12\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00", section "__LLVM,__bitcode"
@llvm.cmdline = appending constant [67 x i8] c"-triple\00x86_64-apple-macosx10.10.0\00-emit-llvm\00-disable-llvm-optzns\00", section "__LLVM,__cmdline"

; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4
  store i32 0, i32* %1
  %2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([10 x i8]* @.str, i32 0, i32 0))
  ret i32 0
}

declare i32 @printf(i8*, ...) #1

attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.0.53.3)"}

The data array that is in the IR also changes depending on the optimization and other code generation settings of clang. It's completely unknown to me what format or anything that this is in.

EDIT:

Following the hint on Twitter, I decided to revisit this and to confirm it. I followed this blog post and used his bitcode extractor tool to get the Apple Archive binary out of the MachO executable. And after extracting the Apple Archive with the xar utility, I got this (converted to text with llvm-dis of course)

; ModuleID = '1'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"

@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1

; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4
  store i32 0, i32* %1
  %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @.str, i32 0, i32 0))
  ret i32 0
}

declare i32 @printf(i8*, ...) #1

attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.1.76)"}

The only notable difference really between the non-bitcode IR and the bitcode IR is that filenames have been stripped to just 1, 2, etc for each architecture.

I also confirmed that the bitcode embedded in a binary is generated after optimizations. If you compile with -O3 and extract out the bitcode, it'll be different than if you compile with -O0.

And just to get extra credit, I also confirmed that Apple does not ship bitcode to devices when you download an iOS 9 app. They include a number of other strange sections that I don't recognized like __LINKEDIT, but they do not include __LLVM.__bundle, and thus do not appear to include bitcode in the final binary that runs on a device. Oddly enough, Apple still ships fat binaries with separate 32/64bit code to iOS 8 devices though.

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

CORS with spring-boot and angularjs not working

This works for me:

@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter  {
   //...
   @Override
   protected void configure(HttpSecurity http) throws Exception {

       //...         

       http.cors().configurationSource(new CorsConfigurationSource() {

        @Override
        public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowedHeaders(Collections.singletonList("*"));
            config.setAllowedMethods(Collections.singletonList("*"));
            config.addAllowedOrigin("*");
            config.setAllowCredentials(true);
            return config;
        }
      });

      //...

   }

   //...

}

jQuery get mouse position within an element

Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

_x000D_
_x000D_
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
  var left = el.offset().left;_x000D_
  var top = el.offset().top;_x000D_
  var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
  if (percent) {_x000D_
    x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
    y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
  } else {_x000D_
    x = (evt.pageX - left - (hotspot / 2));_x000D_
    y = (evt.pageY - top - (hotspot / 2));_x000D_
  }_x000D_
_x000D_
  return {_x000D_
    x: x,_x000D_
    y: y_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('.box').click(function(e) {_x000D_
_x000D_
    var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
    var hotspot = $('<div class="hotspot">').css({_x000D_
      left: hp.x,_x000D_
      top: hp.y,_x000D_
    });_x000D_
    $(this).append(hotspot);_x000D_
    $("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
  });_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  background: #efefef;_x000D_
  margin: 20px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  background: green;_x000D_
  border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
  <p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

++i or i++ in for loops ??

For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

Gson: How to exclude specific fields from Serialization without annotations

You can explore the json tree with gson.

Try something like this :

gson.toJsonTree(student).getAsJsonObject()
.get("country").getAsJsonObject().remove("name");

You can add some properties also :

gson.toJsonTree(student).getAsJsonObject().addProperty("isGoodStudent", false);

Tested with gson 2.2.4.

Parse error: Syntax error, unexpected end of file in my PHP code

Check that you closed your class.

For example, if you have controller class with methods, and by accident you delete the final bracket, which close whole class, you will get this error.

class someControler{
private $varr;
public $varu;
..
public function method {
..
} 
..
}// if you forget to close the controller, you will get the error

How can I set the max-width of a table cell using percentages?

According to the definition of max-width in the CSS 2.1 spec, “the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.” So you cannot directly set max-width on a td element.

If you just want the second column to take up at most 67%, then you can set the width (which is in effect minimum width, for table cells) to 33%, e.g. in the example case

td:first-child { width: 33% ;}

Setting that for both columns won’t work that well, since it tends to make browsers give the columns equal width.

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

Get length of array?

Function

Public Function ArrayLen(arr As Variant) As Integer
    ArrayLen = UBound(arr) - LBound(arr) + 1
End Function

Usage

Dim arr(1 To 3) As String  ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr)  ' Prints 3.  Everything's going to be ok.

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

Put byte array to JSON and vice versa

The typical way to send binary in json is to base64 encode it.

Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

Very simply

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);

You'll have to make this conversion depending on the json parser/generator library you use.

Java 8 Stream and operation on arrays

You can turn an array into a stream by using Arrays.stream():

int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);

Once you've got your stream, you can use any of the methods described in the documentation, like sum() or whatever. You can map or filter like in Python by calling the relevant stream methods with a Lambda function:

Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);

Once you're done modifying your stream, you then call toArray() to convert it back into an array to use elsewhere:

int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();

What is the maximum recursion depth in Python, and how to increase it?

I wanted to give you an example for using memoization to compute Fibonacci as this will allow you to compute significantly larger numbers using recursion:

cache = {}
def fib_dp(n):
    if n in cache:
        return cache[n]
    if n == 0: return 0
    elif n == 1: return 1
    else:
        value = fib_dp(n-1) + fib_dp(n-2)
    cache[n] = value
    return value

print(fib_dp(998))

This is still recursive, but uses a simple hashtable that allows the reuse of previously calculated Fibonacci numbers instead of doing them again.

PHP date() format when inserting into datetime in MySQL

Using DateTime class in PHP7+:

function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
 $dt = new DateTime();
 $dt->setDate($year, $month, $day);
 $dt->setTime(0, 0, 0, 0); // set time to midnight

 return $dt->format('Y-m-d H:i:s');
}

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

The -jar option is mutually exclusive of -classpath. See an old description here

-jar

Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.

See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path

Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

How to instantiate a javascript class in another js file?

It is saying the value is undefined because it is a constructor function, not a class with a constructor. In order to use it, you would need to use Customer() or customer().

First, you need to load file1.js before file2.js, like slebetman said:

<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>

Then, you could change your file1.js as follows:

export default class Customer(){
    constructor(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        };
    }
}

And the file2.js as follows:

import { Customer } from "./file1";
var customer=new Customer();

Please correct me if I am wrong.

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

What is Mocking?

The purpose of mocking types is to sever dependencies in order to isolate the test to a specific unit. Stubs are simple surrogates, while mocks are surrogates that can verify usage. A mocking framework is a tool that will help you generate stubs and mocks.

EDIT: Since the original wording mention "type mocking" I got the impression that this related to TypeMock. In my experience the general term is just "mocking". Please feel free to disregard the below info specifically on TypeMock.

TypeMock Isolator differs from most other mocking framework in that it works my modifying IL on the fly. That allows it to mock types and instances that most other frameworks cannot mock. To mock these types/instances with other frameworks you must provide your own abstractions and mock these.

TypeMock offers great flexibility at the expense of a clean runtime environment. As a side effect of the way TypeMock achieves its results you will sometimes get very strange results when using TypeMock.

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is meant by Ems? (Android TextView)

To add to the other answers in Android, Ems size, can, by default, vary in each language and input.

It means that if you want to set a minimum width to a text field, defined by number of chars, you have to calculate the Ems properly and set it, according to your typeface and font size with the Ems attribute.

To those of you struggle with this, you can calculate the hint size yourself to avoid messing with Ems:

val tf = TextField()
val layout = TextInputLayout()
val hint = "Hint"

val measureText = tf.paint.measureText(hint).toInt()
tf.width = tf.paddingLeft + tf.paddingRight + measureText.toInt()
layout.hint = hint

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Replacing &nbsp; from javascript dom text node

i used this, and it worked:

var cleanText = text.replace(/&amp;nbsp;/g,"");

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

What I am thinking is having webpack would be easy when production release.

FYI : https://github.com/Piusha/ngx-lazyloading

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

How can I extract a number from a string in JavaScript?

You can use regular expression.

var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);

That will alert 2.

How to semantically add heading to a list

In this case I would use a definition list as so:

<dl>
  <dt>Fruits I like:</dt>
  <dd>Apples</dd>
  <dd>Bananas</dd>
  <dd>Oranges</dd>
</dl>

How do I install the OpenSSL libraries on Ubuntu?

You want the openssl-devel package. At least I think it's -devel on Ubuntu. Might be -dev. It's one of the two.

How to upload a file in Django?

Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it:

> git clone https://github.com/axelpale/minimal-django-file-upload-example.git

Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4.

Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort.

Update 2013-12-07: Django 1.6 supported at GitHub. One import changed in myapp/urls.py. Thanks goes to Arthedian.

Update 2015-03-17: Django 1.7 supported at GitHub, thanks to aronysidoro.

Update 2015-09-04: Django 1.8 supported at GitHub, thanks to nerogit.

Update 2016-07-03: Django 1.9 supported at GitHub, thanks to daavve and nerogit

Project tree

A basic Django 1.3 project with single app and media/ directory for uploads.

minimal-django-file-upload-example/
    src/
        myproject/
            database/
                sqlite.db
            media/
            myapp/
                templates/
                    myapp/
                        list.html
                forms.py
                models.py
                urls.py
                views.py
            __init__.py
            manage.py
            settings.py
            urls.py

1. Settings: myproject/settings.py

To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS

...
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
    ...
    'myapp',
)

2. Model: myproject/myapp/models.py

Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference.

# -*- coding: utf-8 -*-
from django.db import models

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

3. Form: myproject/myapp/forms.py

To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details.

# -*- coding: utf-8 -*-
from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )

4. View: myproject/myapp/views.py

A view where all the magic happens. Pay attention how request.FILES are handled. For me, it was really hard to spot the fact that request.FILES['docfile'] can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically.

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

5. Project URLs: myproject/urls.py

Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage.

See django.conf.urls.static.static reference for details. See also this discussion about serving media files.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    (r'^', include('myapp.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

6. App URLs: myproject/myapp/urls.py

To make the view accessible, you must specify urls for it. Nothing special here.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
    url(r'^list/$', 'list', name='list'),
)

7. Template: myproject/myapp/templates/myapp/list.html

The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details.

The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>   
    </head>
    <body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No documents.</p>
    {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>
    </body>
</html> 

8. Initialize

Just run syncdb and runserver.

> cd myproject
> python manage.py syncdb
> python manage.py runserver

Results

Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at localhost:8000/list/. Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list.

I hope this answer will help someone as much as it would have helped me.

Insert json file into mongodb

This worked for me - ( from mongo shell )

var file = cat('./new.json');     # file name
use testdb                        # db name
var o = JSON.parse(file);         # convert string to JSON
db.forms.insert(o)                # collection name

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

How to return multiple values in one column (T-SQL)?

Sorry, read the question wrong the first time. You can do something like this:

declare @result varchar(max)

--must "initialize" result for this to work
select @result = ''

select @result = @result + alias
FROM aliases
WHERE username='Bob'

Equivalent VB keyword for 'break'

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

What is a loop invariant?

Beside all of the good answers, I guess a great example from How to Think About Algorithms, by Jeff Edmonds can illustrate the concept very well:

EXAMPLE 1.2.1 "The Find-Max Two-Finger Algorithm"

1) Specifications: An input instance consists of a list L(1..n) of elements. The output consists of an index i such that L(i) has maximum value. If there are multiple entries with this same value, then any one of them is returned.

2) Basic Steps: You decide on the two-finger method. Your right finger runs down the list.

3) Measure of Progress: The measure of progress is how far along the list your right finger is.

4) The Loop Invariant: The loop invariant states that your left finger points to one of the largest entries encountered so far by your right finger.

5) Main Steps: Each iteration, you move your right finger down one entry in the list. If your right finger is now pointing at an entry that is larger then the left finger’s entry, then move your left finger to be with your right finger.

6) Make Progress: You make progress because your right finger moves one entry.

7) Maintain Loop Invariant: You know that the loop invariant has been maintained as follows. For each step, the new left finger element is Max(old left finger element, new element). By the loop invariant, this is Max(Max(shorter list), new element). Mathe- matically, this is Max(longer list).

8) Establishing the Loop Invariant: You initially establish the loop invariant by point- ing both fingers to the first element.

9) Exit Condition: You are done when your right finger has finished traversing the list.

10) Ending: In the end, we know the problem is solved as follows. By the exit condi- tion, your right finger has encountered all of the entries. By the loop invariant, your left finger points at the maximum of these. Return this entry.

11) Termination and Running Time: The time required is some constant times the length of the list.

12) Special Cases: Check what happens when there are multiple entries with the same value or when n = 0 or n = 1.

13) Coding and Implementation Details: ...

14) Formal Proof: The correctness of the algorithm follows from the above steps.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

You most likely ran out of battery and your postgresql server didn't shutdown correctly.

The easiest workaround is to download the official postgresql app and launch it: it will force the server to start (http://postgresapp.com/)

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Open Your .edmx file in XML editor and then remove tag from Tag and also change store:Schema="dbo" to Schema="dbo" and rebuild the solution now error will resolve and you will be able to save the data.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The writer of the database probably did a

sql = "SELECT * FROM STUDENTS WHERE (STUDENT_NAME = '" + student_name + "') AND other stuff";
execute(sql);

If student_name is the one given, that does the selection with the name "Robert" and then drops the table. The "-- " part changes the rest of the given query into a comment.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I fixed it by add a property to renderSeparator Component,the code is here:

_renderSeparator(sectionID,rowID){
    return (
        <View style={styles.separatorLine} key={"sectionID_"+sectionID+"_rowID_"+rowID}></View>
    );
}

The key words of this warning is "unique", sectionID + rowID return a unique value in ListView.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

Read url to string in few lines of java code

URL to String in pure Java

Example call

 String str = getStringFromUrl("YourUrl");

Implementation

You can use the method described in this answer, on How to read URL to an InputStream and combine it with this answer on How to read InputStream to String.

The outcome will be something like

public String getStringFromUrl(URL url) throws IOException {
        return inputStreamToString(urlToInputStream(url,null));
}

public String inputStreamToString(InputStream inputStream) throws IOException {
    try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(UTF_8);
    }
}

private InputStream urlToInputStream(URL url, Map<String, String> args) {
    HttpURLConnection con = null;
    InputStream inputStream = null;
    try {
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(15000);
        con.setReadTimeout(15000);
        if (args != null) {
            for (Entry<String, String> e : args.entrySet()) {
                con.setRequestProperty(e.getKey(), e.getValue());
            }
        }
        con.connect();
        int responseCode = con.getResponseCode();
        /* By default the connection will follow redirects. The following
         * block is only entered if the implementation of HttpURLConnection
         * does not perform the redirect. The exact behavior depends to 
         * the actual implementation (e.g. sun.net).
         * !!! Attention: This block allows the connection to 
         * switch protocols (e.g. HTTP to HTTPS), which is <b>not</b> 
         * default behavior. See: https://stackoverflow.com/questions/1884230 
         * for more info!!!
         */
        if (responseCode < 400 && responseCode > 299) {
            String redirectUrl = con.getHeaderField("Location");
            try {
                URL newUrl = new URL(redirectUrl);
                return urlToInputStream(newUrl, args);
            } catch (MalformedURLException e) {
                URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
                return urlToInputStream(newUrl, args);
            }
        }
        /*!!!!!*/

        inputStream = con.getInputStream();
        return inputStream;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Pros

  • It is pure java

  • It can be easily enhanced by adding different headers (instead of passing a null object, like the example above does), authentication, etc.

  • Handling of protocol switches is supported

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

How can I get date in application run by node.js?

You would use the javascript date object:

MDN documentation for the Date object

var d = new Date();

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Integer division with remainder in JavaScript?

I normally use:

const quotient =  (a - a % b) / b;
const remainder = a % b;

It's probably not the most elegant, but it works.

Is there a function to copy an array in C/C++?

I give here 2 ways of coping array, for C and C++ language. memcpy and copy both ar usable on C++ but copy is not usable for C, you have to use memcpy if you are trying to copy array in C.

#include <stdio.h>
#include <iostream>
#include <algorithm> // for using copy (library function)
#include <string.h> // for using memcpy (library function)


int main(){

    int arr[] = {1, 1, 2, 2, 3, 3};
    int brr[100];

    int len = sizeof(arr)/sizeof(*arr); // finding size of arr (array)

    std:: copy(arr, arr+len, brr); // which will work on C++ only (you have to use #include <algorithm>
    memcpy(brr, arr, len*(sizeof(int))); // which will work on both C and C++

    for(int i=0; i<len; i++){ // Printing brr (array).
        std:: cout << brr[i] << " ";
    }

    return 0;
}

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Convert string to Color in C#

It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:

System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84

C++ display stack trace on exception

I recommend http://stacktrace.sourceforge.net/ project. It support Windows, Mac OS and also Linux

Get first day of week in SQL Server

Maybe I'm over simplifying here, and that may be the case, but this seems to work for me. Haven't ran into any problems with it yet...

CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7 - 7) as 'FirstDayOfWeek'
CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7) as 'LastDayOfWeek'

How to read from standard input in the console?

I think a more standard way to do this would be:

package main

import "fmt"

func main() {
    fmt.Print("Enter text: ")
    var input string
    fmt.Scanln(&input)
    fmt.Print(input)
}

Take a look at the scan godoc: http://godoc.org/fmt#Scan

Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

Iframe positioning

you should use position: relative; for one iframe and position:absolute; for the second;

Example: for first iframe use:

<div id="contentframe" style="position:relative; top: 100px; left: 50px;">

for second iframe use:

<div id="contentframe" style="position:absolute; top: 0px; left: 690px;">

How do I check in JavaScript if a value exists at a certain array index?

if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}

Using jquery to get element's position relative to viewport

Look into the Dimensions plugin, specifically scrollTop()/scrollLeft(). Information can be found at http://api.jquery.com/scrollTop.

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

Ajax Upload image

Here is simple way using HTML5 and jQuery:

1) include two JS file

<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>

2) include CSS to have cool buttons

<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />

3) create DIV or SPAN

<div class="demo" > </div>

4) write this code in your HTML page

$('.demo').ajaxupload({
    url:'upload.php'
});

5) create you upload.php file to have PHP code to upload data.

You can download required JS file from here Here is Example

Its too cool and too fast And easy too! :)

Why won't bundler install JSON gem?

This appears to be a bug in Bundler not recognizing the default gems installed along with ruby 2.x. I still experienced the problem even with the latest version of bundler (1.5.3).

One solution is to simply delete json-1.8.1.gemspec from the default gemspec directory.

rm ~/.rubies/ruby-2.1.0/lib/ruby/gems/2.1.0/specifications/default/json-1.8.1.gemspec

After doing this, bundler should have no problem locating the gem. Note that I am using chruby. If you're using some other ruby manager, you'll have to update your path accordingly.

How to make Bitmap compress without change the bitmap size?

Here's a short means I used to reduce the size of Images that have a high byteCount (basically pixels)

fun resizeImage(image: Bitmap): Bitmap {

    val width = image.width
    val height = image.height

    val scaleWidth = width / 10
    val scaleHeight = height / 10

    if (image.byteCount <= 1000000)
        return image

    return Bitmap.createScaledBitmap(image, scaleWidth, scaleHeight, false)
}

This returns a scaled Bitmap that is over 10 times smaller than the Bitmap passed as a parameter. Might not be the most ideal solution but it works.

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

What does -> mean in Python function definitions?

def f(x) -> str:
return x+4

print(f(45))

# will give the result : 
49

# or with other words '-> str' has NO effect to return type:

print(f(45).__class__)

<class 'int'>

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

How to parse a JSON Input stream

This example reads all objects from a stream of objects, it is assumed that you need CustomObjects instead of a Map:

        ObjectMapper mapper = new ObjectMapper();
        JsonParser parser = mapper.getFactory().createParser( source );
        if(parser.nextToken() != JsonToken.START_ARRAY) {
          throw new IllegalStateException("Expected an array");
        }
        while(parser.nextToken() == JsonToken.START_OBJECT) {
          // read everything from this START_OBJECT to the matching END_OBJECT
          // and return it as a tree model ObjectNode
          ObjectNode node = mapper.readTree(parser);
          CustomObject custom = mapper.convertValue( node, CustomObject.class );
           // do whatever you need to do with this object
          System.out.println( "" + custom );
        }
        parser.close();

This answer was composed by using : Use Jackson To Stream Parse an Array of Json Objects and Convert JsonNode into Object

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

Could not resolve this reference. Could not locate the assembly

in 2020, this behavior still present with VS2019. (even if I clean projects from the solution explorer in VS2019, this not solves the problem)

The solution that worked for me was to open the folder of the project, and manually remove the \bin and \obj directories.

Relative Paths in Javascript in an external file

Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript

<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>

error: (-215) !empty() in function detectMultiScale

You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example

This will not work

front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')

Use full path, now it will work fine

front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')

How to import data from text file to mysql database

1. if it's tab delimited txt file:

LOAD DATA LOCAL INFILE 'D:/MySQL/event.txt' INTO TABLE event

LINES TERMINATED BY '\r\n';

2. otherwise:

LOAD DATA LOCAL INFILE 'D:/MySQL/event.txt' INTO TABLE event

FIELDS TERMINATED BY 'x' (here x could be comma ',', tab '\t', semicolon ';', space ' ')

LINES TERMINATED BY '\r\n';

Using different Web.config in development and production environment

I'd like to know, too. This helps isolate the problem for me

<connectionStrings configSource="connectionStrings.config"/>

I then keep a connectionStrings.config as well as a "{host} connectionStrings.config". It's still a problem, but if you do this for sections that differ in the two environments, you can deploy and version the same web.config.

(And I don't use VS, btw.)

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

When should I use File.separator and when File.pathSeparator?

If you mean File.separator and File.pathSeparator then:

  • File.pathSeparator is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ; to separate the file paths so on Windows File.pathSeparator would be ;.

  • File.separator is either / or \ that is used to split up the path to a specific file. For example on Windows it is \ or C:\Documents\Test

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to initialize weights in PyTorch?

Here is the better way, just pass your whole model

import torch.nn as nn
def initialize_weights(model):
    # Initializes weights according to the DCGAN paper
    for m in model.modules():
        if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):
            nn.init.normal_(m.weight.data, 0.0, 0.02)
        # if you also want for linear layers ,add one more elif condition 

<ng-container> vs <template>

Edit : Now it is documented

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

(...)

The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:

  if (someCondition) {
      statement1; 
      statement2;
      statement3;
     }

Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.

Original answer:

According to this pull request :

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

so this angular template :

<div>
    <ng-container>foo</ng-container>
<div>

will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

<div>
    <ng-container *ngIf="true">
        <h2>Title</h2>
        <div>Content</div>
    </ng-container>
</div>

will then produce :

<div>
    <h2>Title</h2>
    <div>Content</div>
</div>

Spring Security redirect to previous page after successful login

I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.

Here is an example:

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

How do I clone a subdirectory only of a Git repository?

It's not possible to clone subdirectory only with Git, but below are few workarounds.

Filter branch

You may want to rewrite the repository to look as if trunk/public_html/ had been its project root, and discard all other history (using filter-branch), try on already checkout branch:

git filter-branch --subdirectory-filter trunk/public_html -- --all

Notes: The -- that separates filter-branch options from revision options, and the --all to rewrite all branches and tags. All information including original commit times or merge information will be preserved. This command honors .git/info/grafts file and refs in the refs/replace/ namespace, so if you have any grafts or replacement refs defined, running this command will make them permanent.

Warning! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem.


Sparse checkout

Here are simple steps with sparse checkout approach which will populate the working directory sparsely, so you can tell Git which folder(s) or file(s) in the working directory are worth checking out.

  1. Clone repository as usual (--no-checkout is optional):

    git clone --no-checkout git@foo/bar.git
    cd bar
    

    You may skip this step, if you've your repository already cloned.

    Hint: For large repos, consider shallow clone (--depth 1) to checkout only latest revision or/and --single-branch only.

  2. Enable sparseCheckout option:

    git config core.sparseCheckout true
    
  3. Specify folder(s) for sparse checkout (without space at the end):

    echo "trunk/public_html/*"> .git/info/sparse-checkout
    

    or edit .git/info/sparse-checkout.

  4. Checkout the branch (e.g. master):

    git checkout master
    

Now you should have selected folders in your current directory.

You may consider symbolic links if you've too many levels of directories or filtering branch instead.


How can I set a UITableView to grouped style

You can do this with using storyboard/XIB also

  1. Go To storyboard -> Select your viewController -> Select your table
  2. Select the "Style" property in interface-builder
  3. Select the "Grouped"
  4. Done

R object identification

I usually start out with some combination of:

typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)

as appropriate based on what's revealed. For example, try with:

obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)

..etc.

If obj is an S3 or S4 object, you can also try methods or showMethods, showClass, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).

EDIT: Dirk and Hadley mention str(obj) in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.

Repeat string to certain length

This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt string increases.

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

MySQL: Check if the user exists and drop it

This worked for me:

GRANT USAGE ON *.* TO 'username'@'localhost';
DROP USER 'username'@'localhost';

This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: http://bugs.mysql.com/bug.php?id=19166

Updates: @Hao recommends adding IDENTIFIED BY; @andreb (in comments) suggests disabling NO_AUTO_CREATE_USER.

A simple algorithm for polygon intersection

This can be a huge approximation depending on your polygons, but here's one :

  • Compute the center of mass for each polygon.
  • Compute the min or max or average distance from each point of the polygon to the center of mass.
  • If C1C2 (where C1/2 is the center of the first/second polygon) >= D1 + D2 (where D1/2 is the distance you computed for first/second polygon) then the two polygons "intersect".

Though, this should be very efficient as any transformation to the polygon applies in the very same way to the center of mass and the center-node distances can be computed only once.

How to start a stopped Docker container with a different command?

I took @Dmitriusan's answer and made it into an alias:

alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'

Add this into your ~/.bashrc aliases file, and you'll have a nifty new docker-run-prev-container alias which'll drop you into a shell in the previous container.

Helpful for debugging failed docker builds.