Programs & Examples On #Text extraction

How to extract string following a pattern with grep, regex or perl

The regular expression would be:

.+name="([^"]+)"

Then the grouping would be in the \1

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

PDF Parsing Using Python - extracting formatted and plain texts

That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.

I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.

How to extract text from a PDF?

PdfTextStream (which you said you have been looking at) is now free for single threaded applications. In my opinion its quality is much better than other libraries (esp. for things like funky embedded fonts, etc).

Alternatively, you should have a look at Apache PDFBox, open source.

Getting URL parameter in java and extract a specific text from that URL

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

Import These Libraries

    import java.net.URL;
    import java.util.regex.*;

Copy/Paste this function

    public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)

Python module for converting PDF to text

The PDFMiner package has changed since codeape posted.

EDIT (again):

PDFMiner has been updated again in version 20100213

You can check the version you have installed with the following:

>>> import pdfminer
>>> pdfminer.__version__
'20100213'

Here's the updated version (with comments on what I changed/added):

def pdf_to_csv(filename):
    from cStringIO import StringIO  #<-- added so you can copy/paste this to try it
    from pdfminer.converter import LTTextItem, TextConverter
    from pdfminer.pdfparser import PDFDocument, PDFParser
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter

    class CsvConverter(TextConverter):
        def __init__(self, *args, **kwargs):
            TextConverter.__init__(self, *args, **kwargs)

        def end_page(self, i):
            from collections import defaultdict
            lines = defaultdict(lambda : {})
            for child in self.cur_item.objs:
                if isinstance(child, LTTextItem):
                    (_,_,x,y) = child.bbox                   #<-- changed
                    line = lines[int(-y)]
                    line[x] = child.text.encode(self.codec)  #<-- changed

            for y in sorted(lines.keys()):
                line = lines[y]
                self.outfp.write(";".join(line[x] for x in sorted(line.keys())))
                self.outfp.write("\n")

    # ... the following part of the code is a remix of the 
    # convert() function in the pdfminer/tools/pdf2text module
    rsrc = PDFResourceManager()
    outfp = StringIO()
    device = CsvConverter(rsrc, outfp, codec="utf-8")  #<-- changed 
        # becuase my test documents are utf-8 (note: utf-8 is the default codec)

    doc = PDFDocument()
    fp = open(filename, 'rb')
    parser = PDFParser(fp)       #<-- changed
    parser.set_document(doc)     #<-- added
    doc.set_parser(parser)       #<-- added
    doc.initialize('')

    interpreter = PDFPageInterpreter(rsrc, device)

    for i, page in enumerate(doc.get_pages()):
        outfp.write("START PAGE %d\n" % i)
        interpreter.process_page(page)
        outfp.write("END PAGE %d\n" % i)

    device.close()
    fp.close()

    return outfp.getvalue()

Edit (yet again):

Here is an update for the latest version in pypi, 20100619p1. In short I replaced LTTextItem with LTChar and passed an instance of LAParams to the CsvConverter constructor.

def pdf_to_csv(filename):
    from cStringIO import StringIO  
    from pdfminer.converter import LTChar, TextConverter    #<-- changed
    from pdfminer.layout import LAParams
    from pdfminer.pdfparser import PDFDocument, PDFParser
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter

    class CsvConverter(TextConverter):
        def __init__(self, *args, **kwargs):
            TextConverter.__init__(self, *args, **kwargs)

        def end_page(self, i):
            from collections import defaultdict
            lines = defaultdict(lambda : {})
            for child in self.cur_item.objs:
                if isinstance(child, LTChar):               #<-- changed
                    (_,_,x,y) = child.bbox                   
                    line = lines[int(-y)]
                    line[x] = child.text.encode(self.codec)

            for y in sorted(lines.keys()):
                line = lines[y]
                self.outfp.write(";".join(line[x] for x in sorted(line.keys())))
                self.outfp.write("\n")

    # ... the following part of the code is a remix of the 
    # convert() function in the pdfminer/tools/pdf2text module
    rsrc = PDFResourceManager()
    outfp = StringIO()
    device = CsvConverter(rsrc, outfp, codec="utf-8", laparams=LAParams())  #<-- changed
        # becuase my test documents are utf-8 (note: utf-8 is the default codec)

    doc = PDFDocument()
    fp = open(filename, 'rb')
    parser = PDFParser(fp)       
    parser.set_document(doc)     
    doc.set_parser(parser)       
    doc.initialize('')

    interpreter = PDFPageInterpreter(rsrc, device)

    for i, page in enumerate(doc.get_pages()):
        outfp.write("START PAGE %d\n" % i)
        if page is not None:
            interpreter.process_page(page)
        outfp.write("END PAGE %d\n" % i)

    device.close()
    fp.close()

    return outfp.getvalue()

EDIT (one more time):

Updated for version 20110515 (thanks to Oeufcoque Penteano!):

def pdf_to_csv(filename):
    from cStringIO import StringIO  
    from pdfminer.converter import LTChar, TextConverter
    from pdfminer.layout import LAParams
    from pdfminer.pdfparser import PDFDocument, PDFParser
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter

    class CsvConverter(TextConverter):
        def __init__(self, *args, **kwargs):
            TextConverter.__init__(self, *args, **kwargs)

        def end_page(self, i):
            from collections import defaultdict
            lines = defaultdict(lambda : {})
            for child in self.cur_item._objs:                #<-- changed
                if isinstance(child, LTChar):
                    (_,_,x,y) = child.bbox                   
                    line = lines[int(-y)]
                    line[x] = child._text.encode(self.codec) #<-- changed

            for y in sorted(lines.keys()):
                line = lines[y]
                self.outfp.write(";".join(line[x] for x in sorted(line.keys())))
                self.outfp.write("\n")

    # ... the following part of the code is a remix of the 
    # convert() function in the pdfminer/tools/pdf2text module
    rsrc = PDFResourceManager()
    outfp = StringIO()
    device = CsvConverter(rsrc, outfp, codec="utf-8", laparams=LAParams())
        # becuase my test documents are utf-8 (note: utf-8 is the default codec)

    doc = PDFDocument()
    fp = open(filename, 'rb')
    parser = PDFParser(fp)       
    parser.set_document(doc)     
    doc.set_parser(parser)       
    doc.initialize('')

    interpreter = PDFPageInterpreter(rsrc, device)

    for i, page in enumerate(doc.get_pages()):
        outfp.write("START PAGE %d\n" % i)
        if page is not None:
            interpreter.process_page(page)
        outfp.write("END PAGE %d\n" % i)

    device.close()
    fp.close()

    return outfp.getvalue()

Extract a single (unsigned) integer from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

How to extract a substring using regex

Some how the group(1) didnt work for me. I used group(0) to find the url version.

Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
Matcher m = urlVersionPattern.matcher(url);
if (m.find()) { 
    return StringUtils.substringBetween(m.group(0), "/", "/");
}
return "v0";

Spring configure @ResponseBody JSON format

In spring3.2, new solution is introduced by: http://static.springsource.org/spring/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.html , the below is my example:

 <mvc:annotation-driven>
   ?<mvc:message-converters>
     ??<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
       ???<property name="objectMapper">
         ????<bean
 class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
           ?????<property name="featuresToEnable">
             ??????<array>
               ???????<util:constant static-field="com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES" />
             ??????</array>
           ?????</property>
         ????</bean>
       ???</property>
     ??</bean>
   ?</mvc:message-converters>
 </mvc:annotation-driven>

Handling ExecuteScalar() when no results are returned

this could help .. example::

using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteScalar
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
    mySqlConnection.Open();

    int returnValue = (int) mySqlCommand.ExecuteScalar();
    Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

    mySqlConnection.Close();
  }
}

from this here

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

I have solved as plist file.

  1. Add a NSAppTransportSecurity : Dictionary.
  2. Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES

enter image description here

Simple way to convert datarow array to datatable

Another way is to use a DataView

// Create a DataTable
DataTable table = new DataTable()
...

// Filter and Sort expressions
string expression = "[Birth Year] >= 1983"; 
string sortOrder = "[Birth Year] ASC";

// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);

// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

How to place the ~/.composer/vendor/bin directory in your PATH?

In case someone uses ZSH, all steps are the same, except a few things:

  1. Locate file .zshrc
  2. Add the following line at the bottom export PATH=~/.composer/vendor/bin:$PATH
  3. source ~/.zshrc

Then try valet, if asks for password, then everything is ok.

Taking pictures with camera on Android programmatically

Intent takePhoto = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(takePhoto, CAMERA_PIC_REQUEST)

and set CAMERA_PIC_REQUEST= 1 or 0

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

You can use the getters of java.time.LocalDateTime for that.

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Or, when you're not on Java 8 yet, make use of java.util.Calendar.

Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Either way, this prints as of now:

2010-04-16 15:15:17.816

To convert an int to String, make use of String#valueOf().


If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),

LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

or when you're not on Java 8 yet, use java.text.SimpleDateFormat:

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

Either way, this yields:

2010-04-16T15:15:17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517

See also:

How to Batch Rename Files in a macOS Terminal?

To rename files, you can use the rename utility:

brew install rename

For example, to change a search string in all filenames in current directory:

rename -nvs searchword replaceword *

Remove the 'n' parameter to apply the changes.

More info: man rename

How to know that a string starts/ends with a specific string in jQuery?

ES6 now supports the startsWith() and endsWith() method for checking beginning and ending of strings. If you want to support pre-es6 engines, you might want to consider adding one of the suggested methods to the String prototype.

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true

Download file and automatically save it to folder

My program does exactly what you are after, no prompts or anything, please see the following code.

This code will create all of the necessary directories if they don't already exist:

Directory.CreateDirectory(C:\dir\dira\dirb);  // This code will create all of these directories  

This code will download the given file to the given directory (after it has been created by the previous snippet:

private void install()
    {
        WebClient webClient = new WebClient();                                                          // Creates a webclient
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);                   // Uses the Event Handler to check whether the download is complete
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);  // Uses the Event Handler to check for progress made
        webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip");           // Defines the URL and destination directory for the downloaded file
    }

So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.

jQuery checkbox event handling

There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log).

  • Listening for click events on checkboxes is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label element was clicked. Always listen for the change event.

  • Use the jQuery :checkbox pseudo-selector, rather than input[type=checkbox]. :checkbox is shorter and more readable.

  • Use is() with the jQuery :checked pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.

Basic event handler attached to existing elements:

$('#myform :checkbox').change(function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

Notes:

  • Uses the :checkbox selector, which is preferable to using input[type=checkbox]
  • This connects only to matching elements that exist at the time the event was registered.

Delegated event handler attached to ancestor element:

Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).

$('#myform').on('change', ':checkbox', function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

Notes:

  • This works by listening for events (in this case change) to bubble up to a non-changing ancestor element (in this case #myform).
  • It then applies the jQuery selector (':checkbox' in this case) to only the elements in the bubble chain.
  • It then applies the event handler function to only those matching elements that caused the event.
  • Use document as the default to connect the delegated event handler, if nothing else is closer/convenient.
  • Do not use body to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.

The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.

Q: Is it slower?

A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.


Why doesn't prop('checked', true) fire the change event?

This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger (not triggerHandler):

e.g. without trigger no event occurs

$cb.prop('checked', !$cb.prop('checked'));

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

e.g. with trigger the normal change event is caught

$cb.prop('checked', !$cb.prop('checked')).trigger('change');

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

Notes:

  • Do not use triggerHandler as was suggested by one user, as it will not bubble events to a delegated event handler.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

although it will work for an event handler directly connected to the element:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Reference: http://api.jquery.com/triggerhandler/

If anyone has additional features they feel are not covered by this, please do suggest additions.

Why when I transfer a file through SFTP, it takes longer than FTP?

Yes, encryption add some load to your cpu, but if your cpu is not ancient that should not affect as much as you say.

If you enable compression for SSH, SCP is actually faster than FTP despite the SSH encryption (if I remember, twice as fast as FTP for the files I tried). I haven't actually used SFTP, but I believe it uses SCP for the actual file transfer. So please try this and let us know :-)

JavaScript: undefined !== undefined?

A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.

B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined wherever you are.

In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

Is a DIV inside a TD a bad idea?

No. Not necessarily.

If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.

According to the HTML Specification

A <div> can be placed where flow content is expected1, which is the <td> content model2.

Get the name of an object's type

Is there a JavaScript equivalent of Java's class.getName()?

No.

ES2015 Update: the name of class Foo {} is Foo.name. The name of thing's class, regardless of thing's type, is thing.constructor.name. Builtin constructors in an ES2015 environment have the correct name property; for instance (2).constructor.name is "Number".


But here are various hacks that all fall down in one way or another:

Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};

Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can't speak for other implementations.

If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...


I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...

Using the constructor property...

Every object has a value for its constructor property, but depending on how that object was constructed as well as what you want to do with that value, it may or may not be useful.

Generally speaking, you can use the constructor property to test the type of the object like so:

var myArray = [1,2,3];
(myArray.constructor == Array); // true

So, that works well enough for most needs. That said...

Caveats

Will not work AT ALL in many cases

This pattern, though broken, is quite common:

function Thingy() {
}
Thingy.prototype = {
    method1: function() {
    },
    method2: function() {
    }
};

Objects constructed via new Thingy will have a constructor property that points to Object, not Thingy. So we fall right at the outset; you simply cannot trust constructor in a codebase that you don't control.

Multiple Inheritance

An example where it isn't as obvious is using multiple inheritance:

function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a

Things now don't work as you might expect them to:

var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true

So, you might get unexpected results if the object your testing has a different object set as its prototype. There are ways around this outside the scope of this discussion.

There are other uses for the constructor property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.

Will not work cross-frame and cross-window

Using .constructor for type checking will break when you want to check the type of objects coming from different window objects, say that of an iframe or a popup window. This is because there's a different version of each core type constructor in each `window', i.e.

iframe.contentWindow.Array === Array // false

Using the instanceof operator...

The instanceof operator is a clean way of testing object type as well, but has its own potential issues, just like the constructor property.

var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true

But instanceof fails to work for literal values (because literals are not Objects)

3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false

The literals need to be wrapped in an Object in order for instanceof to work, for example

new Number(3) instanceof Number // true

The .constructor check works fine for literals because the . method invocation implicitly wraps the literals in their respective object type

3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true

Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)

Will not work cross-frame and cross-window

instanceof also will not work across different windows, for the same reason as the constructor property check.


Using the name property of the constructor property...

Does not work AT ALL in many cases

Again, see above; it's quite common for constructor to be utterly and completely wrong and useless.

Does NOT work in <IE9

Using myObjectInstance.constructor.name will give you a string containing the name of the constructor function used, but is subject to the caveats about the constructor property that were mentioned earlier.

For IE9 and above, you can monkey-patch in support:

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1] : "";
        },
        set: function(value) {}
    });
}

Updated version from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by comments pointing out potential pitfalls in the previous code.

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s([^(]{1,})\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1].trim() : "";
        },
        set: function(value) {}
    });
}

Using Object.prototype.toString

It turns out, as this post details, you can use Object.prototype.toString - the low level and generic implementation of toString - to get the type for all built-in types

Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]

One could write a short helper function such as

function type(obj){
    return Object.prototype.toString.call(obj).slice(8, -1);
}

to remove the cruft and get at just the type name

type('abc') // String

However, it will return Object for all user-defined types.


Caveats for all...

All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:

// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // true
(obj.constructor.name == "Foo");  // true

// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // false
(obj.constructor.name == "Foo");  // false


// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object);              // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == "");         // true


// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object);      // true
(obj instanceof Foo);         // true
(obj.constructor == Foo);     // true
(obj.constructor.name == ""); // true


// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object);            // true
(obj.constructor == Object);        // true
(obj.constructor.name == "Object"); // true

While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.

NOTE:

Discussion of the typeof operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an object is a given type, since it is very simplistic. Understanding where typeof is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)

Getting the parent div of element

Knowing the parent of an element is useful when you are trying to position them out the "real-flow" of elements.

Below given code will output the id of parent of element whose id is provided. Can be used for misalignment diagnosis.

<!-- Patch of code to find parent -->
<p id="demo">Click the button </p>
<button onclick="parentFinder()">Find Parent</button>
<script>
function parentFinder()
{
    var x=document.getElementById("demo"); 
    var y=document.getElementById("*id of Element you want to know parent of*");
    x.innerHTML=y.parentNode.id;
}
</script>
<!-- Patch ends -->

height: calc(100%) not working correctly in CSS

If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:

height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");

Removing multiple classes (jQuery)

There are many ways can do that!

jQuery

  1. remove all class
    $("element").removeClass();
    OR
    $("#item").removeAttr('class');
    OR
    $("#item").attr('class', '');
    OR
    $('#item')[0].className = '';

  2. remove multi class
    $("element").removeClass("class1 ... classn");
    OR
    $("element").removeClass("class1").removeClass("...").removeClass("classn");

Vanilla Javascript

  1. remove all class

_x000D_
_x000D_
// remove all items all class  _x000D_
const items = document.querySelectorAll('item');_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
    items[i].className = '';_x000D_
}
_x000D_
_x000D_
_x000D_

  1. remove multi class

_x000D_
_x000D_
// only remove all class of first item_x000D_
const item1 = document.querySelector('item');_x000D_
item1.className = '';
_x000D_
_x000D_
_x000D_

Why aren't python nested functions called closures?

The question has already been answered by aaronasterling

However, someone might be interested in how the variables are stored under the hood.

Before coming to the snippet:

Closures are functions that inherit variables from their enclosing environment. When you pass a function callback as an argument to another function that will do I/O, this callback function will be invoked later, and this function will — almost magically — remember the context in which it was declared, along with all the variables available in that context.

  • If a function does not use free variables it doesn't form a closure.

  • If there is another inner level which uses free variables -- all previous levels save the lexical environment ( example at the end )

  • function attributes func_closure in python < 3.X or __closure__ in python > 3.X save the free variables.

  • Every function in python has this closure attributes, but it doesn't save any content if there is no free variables.

example: of closure attributes but no content inside as there is no free variable.

>>> def foo():
...     def fii():
...         pass
...     return fii
...
>>> f = foo()
>>> f.func_closure
>>> 'func_closure' in dir(f)
True
>>>

NB: FREE VARIABLE IS MUST TO CREATE A CLOSURE.

I will explain using the same snippet as above:

>>> def make_printer(msg):
...     def printer():
...         print msg
...     return printer
...
>>> printer = make_printer('Foo!')
>>> printer()  #Output: Foo!

And all Python functions have a closure attribute so let's examine the enclosing variables associated with a closure function.

Here is the attribute func_closure for the function printer

>>> 'func_closure' in dir(printer)
True
>>> printer.func_closure
(<cell at 0x108154c90: str object at 0x108151de0>,)
>>>

The closure attribute returns a tuple of cell objects which contain details of the variables defined in the enclosing scope.

The first element in the func_closure which could be None or a tuple of cells that contain bindings for the function’s free variables and it is read-only.

>>> dir(printer.func_closure[0])
['__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__getattribute__',
 '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
 '__setattr__',  '__sizeof__', '__str__', '__subclasshook__', 'cell_contents']
>>>

Here in the above output you can see cell_contents, let's see what it stores:

>>> printer.func_closure[0].cell_contents
'Foo!'    
>>> type(printer.func_closure[0].cell_contents)
<type 'str'>
>>>

So, when we called the function printer(), it accesses the value stored inside the cell_contents. This is how we got the output as 'Foo!'

Again I will explain using the above snippet with some changes:

 >>> def make_printer(msg):
 ...     def printer():
 ...         pass
 ...     return printer
 ...
 >>> printer = make_printer('Foo!')
 >>> printer.func_closure
 >>>

In the above snippet, I din't print msg inside the printer function, so it doesn't create any free variable. As there is no free variable, there will be no content inside the closure. Thats exactly what we see above.

Now I will explain another different snippet to clear out everything Free Variable with Closure:

>>> def outer(x):
...     def intermediate(y):
...         free = 'free'
...         def inner(z):
...             return '%s %s %s %s' %  (x, y, free, z)
...         return inner
...     return intermediate
...
>>> outer('I')('am')('variable')
'I am free variable'
>>>
>>> inter = outer('I')
>>> inter.func_closure
(<cell at 0x10c989130: str object at 0x10c831b98>,)
>>> inter.func_closure[0].cell_contents
'I'
>>> inn = inter('am')

So, we see that a func_closure property is a tuple of closure cells, we can refer them and their contents explicitly -- a cell has property "cell_contents"

>>> inn.func_closure
(<cell at 0x10c9807c0: str object at 0x10c9b0990>, 
 <cell at 0x10c980f68: str object at   0x10c9eaf30>, 
 <cell at 0x10c989130: str object at 0x10c831b98>)
>>> for i in inn.func_closure:
...     print i.cell_contents
...
free
am 
I
>>>

Here when we called inn, it will refer all the save free variables so we get I am free variable

>>> inn('variable')
'I am free variable'
>>>

How do I display image in Alert/confirm box in Javascript?

Use jQuery dialog to show image, try this code

<html>
  <head>
    </head>
    <body>
     <div id="divid">
         <img>
     </div>
    <body>
  </html>


<script>
 $(document).ready(function(){
      $("btn").click(function(){
      $("divid").dialog();
   });
  });  
 </script>

`

first you have to include jQuery UI at your Page.

Working fiddle

Last Key in Python Dictionary

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

java: run a function after a specific number of seconds

All other unswers require to run your code inside a new thread. In some simple use cases you may just want to wait a bit and continue execution within the same thread/flow.

Code below demonstrates that technique. Keep in mind this is similar to what java.util.Timer does under the hood but more lightweight.

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

DelayUtil Implementation

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param duration the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Solution that helped me is: do not map DispatcherServlet to /*, map it to /. Final config is then:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        ...
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Check if value exists in dataTable?

you could set the database as IEnumberable and use linq to check if the values exist. check out this link

LINQ Query on Datatable to check if record exists

the example given is

var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...

you could supplement where with any

PHP - Fatal error: Unsupported operand types

I guess you want to do this:

$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
   $avg = round($total_rating_points / $total_rating_count, 1);

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
    Range("E2:E1344").Select

Only exception being are you sure your Autofill code is perfect...

Windows Task Scheduler doesn't start batch file task

Configuration that worked for me:

  • In General tab: mark radio button - "Run only when user is logged on" <= important !
  • Program/script: just the path to script without quotes or nothing: C:/tools/script.bat
  • Add arguments: kept it empty
  • Start in: kept it empty

In settings, only 2 checkboxes marked:

  • Allow task to be run on demand
  • if the running task does not end when requested, force it to stop

Date Conversion from String to sql Date in Java giving different output?

mm stands for "minutes". Use MM instead:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

How to check whether dynamically attached event listener exists or not?

Possible duplicate: Check if an element has event listener on it. No jQuery Please find my answer there.

Basically here is the trick for Chromium (Chrome) browser:

getEventListeners(document.querySelector('your-element-selector'));

How do I import CSV file into a MySQL table?

Try this, it worked for me

    LOAD DATA LOCAL INFILE 'filename.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 ROWS;

IGNORE 1 ROWS here ignores the first row which contains the fieldnames. Note that for the filename you must type the absolute path of the file.

How to update single value inside specific array item in redux

You don't have to do everything in one line:

case 'SOME_ACTION':
  const newState = { ...state };
  newState.contents = 
    [
      newState.contents[0],
      {title: newState.contnets[1].title, text: action.payload}
    ];
  return newState

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

In AngularJS, what's the difference between ng-pristine and ng-dirty?

The ng-dirty class tells you that the form has been modified by the user, whereas the ng-pristine class tells you that the form has not been modified by the user. So ng-dirty and ng-pristine are two sides of the same story.

The classes are set on any field, while the form has two properties, $dirty and $pristine.

You can use the $scope.form.$setPristine() function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).

If you want a $scope.form.$setPristine()-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty flag to false.

Hope this helps.

The entity cannot be constructed in a LINQ to Entities query

You can solve this by using Data Transfer Objects (DTO's).

These are a bit like viewmodels where you put in the properties you need and you can map them manually in your controller or by using third-party solutions like AutoMapper.

With DTO's you can :

  • Make data serialisable (Json)
  • Get rid of circular references
  • Reduce networktraffic by leaving properties you don't need (viewmodelwise)
  • Use objectflattening

I've been learning this in school this year and it's a very useful tool.

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

How to check if an NSDictionary or NSMutableDictionary contains a key?

Because nil cannot be stored in Foundation data structures NSNull is sometimes to represent a nil. Because NSNull is a singleton object you can check to see if NSNull is the value stored in dictionary by using direct pointer comparison:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

Check your Elastic version.

I had these problem because I was looking at the incorrect version's documentation.

enter image description here

How to check if div element is empty

Like others have already noted, you can use :empty in jQuery like this:

$('#cartContent:empty').remove();

It will remove the #cartContent div if it is empty.

But this and other techniques that people are suggesting here may not do what you want because if it has any text nodes containing whitespace it is not considered empty. So this is not empty:

<div> </div>

while you may want to consider it empty.

I had this problem some time ago and I wrote this tiny jQuery plugin - just add it to your code:

jQuery.expr[':'].space = function(elem) {
  var $elem = jQuery(elem);
  return !$elem.children().length && !$elem.text().match(/\S/);
}

and now you can use

$('#cartContent:space').remove();

which will remove the div if it is empty or contains only whitespace. Of course you can not only remove it but do anything you like, like

$('#cartContent:space').append('<p>It is empty</p>');

and you can use :not like this:

$('#cartContent:not(:space)').append('<p>It is not empty</p>');

I came out with this test that reliably did what I wanted and you can take it out of the plugin to use it as a standalone test:

This one will work for jQuery objects:

function testEmpty($elem) {
  return !$elem.children().length && !$elem.text().match(/\S/);
}

This one will work for DOM nodes:

function testEmpty(elem) {
  var $elem = jQuery(elem);
  return !$elem.children().length && !$elem.text().match(/\S/);
}

This is better than using .trim because the above code first tests if the tested element has any child elements and if it does it tries to find the first non-whitespace character and then stops, without the need to read or mutate the string if it has even one character that is not whitespace.

Hope it helps.

How to create PDF files in Python

fpdf is python (too). And often used. See PyPI / pip search. But maybe it was renamed from pyfpdf to fpdf. From features: PNG, GIF and JPG support (including transparency and alpha channel)

Java: Best way to iterate through a Collection (here ArrayList)

The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayLists, but will be really slow if you use a LinkedList.

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.

The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection in any way - which is the most common case).

annotation to make a private method public only for test classes

Consider using interfaces to expose the API methods, using factories or DI to publish the objects so the consumers know them only by the interface. The interface describes the published API. That way you can make whatever you want public on the implementation objects and the consumers of them see only those methods exposed through the interface.

Android: how to refresh ListView contents?

I'm doing the same thing using invalidateViews() and that works for me. If you want it to invalidate immediately you could try calling postInvalidate after calling invalidateViews.

Is ASCII code 7-bit or 8-bit?

On Linux man ascii says:

ASCII is the American Standard Code for Information Interchange. It is a 7-bit code.

How do I make a WPF TextBlock show my text on multiple lines?

This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.

    <Window.Resources>
        <local:WidthConverter x:Key="widthConverter"/>
    </Window.Resources>
    <Grid>
        <Grid>
            <StackPanel VerticalAlignment="Center" Orientation="Vertical" >
                <Viewbox Margin="100,0,100,0">
                    <TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
                </Viewbox>
                <TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
            </StackPanel>
        </Grid>
    </Grid>        

Converter

    [ValueConversion(typeof(double), typeof(double))]
    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double width = (double)value*.7;
            return width; // columnsCount;
        }

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

SQL Combine Two Columns in Select Statement

If your address1 = '123 Center St' and address2 = 'Apt 3B' then even if you combine and do a LIKE, you cannot search on searchstring as 'Center St 3B'. However, if your searchstring was 'Center St Apt', then you can do it using -

WHERE (address1 + ' ' + address2) LIKE '%searchstring%'

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

enter image description here

Summary:

  • PagingAndSortingRepository extends CrudRepository

  • JpaRepository extends PagingAndSortingRepository

The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.

The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.

Finally the JpaRepository add some more functionality that is specific to JPA.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

How do I write a "tab" in Python?

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.

private constructor

One common use is for template-typedef workaround classes like following:

template <class TObj>
class MyLibrariesSmartPointer
{
  MyLibrariesSmartPointer();
  public:
    typedef smart_ptr<TObj> type;
};

Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType> instead of MyLibrariesSmartPointer<SomeType>::type, which is desireable.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.

If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).

Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:

  1. Split your data into training and testing (80/20 is indeed a good starting point)
  2. Split the training data into training and validation (again, 80/20 is a fair split).
  3. Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set
  4. Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples
  5. To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your validation data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples

Return index of highest value in an array

My solution to get the higher key is as follows:

max(array_keys($values['Users']));

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

When you use a blade echo {{ $data }} it will automatically escape the output. It can only escape strings. In your data $data->ac is an array and $data is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }} (not sure why you have two nested arrays but I'm just following your data structure).

@foreach($data->ac['0'] as $link)
    <a href="{{ $link['url'] }}">This is a link</a>
@endforeach

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

What is the difference between a port and a socket?

A socket is a special type of file handle which is used by a process to request network services from the operating system. A socket address is the triple: {protocol, local-address, local-process} where the local process is identified by a port number.

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 12345}

A conversation is the communication link between two processes thus depicting an association between two. An association is the 5-tuple that completely specifies the two processes that comprise a connection: {protocol, local-address, local-process, foreign-address, foreign-process}

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 1500, 193.44.234.5, 21}

could be a valid association.

A half-association is either: {protocol, local-address, local-process}

or

{protocol, foreign-address, foreign-process}

which specify each half of a connection.

The half-association is also called a socket or a transport address. That is, a socket is an end point for communication that can be named and addressed in a network. The socket interface is one of several application programming interfaces (APIs) to the communication protocols. Designed to be a generic communication programming interface, it was first introduced by the 4.2BSD UNIX system. Although it has not been standardized, it has become a de facto industry standard.

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

How to display an unordered list in two columns?

This is the simplest way to do it. CSS only.

  1. add width to the ul element.
  2. add display:inline-block and width of the new column (should be less than half of the ul width).
_x000D_
_x000D_
ul.list {_x000D_
  width: 300px;  _x000D_
}_x000D_
_x000D_
ul.list li{_x000D_
  display:inline-block;_x000D_
  width: 100px;_x000D_
}
_x000D_
<ul class="list">_x000D_
    <li>A</li>_x000D_
    <li>B</li>_x000D_
    <li>C</li>_x000D_
    <li>D</li>_x000D_
    <li>E</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Difference between dict.clear() and assigning {} in Python

d = {} will create a new instance for d but all other references will still point to the old contents. d.clear() will reset the contents, but all references to the same instance will still be correct.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The source code provides some basic guidance:

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

For more detail, Kurtis' answer is dead on. I would just add: Don't log any personally identifiable or private information at INFO or above (WARN/ERROR). Otherwise, bug reports or anything else that includes logging may be polluted.

Angular 2 change event on every keypress

The secret event that keeps angular ngModel synchronous is the event call input. Hence the best answer to your question should be:

<input type="text" [(ngModel)]="mymodel" (input)="valuechange($event)" />
{{mymodel}}

Using fonts with Rails asset pipeline

I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:

src:url('fonts/footable.eot');

to look like this:

src:url('footable.eot');

It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:

var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));

Proper usage of .net MVC Html.CheckBoxFor

That isn't the proper syntax

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

The correct way

Although my proper suggestion would be to provide initialized model to your view with that particular boolean property initialized to true.

Property types

As per Asp.net MVC HtmlHelper extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the id.

Other helpers

There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

Note: checked is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.

How to set Java classpath in Linux?

You have to use ':' colon instead of ';' semicolon.

As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.

And the variable must be CLASSPATH not classpath.

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

ImportError: No module named PyQt4

I solved the same problem for my own program by installing python3-pyqt4.

I'm not using Python 3 but it still helped.

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

I think you may have installed the version of mongodb for the wrong system distro.

Take a look at how to install mongodb for ubuntu and debian:

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian/ http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

I had a similar problem, and what happened was that I was installing the ubuntu packages in debian

How do I redirect in expressjs while passing some context?

You can pass small bits of key/value pair data via the query string:

res.redirect('/?error=denied');

And javascript on the home page can access that and adjust its behavior accordingly.

Note that if you don't mind /category staying as the URL in the browser address bar, you can just render directly instead of redirecting. IMHO many times people use redirects because older web frameworks made directly responding difficult, but it's easy in express:

app.post('/category', function(req, res) {

  // Process the data received in req.body

  res.render('home.jade', {error: 'denied'});
});

As @Dropped.on.Caprica commented, using AJAX eliminates the URL changing concern.

How can I get System variable value in Java?

As mentioned by sombody above, restarting eclipse worked for me for the user defined environment variable. After I restart eclipse IDE, System.getenv() is picking up my environment variable.

Delete a row in Excel VBA

Something like this will do it:

Rows("12:12").Select
Selection.Delete

So in your code it would look like something like this:

Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete

Subtract minute from DateTime in SQL Server 2005

You want to use DATEADD, using a negative duration. e.g.

DATEADD(minute, -15, '2000-01-01 08:30:00') 

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

How to randomly select an item from a list?

I propose a script for removing randomly picked up items off a list until it is empty:

Maintain a set and remove randomly picked up element (with choice) until list is empty.

s=set(range(1,6))
import random

while len(s)>0:
  s.remove(random.choice(list(s)))
  print(s)

Three runs give three different answers:

>>> 
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>> 
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])

>>> 
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])

jQuery: how to trigger anchor link's click event

There's a difference in invoking the click event (does not do the redirect), and navigating to the href location.

Navigate:

 window.location = $('#myanchor').attr('href');

Open in new tab or window:

 window.open($('#myanchor').attr('href'));

invoke click event (call the javascript):

 $('#myanchor').click();

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

Test iOS app on device without apple developer program or jailbreak

The JailCoder references above point to a site that does not exist any more. Looks like you should use http://oneiros.altervista.org/jailcoder/ or https://www.facebook.com/jailcoder

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

Java naming convention for static final variables

These variables are constants, i.e. private static final whether they're named in all caps or not. The all-caps convention simply makes it more obvious that these variables are meant to be constants, but it isn't required. I've seen

private static final Logger log = Logger.getLogger(MyClass.class);

in lowercase before, and I'm fine with it because I know to only use the logger to log messages, but it does violate the convention. You could argue that naming it log is a sub-convention, I suppose. But in general, naming constants in uppercase isn't the One Right Way, but it is The Best Way.

Cannot authenticate into mongo, "auth fails"

In MongoDB 3.0, it now supports multiple authentication mechanisms.

  1. MongoDB Challenge and Response (SCRAM-SHA-1) - default in 3.0
  2. MongoDB Challenge and Response (MONGODB-CR) - previous default (< 3.0)

If you started with a new 3.0 database with new users created, they would have been created using SCRAM-SHA-1.

So you will need a driver capable of that authentication:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#considerations-scram-sha-1-drivers

If you had a database upgraded from 2.x with existing user data, they would still be using MONGODB-CR, and the user authentication database would have to be upgraded:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#upgrade-mongodb-cr-to-scram

Now, connecting to MongoDB 3.0 with users created with SCRAM-SHA-1 are required to specify the authentication database (via command line mongo client), and using other mechanisms if using a driver.

$> mongo -u USER -p PASSWORD --authenticationDatabase admin

In this case, the "admin" database, which is also the default will be used to authenticate.

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

jQuery function after .append

For images and other sources you can use that:

$(el).one('load', function(){
    // completed
}).each(function() {
    if (this.complete)
        $(this).load();
});

Java heap terminology: young, old and permanent generations?

What is the young generation?

The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.

What is the old generation?

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection

What is the permanent generation?

The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.

PermGen has been replaced with Metaspace since Java 8 release.

PermSize & MaxPermSize parameters will be ignored now

How does the three generations interact/relate to each other?

enter image description here

Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.

Have a look at summary diagram:

enter image description here

SQlite - Android - Foreign key syntax

Since I cannot comment, adding this note in addition to @jethro answer.

I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

private static final String TASK_TABLE_CREATE = "create table "
    + TASK_TABLE + " (" + TASK_ID
    + " integer primary key autoincrement, " + TASK_TITLE
    + " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";

Where I put the TASK_DATE_TIME after the foreign key line.

Converting a string to JSON object

var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);

Convert a PHP object to an associative array

Use:

function readObject($object) {
    $name = get_class ($object);
    $name = str_replace('\\', "\\\\", $name); // Outcomment this line, if you don't use
                                              // class namespaces approach in your project
    $raw = (array)$object;

    $attributes = array();
    foreach ($raw as $attr => $val) {
        $attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val;
    }
    return $attributes;
}

It returns an array without special characters and class names.

How do I exit a while loop in Java?

if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.

package com.java.demo;

/**
 * @author Ankit Sood Apr 20, 2017
 */
public class Demo {

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        /* Initialize while loop */
        while (true) {
            /*
            * You have to declare some condition to stop while loop 

            * In which situation or condition you want to terminate while loop.
            * conditions like: if(condition){break}, if(var==10){break} etc... 
            */

            /* break keyword is for stop while loop */

            break;
        }
    }
}

How to link to specific line number on github

For a line in a pull request.

https://github.com/foo/bar/pull/90/files#diff-ce6bf647d5a531e54ef0502c7fe799deR27
https://github.com/foo/bar/pull/
90 <- PR number
/files#diff-
ce6bf647d5a531e54ef0502c7fe799de <- MD5 has of file name from repo root
R <- Which side of the diff to reference (merge-base or head). Can be L or R.
27 <- Line number

This will take you to a line as long as L and R are correct. I am not sure if there is a way to visit L OR R. I.e If the PR adds a line you must use R. If it removes a line you must use L.

From: Generate line pointer URL into Github Pull Request

Get yesterday's date in bash on Linux, DST-safe

date -d "yesterday" '+%Y-%m-%d'

To use this later:

date=$(date -d "yesterday" '+%Y-%m-%d')

How to delete an item in a list if it exists?

Adding this answer for completeness, though it's only usable under certain conditions.

If you have very large lists, removing from the end of the list avoids CPython internals having to memmove, for situations where you can re-order the list. It gives a performance gain to remove from the end of the list, since it won't need to memmove every item after the one your removing - back one step (1).
For one-off removals the performance difference may be acceptable, but if you have a large list and need to remove many items - you will likely notice a performance hit.

Although admittedly, in these cases, doing a full list search is likely to be a performance bottleneck too, unless items are mostly at the front of the list.

This method can be used for more efficient removal,
as long as re-ordering the list is acceptable. (2)

def remove_unordered(ls, item):
    i = ls.index(item)
    ls[-1], ls[i] = ls[i], ls[-1]
    ls.pop()

You may want to avoid raising an error when the item isn't in the list.

def remove_unordered_test(ls, item):
    try:
        i = ls.index(item)
    except ValueError:
        return False
    ls[-1], ls[i] = ls[i], ls[-1]
    ls.pop()
    return True

  1. While I tested this with CPython, its quite likely most/all other Python implementations use an array to store lists internally. So unless they use a sophisticated data structure designed for efficient list re-sizing, they likely have the same performance characteristic.

A simple way to test this, compare the speed difference from removing from the front of the list with removing the last element:

python -m timeit 'a = [0] * 100000' 'while a: a.remove(0)'

With:

python -m timeit 'a = [0] * 100000' 'while a: a.pop()'

(gives an order of magnitude speed difference where the second example is faster with CPython and PyPy).

  1. In this case you might consider using a set, especially if the list isn't meant to store duplicates.
    In practice though you may need to store mutable data which can't be added to a set. Also check on btree's if the data can be ordered.

Is there a CSS selector for the first direct child only?

Use div.section > div.

Better yet, use an <h1> tag for the heading and div.section h1 in your CSS, so as to support older browsers (that don't know about the >) and keep your markup semantic.

A simple algorithm for polygon intersection

I have no very simple solution, but here are the main steps for the real algorithm:

  1. Do a custom double linked list for the polygon vertices and edges. Using std::list won't do because you must swap next and previous pointers/offsets yourself for a special operation on the nodes. This is the only way to have simple code, and this will give good performance.
  2. Find the intersection points by comparing each pair of edges. Note that comparing each pair of edge will give O(N²) time, but improving the algorithm to O(N·logN) will be easy afterwards. For some pair of edges (say a?b and c?d), the intersection point is found by using the parameter (from 0 to 1) on edge a?b, which is given by t?=d0/(d0-d1), where d0 is (c-a)×(b-a) and d1 is (d-a)×(b-a). × is the 2D cross product such as p×q=p?·q?-p?·q?. After having found t?, finding the intersection point is using it as a linear interpolation parameter on segment a?b: P=a+t?(b-a)
  3. Split each edge adding vertices (and nodes in your linked list) where the segments intersect.
  4. Then you must cross the nodes at the intersection points. This is the operation for which you needed to do a custom double linked list. You must swap some pair of next pointers (and update the previous pointers accordingly).

Then you have the raw result of the polygon intersection resolving algorithm. Normally, you will want to select some region according to the winding number of each region. Search for polygon winding number for an explanation on this.

If you want to make a O(N·logN) algorithm out of this O(N²) one, you must do exactly the same thing except that you do it inside of a line sweep algorithm. Look for Bentley Ottman algorithm. The inner algorithm will be the same, with the only difference that you will have a reduced number of edges to compare, inside of the loop.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Why do package names often begin with "com"

Wikipedia, of all places, actually discusses this.

The idea is to make sure all package names are unique world-wide, by having authors use a variant of a DNS name they own to name the package. For example, the owners of the domain name joda.org created a number of packages whose names begin with org.joda, for example:

  • org.joda.time
  • org.joda.time.base
  • org.joda.time.chrono
  • org.joda.time.convert
  • org.joda.time.field
  • org.joda.time.format

Android studio: emulator is running but not showing up in Run App "choose a running device"

Wipe the data of your Android virtual Device and then start the emulator. Works for me.

How to read a file from jar in Java?

Just for completeness, there has recently been a question on the Jython mailinglist where one of the answers referred to this thread.

The question was how to call a Python script that is contained in a .jar file from within Jython, the suggested answer is as follows (with "InputStream" as explained in one of the answers above:

PythonInterpreter.execfile(InputStream)

How to clear/delete the contents of a Tkinter Text widget?

I think this:

text.delete("1.0", tkinter.END)

Or if you did from tkinter import *

text.delete("1.0", END)

That should work

DATEDIFF function in Oracle

We can directly subtract dates to get difference in Days.

    SET SERVEROUTPUT ON ;
    DECLARE
        V_VAR NUMBER;
    BEGIN
         V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
         DBMS_OUTPUT.PUT_LINE(V_VAR);
    END;

Specify a Root Path of your HTML directory for script links?

Use two periods before /, example:

../style.css

Making a Sass mixin with optional arguments

I am new to css compilers, hope this helps,

        @mixin positionStyle($params...){

            $temp:nth($params,1);
            @if $temp != null{
            position:$temp;
            }

             $temp:nth($params,2);
            @if $temp != null{
            top:$temp;
            }

             $temp:nth($params,3);
            @if $temp != null{
            right:$temp;
            }

             $temp:nth($params,4);
            @if $temp != null{
            bottom:$temp;
            }

            $temp:nth($params,5);
            @if $temp != null{
            left:$temp;
            }

    .someClass{
    @include positionStyle(absolute,30px,5px,null,null);
    }

//output

.someClass{
position:absolute;
 top: 30px;
 right: 5px;
}

Installation failed with message Invalid File

Click Build tab ---> Clean Project

Click Build tab ---> Build APK

Run.

How can I add an item to a ListBox in C# and WinForms?

If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):

for (int x = 1; x <= 50; x++)
{
   list.Items.Add(x);
}

You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:

listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });

How would I create a UIAlertView in Swift?

try This. Put Bellow Code In Button.

let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)

Replace \n with <br />

thatLine = thatLine.replace('\n', '<br />')

str.replace() returns a copy of the string, it doesn't modify the string you pass in.

Easiest way to open a download window without navigating away from the page

7 years have passed and I don't know whether it works for IE6 or not, but this prompts OpenFileDialog in FF and Chrome.

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

How to handle the `onKeyPress` event in ReactJS?

var Test = React.createClass({
     add: function(event){
         if(event.key === 'Enter'){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={(event) => this.add(event)}/>    
          </div>
        );
     }
});

How to add content to html body using JS?

I think if you want to add content directly to the body, the best way is:

document.body.innerHTML = document.body.innerHTML + "bla bla";

To replace it, use:

document.body.innerHTML = "bla bla";

How do I add space between two variables after a print in Python

This is a stupid/hacky way

print count,    
print conv

LINQ Join with Multiple Conditions in On Clause

You just need to name the anonymous property the same on both sides

on new { t1.ProjectID, SecondProperty = true } equals 
   new { t2.ProjectID, SecondProperty = t2.Completed } into j1

Based on the comments of @svick, here is another implementation that might make more sense:

from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
                .DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }

Replace \n with actual new line in Sublime Text

Use Find > Replace, or (Ctrl+H), to open the Find What/Replace With Window, and use Ctrl+Enter to indicate a new line in the Replace With inputbox.

Textarea to resize based on content length

You may also try contenteditable attribute onto a normal p or div. Not really a textarea but it will auto-resize without script.

_x000D_
_x000D_
.divtext {
    border: ridge 2px;
    padding: 5px;
    width: 20em;
    min-height: 5em;
    overflow: auto;
}
_x000D_
<div class="divtext" contentEditable>Hello World</div>
_x000D_
_x000D_
_x000D_

"Cannot instantiate the type..."

Queue is an Interface not a class.

Replace console output in Python

Added a little bit more functionality to the example of Aravind Voggu:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent*bar_length) - 1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))
        sys.stdout.flush()
        if value == endvalue:     
             sys.stdout.write('\n\n')

Now you are able to generate multiple progressbars without replacing the previous one.

I've also added name as a value with a fixed width.

For two loops and two times the use of progressBar() the result will look like:

progress bar animation

Root user/sudo equivalent in Cygwin?

Try:

chmod -R ug+rwx <dir>

where <dir> is the directory on which you want to change permissions.

How to make a JFrame Modal in Swing java

What I've done in this case is, in the primary jframe that I want to keep visible (for example, a menu frame), I deselect the option focusableWindowState in the property window so It will be FALSE. Once that is done, the jframes I call don´t lose focus until I close them.

How to sort multidimensional array by column?

You can use the sorted method with a key.

sorted(a, key=lambda x : x[1])

C: socket connection timeout

The two socket options SO_RCVTIMEO and SO_SNDTIMEO have no effect on connect. Below is a link to the screenshot which includes this explanation, here I am just briefing it. The apt way of implementing timeouts with connect are using signal or select or poll.

Signals

connect can be interrupted by a self generated signal SIGALRM by using syscall (wrapper) alarm. But, a signal disposition should be installed for the same signal otherwise the program would be terminated. The code goes like this...

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<errno.h>

static void signal_handler(int signo)
{
    return; // Do nothing just interrupt.
}

int main()
{
    /* Register signal handler */

    struct sigaction act, oact;

    act.sa_handler = signal_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    if(sigaction(SIGALRM, &act, &oact) < 0)  // Error registering signal handler.
    {
        fprintf(stderr, "Error registering signal disposition\n");
        exit(1);
    }

    /* Prepare your socket and sockaddr structures */

    int sockfd;
    struct sockaddr* servaddr;

    /* Implementing timeout connect */

    int sec = 30;

    if(alarm(sec) != 0)
        fprintf(stderr, "Already timer was set\n");

    if(connect(sockfd, servaddr, sizeof(struct sockaddr)) < 0)
    {
        if(errno == EINTR)
            fprintf(stderr, "Connect timeout\n");
        else
            fprintf(stderr, "Connect failed\n");

        close(sockfd);

        exit(1);
    }

    alarm(0);  /* turn off the alarm */

    sigaction(SIGALRM, &oact, NULL);  /* Restore the default actions of SIGALRM */

    /* Use socket */


    /* End program */

    close(sockfd);
    return 0;
}

Select or Poll

As already some users provided nice explanation on how to use select to achieve connect timeout, it would not be necessary for me to reiterate the same. poll can be used in the same way. However, there are few mistakes that are common in all of the answers, which I would like to address.

  • Even though socket is non-blocking, if the server to which we are connecting is on the same local machine, connect may return with success. So it is advised to check the return value of connect before calling select.

  • Berkeley-derived implementations (and POSIX) have the following rules for non-blocking sockets and connect.

    1) When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).

    2) When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2).

So the code should handle these cases, here I just code the necessary modifications.

/* All the code stays */

/* Modifications at connect */

int conn_ret = connect(sockfd, servaddr, sizeof(struct sockdaddr));

if(conn_ret == 0)
    goto done;

/* Modifications at select */

int sec = 30;
for( ; ; )
{
    struct timeval timeo;
    timeo.tv_sec = sec;
    timeo.tv_usec = 0;

    fd_set wr_set, rd_set;
    FDZERO(&wr_set);
    FD_SET(sockfd, &wr_set);
    rd_set = wr_set;
    int sl_ret = select(sockfd + 1, &rd_set, &wr_set, NULL, &timeo);

    /* All the code stays */
}


done:

    /* Use your socket */

Text from Unix Network Programming Volume 1

OnClickListener in Android Studio

you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:

 Button button;  //<< declare here..

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.standingsButton); //<< initialize here
         // set OnClickListener for Button here
        button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
      });
    }

how to show lines in common (reverse diff)?

Easiest way to do is :

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2

Files are not necessary to be sorted.

Which maven dependencies to include for spring 3.0?

You can try this

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>`

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

How can I determine browser window size on server side C#

Here how I solved it using Cookies:

First of all, inside the website main script:

var browserWindowSize = getCookie("_browserWindowSize");
var newSize = $(window).width() + "," + $(window).height();
var reloadForCookieRefresh = false;

if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) {
    setCookie("_browserWindowSize", newSize, 30);
    reloadForCookieRefresh = true;
}

if (reloadForCookieRefresh)
    window.location.reload();

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

And inside MVC action filter:

public class SetCurrentRequestDataFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // currentRequestService is registered per web request using IoC
        var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();

        if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize"))
        {
            var browserWindowSize = filterContext.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(',');
            currentRequestService.browserWindowWidth = int.Parse(browserWindowSize[0]);
            currentRequestService.browserWindowHeight = int.Parse(browserWindowSize[1]);
        }

    }
}

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

ActionBarActivity: cannot be resolved to a type

It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..

in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library

follow this tutorial in the docs

http://developer.android.com/tools/support-library/setup.html

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

How to check if IsNumeric

Other answers have suggested using TryParse, which might fit your needs, but the safest way to provide the functionality of the IsNumeric function is to reference the VB library and use the IsNumeric function.

IsNumeric is more flexible than TryParse. For example, IsNumeric returns true for the string "$100", while the TryParse methods all return false.

To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information class, so assuming you have using Microsoft.VisualBasic;, you can do this:

if (Information.IsNumeric(txtMyText.Text.Trim())) //...

How can I copy a conditional formatting from one document to another?

You can also copy a cell which contains the conditional formatting and then select the range (of destination document -or page-) where you want the conditional format to be applied and select "paste special" > "paste only conditional formatting"

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

How do I change Bootstrap 3 column order on mobile layout?

This is quite easy with jQuery using insertAfter() or insertBefore():

<div class="left">content</div>
<div class="right">sidebar</div>

_x000D_
_x000D_
<script>
$('.right').insertBefore('left');
</script>
_x000D_
_x000D_
_x000D_

If you want to to set o condition for mobile devices you can make it like this:

_x000D_
_x000D_
<script>
  var $iW = $(window).innerWidth();
  if ($iW < 992){
     $('.right').insertBefore('.left');
  }else{
     $('.right').insertAfter('.left');
  }
</script>
_x000D_
_x000D_
_x000D_

example https://jsfiddle.net/w9n27k23/

Is there a CSS selector by class prefix?

CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

(looks like it's actually at 'recommendation' status for 2.1 and 3)


Here's an outline of how I *think it works:

  • [ ] : is the container for complex selectors if you will...
  • class : 'class' is the attribute you are looking at in this case.
  • * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.
  • test- : the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)

So, for example:

[class*='test-'] {
  color: red;
}

You could be more specific if you have good reason, with the element too

ul[class*='test-'] > li { ... }

I've tried to find edge cases, but I see no need to use a combination of ^ and * - as * gets everything...

example: http://codepen.io/sheriffderek/pen/MaaBwp

http://caniuse.com/#feat=css-sel2

Everything above IE6 will happily obey. : )

note that:

[class] { ... }

Will select anything with a class...

How to insert text at beginning of a multi-line selection in vi/Vim

This replaces the beginning of each line with "//":

:%s!^!//!

This replaces the beginning of each selected line (use visual mode to select) with "//":

:'<,'>s!^!//!

Note that gv (in normal mode) restores the last visual selection, this comes in handy from time to time.

Spark: subtract two DataFrames

For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.

How to access pandas groupby dataframe by key

Rather than

gb.get_group('foo')

I prefer using gb.groups

df.loc[gb.groups['foo']]

Because in this way you can choose multiple columns as well. for example:

df.loc[gb.groups['foo'],('A','B')]

Remove row lines in twitter bootstrap

In Bootstrap 3 I've added a table-no-border class

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td {
  border-top: none; 
}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

What works for me was right-click on the .ps1 file and then properties. Click the "UNBLOCK" button. Works great fir me after spending hours trying to change the policies.

Sorting Values of Set

You're using the default comparator to sort a Set<String>. In this case, that means lexicographic order. Lexicographically, "12" comes before "15", comes before "5".

Either use a Set<Integer>:

Set<Integer> set=new HashSet<Integer>();
set.add(12);
set.add(15);
set.add(5);

Or use a different comparator:

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.parseInt(a) - Integer.parseInt(b);
    }
});

How permission can be checked at runtime without throwing SecurityException?

You can use Context.checkCallingorSelfPermission() function for this. Here is an example:

private boolean checkWriteExternalPermission()
{
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);            
}

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

Counter increment in Bash loop not working

I think this single awk call is equivalent to your grep|grep|awk|awk pipeline: please test it. Your last awk command appears to change nothing at all.

The problem with COUNTER is that the while loop is running in a subshell, so any changes to the variable vanish when the subshell exits. You need to access the value of COUNTER in that same subshell. Or take @DennisWilliamson's advice, use a process substitution, and avoid the subshell altogether.

awk '
  /GET \/log_/ && /upstream timed out/ {
    split($0, a, ", ")
    split(a[2] FS a[4] FS $0, b)
    print "http://example.com" b[5] "&ip=" b[2] "&date=" b[7] "&time=" b[8] "&end=1"
  }
' | {
    while read WFY_URL
    do
        echo $WFY_URL #Some more action
        (( COUNTER++ ))
    done
    echo $COUNTER
}

How to Decrease Image Brightness in CSS

With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.

See the following code for more details.

To make an image gray:

img {
 -webkit-filter: grayscale(100%);
 -moz-filter: grayscale(100%);
}

To give a sepia look:

    img {
     -webkit-filter: sepia(100%);
    -moz-filter: sepia(100%);
}

To adjust brightness:

 img {
     -webkit-filter: brightness(50%);
     -moz-filter: brightness(50%);  
  }

To adjust contrast:

 img {
     -webkit-filter: contrast(200%);
     -moz-filter: contrast(200%);    
}

To Blur an image:

    img {
     -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
  }

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

How to keep a VMWare VM's clock in sync?

If your host time is correct, you can set the following .vmx configuration file option to enable periodic synchronization:

tools.syncTime = true

By default, this synchronizes the time every minute. To change the periodic rate, set the following option to the desired synch time in seconds:

tools.syncTime.period = 60

For this to work you need to have VMWare tools installed in your guest OS.

See http://www.vmware.com/pdf/vmware_timekeeping.pdf for more information

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You must declare the reportfile as variable for console.

Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....

Example: for batch/console

cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile

Exemple Javascript:

var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;

You can change the dir and filename how ever you want.

Frank from Berlin

How to change the CHARACTER SET (and COLLATION) throughout a database?

Beware that in Mysql, the utf8 character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4 data type, and utf8mb4_bin or utf8mb4_general_ci in Mysql.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

how to create inline style with :before and :after

If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style> element right before your content.

<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>

Example use case with PHP and some (wordpress inspired) dummy functions:

<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.

Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

How do you see the entire command history in interactive Python?

This should give you the commands printed out in separate lines:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

yii2 hidden input value

you can also do this

$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);

this is a better option if you set value on controller

$model = new SomeModelName();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
    return $this->redirect(['view', 'id' => $model->group_id]);
 } else {
    $model->hidden1 = 'your value';
    return $this->render('create', [
        'model' => $model,
    ]);
 }

How can I remove a character from a string using JavaScript?

For global replacement of '/r', this code worked for me.

mystring = mystring.replace(/\/r/g,'');

convert a JavaScript string variable to decimal/money

This works:

var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);

How to prevent line-break in a column of a table cell (not a single cell)?

Put non-breaking spaces in your text instead of normal spaces. On Ubuntu I do this with (Compose Key)-space-space.

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

How to get the unix timestamp in C#

I've spliced together the most elegant approaches to this utility method:

public static class Ux {
    public static decimal ToUnixTimestampSecs(this DateTime date) => ToUnixTimestampTicks(date) / (decimal) TimeSpan.TicksPerSecond;
    public static long ToUnixTimestampTicks(this DateTime date) => date.ToUniversalTime().Ticks - UnixEpochTicks;
    private static readonly long UnixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
}

How to get the file name from a full path using JavaScript?

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings):

return fullPath.replace(/^.*(\\|\/|\:)/, '');

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Let's revisit key phases of Mapreduce program.

The map phase is done by mappers. Mappers run on unsorted input key/values pairs. Each mapper emits zero, one, or multiple output key/value pairs for each input key/value pairs.

The combine phase is done by combiners. The combiner should combine key/value pairs with the same key. Each combiner may run zero, once, or multiple times.

The shuffle and sort phase is done by the framework. Data from all mappers are grouped by the key, split among reducers and sorted by the key. Each reducer obtains all values associated with the same key. The programmer may supply custom compare functions for sorting and a partitioner for data split.

The partitioner decides which reducer will get a particular key value pair.

The reducer obtains sorted key/[values list] pairs, sorted by the key. The value list contains all values with the same key produced by mappers. Each reducer emits zero, one or multiple output key/value pairs for each input key/value pair.

Have a look at this javacodegeeks article by Maria Jurcovicova and mssqltips article by Datta for a better understanding

Below is the image from safaribooksonline article

enter image description here

Sound alarm when code finishes

See: Python Sound ("Bell")
This helped me when i wanted to do the same.
All credits go to gbc

Quote:

Have you tried :

import sys
sys.stdout.write('\a')
sys.stdout.flush()

That works for me here on Mac OS 10.5

Actually, I think your original attempt works also with a little modification:

print('\a')

(You just need the single quotes around the character sequence).

How to get TimeZone from android mobile?

TimeZone timeZone = TimeZone.getDefault(); 
timeZone.getID();

It will print like

Asia/Kolkata

Credit card expiration dates - Inclusive or exclusive?

In your example a credit card is expired on 6/2008.

Without knowing what you are doing I cannot say definitively you should not be validating ahead of time but be aware that sometimes business rules defy all logic.

For example, where I used to work they often did not process a card at all or would continue on transaction failure simply so they could contact the customer and get a different card.

Reading a key from the Web.Config using ConfigurationManager

I found this solution to be quite helpful. It uses C# 4.0 DynamicObject to wrap the ConfigurationManager. So instead of accessing values like this:

 WebConfigurationManager.AppSettings["PFUserName"]

you access them as a property:

dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);  

EDIT: Adding code snippet in case link becomes stale:

public class AppSettingsWrapper : DynamicObject
{
     private NameValueCollection _items;

    public AppSettingsWrapper()
    {
        _items = ConfigurationManager.AppSettings;
    }

     public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _items[binder.Name];
        return result != null;
    }
}

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

Github Push Error: RPC failed; result=22, HTTP code = 413

Need to change remote url to ssh or https

git remote set-url origin [email protected]:laravel/laravel.git

or

git remote set-url origin https://github.com/laravel/laravel.git

Hope, this will help :)

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

cast or convert a float to nvarchar?

DECLARE @MyFloat [float]

SET @MyFloat = 1000109360.050

SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')

Convert string to hex-string in C#

few Unicode alternatives

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

Computed / calculated / virtual / derived columns in PostgreSQL

Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.

STORED generated columns are introduced with Postgres 12. Trivial example:

CREATE TABLE tbl (
  int1    int
, int2    int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);

db<>fiddle here

VIRTUAL generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .

Related:


Until then, you can emulate VIRTUAL generated columns with a function using attribute notation (tbl.col) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:

The expression (looking like a column) is not included in a SELECT * FROM tbl, though. You always have to list it explicitly.

Can also be supported with a matching expression index - provided the function is IMMUTABLE. Like:

CREATE FUNCTION col(tbl) ... AS ...  -- your computed expression here
CREATE INDEX ON tbl(col(tbl));

Alternatives

Alternatively, you can implement similar functionality with a VIEW, optionally coupled with expression indexes. Then SELECT * can include the generated column.

"Persisted" (STORED) computed columns can be implemented with triggers in a functionally identical way.

Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.

What is the difference between null and undefined in JavaScript?

In JavasSript there are 5 primitive data types String , Number , Boolean , null and undefined. I will try to explain with some simple example

lets say we have a simple function

 function test(a) {

     if(a == null){
        alert("a is null");
     } else {
        alert("The value of a is " + a);
     }
  }

also in above function if(a == null) is same as if(!a)

now when we call this function without passing the parameter a

   test(); it will alert "a is null";
   test(4); it will alert "The value of a is " + 4;

also

var a;
alert(typeof a); 

this will give undefined; we have declared a variable but we have not asigned any value to this variable; but if we write

var a = null;
alert(typeof a); will give alert as object

so null is an object. in a way we have assigned a value null to 'a'

Send POST request with JSON data using Volley

I know that this thread is quite old, but I had this problem and I came up with a cool solution which can be very useful to many because it corrects/extended the Volley library on many aspects.

I spotted some not supported-out-of-box Volley features:

  • This JSONObjectRequest is not perfect: you have to expect a JSON at the end (see the Response.Listener<JSONObject>).
  • What about Empty Responses (just with a 200 status)?
  • What do I do if I want directly my POJO from the ResponseListener?

I more or less compiled a lot of solutions in a big generic class in order to have a solution for all the problem I quoted.

  /**
  * Created by laurentmeyer on 25/07/15.
  */
 public class GenericRequest<T> extends JsonRequest<T> {

     private final Gson gson = new Gson();
     private final Class<T> clazz;
     private final Map<String, String> headers;
     // Used for request which do not return anything from the server
     private boolean muteRequest = false;

     /**
      * Basically, this is the constructor which is called by the others.
      * It allows you to send an object of type A to the server and expect a JSON representing a object of type B.
      * The problem with the #JsonObjectRequest is that you expect a JSON at the end.
      * We can do better than that, we can directly receive our POJO.
      * That's what this class does.
      *
      * @param method:        HTTP Method
      * @param classtype:     Classtype to parse the JSON coming from the server
      * @param url:           url to be called
      * @param requestBody:   The body being sent
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param headers:       Added headers
      */
     private GenericRequest(int method, Class<T> classtype, String url, String requestBody,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
         super(method, url, requestBody, listener,
                 errorListener);
         clazz = classtype;
         this.headers = headers;
         configureRequest();
     }

     /**
      * Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and not muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param toBeSent:      Object which will be transformed in JSON via Gson and sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param headers:       Added headers
      */
     public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
         this(method, classtype, url, new Gson().toJson(toBeSent), listener,
                 errorListener, headers);
     }

     /**
      * Method to be called if you want to send some objects to your server via body in JSON of the request (without header and not muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param toBeSent:      Object which will be transformed in JSON via Gson and sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      */
     public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
                           Response.Listener<T> listener, Response.ErrorListener errorListener) {
         this(method, classtype, url, new Gson().toJson(toBeSent), listener,
                 errorListener, new HashMap<String, String>());
     }

     /**
      * Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param requestBody:   String to be sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      */
     public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
                           Response.Listener<T> listener, Response.ErrorListener errorListener) {
         this(method, classtype, url, requestBody, listener,
                 errorListener, new HashMap<String, String>());
     }

     /**
      * Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (Without header)
      *
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      */
     public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener) {
         this(Request.Method.GET, url, classtype, "", listener, errorListener);
     }

     /**
      * Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (With headers)
      *
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param headers:       Added headers
      */
     public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
         this(Request.Method.GET, classtype, url, "", listener, errorListener, headers);
     }

     /**
      * Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param toBeSent:      Object which will be transformed in JSON via Gson and sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param headers:       Added headers
      * @param mute:          Muted (put it to true, to make sense)
      */
     public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers, boolean mute) {
         this(method, classtype, url, new Gson().toJson(toBeSent), listener,
                 errorListener, headers);
         this.muteRequest = mute;
     }

     /**
      * Method to be called if you want to send some objects to your server via body in JSON of the request (without header and muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param toBeSent:      Object which will be transformed in JSON via Gson and sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param mute:          Muted (put it to true, to make sense)
      */
     public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
         this(method, classtype, url, new Gson().toJson(toBeSent), listener,
                 errorListener, new HashMap<String, String>());
         this.muteRequest = mute;

     }

     /**
      * Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
      *
      * @param method:        HTTP Method
      * @param url:           URL to be called
      * @param classtype:     Classtype to parse the JSON returned from the server
      * @param requestBody:   String to be sent to the server
      * @param listener:      Listener of the request
      * @param errorListener: Error handler of the request
      * @param mute:          Muted (put it to true, to make sense)
      */
     public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
         this(method, classtype, url, requestBody, listener,
                 errorListener, new HashMap<String, String>());
         this.muteRequest = mute;

     }


     @Override
     protected Response<T> parseNetworkResponse(NetworkResponse response) {
         // The magic of the mute request happens here
         if (muteRequest) {
             if (response.statusCode >= 200 && response.statusCode <= 299) {
                 // If the status is correct, we return a success but with a null object, because the server didn't return anything
                 return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
             }
         } else {
             try {
                 // If it's not muted; we just need to create our POJO from the returned JSON and handle correctly the errors
                 String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                 T parsedObject = gson.fromJson(json, clazz);
                 return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response));
             } catch (UnsupportedEncodingException e) {
                 return Response.error(new ParseError(e));
             } catch (JsonSyntaxException e) {
                 return Response.error(new ParseError(e));
             }
         }
         return null;
     }

     @Override
     public Map<String, String> getHeaders() throws AuthFailureError {
         return headers != null ? headers : super.getHeaders();
     }

     private void configureRequest() {
         // Set retry policy
         // Add headers, for auth for example
         // ...
     }
 }

It could seem a bit overkill but it's pretty cool to have all these constructors because you have all the cases:

(The main constructor wasn't meant to be used directly although it's, of course, possible).

  1. Request with response parsed to POJO / Headers manually set / POJO to Send
  2. Request with response parsed to POJO / POJO to Send
  3. Request with response parsed to POJO / String to Send
  4. Request with response parsed to POJO (GET)
  5. Request with response parsed to POJO (GET) / Headers manually set
  6. Request with no response (200 - Empty Body) / Headers manually set / POJO to Send
  7. Request with no response (200 - Empty Body) / POJO to Send
  8. Request with no response (200 - Empty Body) / String to Send

Of course, in order that it works, you have to have Google's GSON Lib; just add:

compile 'com.google.code.gson:gson:x.y.z'

to your dependencies (current version is 2.3.1).

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

Search an array for matching attribute

for (x in restaurants) {
    if (restaurants[x].restaurant.food == 'chicken') {
        return restaurants[x].restaurant.name;
    }
}

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

django - get() returned more than one topic

I had same problem and solution was obj = ClassName.objects.filter()

How to join multiple collections with $lookup in mongodb

According to the documentation, $lookup can join only one external collection.

What you could do is to combine userInfo and userRole in one collection, as provided example is based on relational DB schema. Mongo is noSQL database - and this require different approach for document management.

Please find below 2-step query, which combines userInfo with userRole - creating new temporary collection used in last query to display combined data. In last query there is an option to use $out and create new collection with merged data for later use.

create collections

db.sivaUser.insert(
{    
    "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
        "email" : "[email protected]",
        "userId" : "AD",
        "userName" : "admin"
})

//"userinfo"
db.sivaUserInfo.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000"
})

//"userrole"
db.sivaUserRole.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "role" : "admin"
})

"join" them all :-)

db.sivaUserInfo.aggregate([
    {$lookup:
        {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind:"$userRole"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :"$userRole.role"
        }
    },
    {
        $out:"sivaUserTmp"
    }
])


db.sivaUserTmp.aggregate([
    {$lookup:
        {
           from: "sivaUser",
           localField: "userId",
           foreignField: "userId",
           as: "user"
        }
    },
    {
        $unwind:"$user"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :1,
            "email" : "$user.email",
            "userName" : "$user.userName"
        }
    }
])

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

Convert a space delimited string to list

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

Get current time as formatted string in Go?

Use the time.Now() function and the time.Format() method.

t := time.Now()
fmt.Println(t.Format("20060102150405"))

prints out 20110504111515, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.

You can use time.Now().UTC() if you'd rather have UTC than your local time zone.

What's the difference between .NET Core, .NET Framework, and Xamarin?

.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore. enter image description here

Center an element in Bootstrap 4 Navbar

from the docs

Navbars may contain bits of text with the help of .navbar-text. This class adjusts vertical alignment and horizontal spacing for strings of text.

i applied the .navbar-text class to my <li> element, so the result is

<li class="nav-item navbar-text">

this centers the links vertically with respect to my navbar-brand img

How to list all `env` properties within jenkins pipeline job?

You can get all variables from your jenkins instance. Just visit:

  • ${jenkins_host}/env-vars.html
  • ${jenkins_host}/pipeline-syntax/globals

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

Change old commit message on Git

Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.

Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.

So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.

From latest master:

git checkout -b new-branch

Then

git merge --squash problem-branch
git commit -m "new message" 

Referece: https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch

How to launch an application from a browser?

I achieved the same thing using a local web server and PHP. I used a script containing shell_exec to launch an application locally.

Alternatively, you could do something like this:

<a href="file://C:/Windows/notepad.exe">Notepad</a>

How do I run Google Chrome as root?

It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome. It simply prints Aborted and ends (Chrome 48 on Ubuntu 12.04).

You need actually to run it as a non-root user. This you can do with

gksu -wu chrome-user google-chrome

where chrome-user is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome.

BTW, the old hack of changing all occurrences of geteuid to getppid in the chrome binary no longer works.