Programs & Examples On #Overuse

Place API key in Headers or URL

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

What are the best use cases for Akka framework

We use Akka in several projects at work, the most interesting of which is related to vehicle crash repair. Primarily in the UK but now expanding to the US, Asia, Australasia and Europe. We use actors to ensure that crash repair information is provided realtime to enable the safe and cost effective repair of vehicles.

The question with Akka is really more 'what can't you do with Akka'. Its ability to integrate with powerful frameworks, its powerful abstraction and all of the fault tolerance aspects make it a very comprehensive toolkit.

jQuery vs. javascript?

"I actually tried to had a normal objective discusssion over pros and cons of 1., using framework over pure javascript and 2., jquery vs. others, since jQuery seems to be easiest to work with with quickest learning curve."

Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.

"Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?"

Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.

Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.

What is the difference between a process and a thread?

  • Every process is a thread (primary thread).
  • But every thread is not a process. It is a part(entity) of a process.

HtmlEncode from Class Library

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

Automatically create requirements.txt

In my case, I use Anaconda, so running the following command from conda terminal inside my environment solved it, and created this requirements txt file for me automatically:

conda list -e > requirements.txt

This was taken from this Github link pratos/condaenv.txt

If an error been seen, and you are using anaconda, try to use the .yml option:

conda env export > <environment-name>.yml

For other person to use the environment...Or if you are creating a new enviroment on other machine: conda env create -f .yml

.yml option been found here

How can I encode a string to Base64 in Swift?

SwiftyBase64 (full disclosure: I wrote it) is a native Swift Base64 encoding (no decoding library. With it, you can encode standard Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)

or URL and Filename Safe Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)

set height of imageview as matchparent programmatically

You can try this incase you would like to match parent. The dimensions arrangement is width and height inorder

web = new WebView(this);
        web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

Is there a simple way that I can sort characters in a string in alphabetical order

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

How to make pylab.savefig() save image for 'maximized' window instead of default size

I think you need to specify a different resolution when saving the figure to a file:

fig = matplotlib.pyplot.figure()
# generate your plot
fig.savefig("myfig.png",dpi=600)

Specifying a large dpi value should have a similar effect as maximizing the GUI window.

Putty: Getting Server refused our key Error

Oh my God I spent days trying to fix this. So here is what worked for me. I went back to the root fold like this: cd /root/ mkdir .ssh cd .ssh chmod 700 .ssh nano -w authorized_keys service ssh restart So I used root to logging via Putty and it worked. so try to do the same with the user you want to use in putty.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Linux command line howto accept pairing for bluetooth device without pin

Try setting security to none in /etc/bluetooth/hcid.conf

http://linux.die.net/man/5/hcid.conf

This will probably only work for HCI devices (mouse, keyboard, spaceball, etc.). If you have a different kind of device, there's probably a different but similar setting to change.

How to measure time in milliseconds using ANSI C?

timespec_get from C11

Returns up to nanoseconds, rounded to the resolution of the implementation.

Looks like an ANSI ripoff from POSIX' clock_gettime.

Example: a printf is done every 100ms on Ubuntu 15.10:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static long get_nanos(void) {
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}

int main(void) {
    long nanos;
    long last_nanos;
    long start;
    nanos = get_nanos();
    last_nanos = nanos;
    start = nanos;
    while (1) {
        nanos = get_nanos();
        if (nanos - last_nanos > 100000000L) {
            printf("current nanos: %ld\n", nanos - start);
            last_nanos = nanos;
        }
    }
    return EXIT_SUCCESS;
}

The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says":

If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock. (321)

321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.

C++11 also got std::chrono::high_resolution_clock: C++ Cross-Platform High-Resolution Timer

glibc 2.21 implementation

Can be found under sysdeps/posix/timespec_get.c as:

int
timespec_get (struct timespec *ts, int base)
{
  switch (base)
    {
    case TIME_UTC:
      if (__clock_gettime (CLOCK_REALTIME, ts) < 0)
        return 0;
      break;

    default:
      return 0;
    }

  return base;
}

so clearly:

  • only TIME_UTC is currently supported

  • it forwards to __clock_gettime (CLOCK_REALTIME, ts), which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html

    Linux x86-64 has a clock_gettime system call.

    Note that this is not a fail-proof micro-benchmarking method because:

    • man clock_gettime says that this measure may have discontinuities if you change some system time setting while your program runs. This should be a rare event of course, and you might be able to ignore it.

    • this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.

    For those reasons getrusage() might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.

    More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?

Changing EditText bottom line color with appcompat v7

I felt like this needed an answer in case somebody wanted to change just a single edittext. I do it like this:

editText.getBackground().mutate().setColorFilter(ContextCompat.getColor(context, R.color.your_color), PorterDuff.Mode.SRC_ATOP);

How do I convert a column of text URLs into active hyperlinks in Excel?

For anyone landing here with Excel 2016, you can simply highlight the column, then click the Hyperlink tab located on the Home ribbon in the Styles box.

enter image description here

Edit: Unfortunately, this only updates the cell style, not the function.

Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

Can't use SURF, SIFT in OpenCV

None of the above suggested solutions worked for me. I use Anaconda and found that opencv version 3.3.1 still had Sift enabled. If you want to test in isolated conda environment, try the following inspired from @A.Ametov's answer above

conda create -n testenv opencv=3.3.1     
conda activate testenv

conda activate myenv
python
#Check version of opencv being used
>>> import cv2
>>> cv2.__version__
#Check if Sift is available
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>

How do I limit the number of decimals printed for a double?

Check out DecimalFormat: http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

You'll do something like:

new DecimalFormat("$#.00").format(shippingCost);

Or since you're working with currency, you could see how NumberFormat.getCurrencyInstance() works for you.

Override body style for content in an iframe

You cannot change the style of a page displayed in an iframe unless you have direct access and therefore ownership of the source html and/or css files.

This is to stop XSS (Cross Site Scripting)

UITableView Separator line

Try this:

UIImageView *separator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"separator.png"]];
[cell.contentView addSubview: separator];

That's an example of how I got it to work pretty well.

Remember to set the separator style for the table view to none.

Python: TypeError: cannot concatenate 'str' and 'int' objects

str(c) returns a new string representation of c, and does not mutate c itself.

c = str(c) 

is probably what you are looking for

How to add manifest permission to an application?

Copy the following line to your application manifest file and paste before the <application> tag.

<uses-permission android:name="android.permission.INTERNET"/>

Placing the permission below the <application/> tag will work, but will give you warning. So take care to place it before the <application/> tag declaration.

How does Tomcat locate the webapps directory?

I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/", for example, I kept getting "This localhost page can't be found" in the browser.

I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/" as changing it to appBase="C:/Java Project/ROOT" will cause "This localhost page can't be found" to be displayed again.

Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.

String replace method is not replacing characters

Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

public class Test{

    public static void main(String[] args) {

        String sentence = "Define, Measure, Analyze, Design and Verify";

        String replaced = sentence.replace("and", "");
        System.out.println(replaced);

    }
}

As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

Appending the same string to a list of strings in Python

list2 = ['%sbar' % (x,) for x in list]

And don't use list as a name; it shadows the built-in type.

React Native: Getting the position of an element

You can use onLayout to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:

<View
  onLayout={event => {
    const layout = event.nativeEvent.layout;
    console.log('height:', layout.height);
    console.log('width:', layout.width);
    console.log('x:', layout.x);
    console.log('y:', layout.y);
  }}
>

Compared to using .measure() as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure() calls with setTimeout to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.

How to tell whether a point is to the right or left side of a line

The vector (y1 - y2, x2 - x1) is perpendicular to the line, and always pointing right (or always pointing left, if you plane orientation is different from mine).

You can then compute the dot product of that vector and (x3 - x1, y3 - y1) to determine if the point lies on the same side of the line as the perpendicular vector (dot product > 0) or not.

Recyclerview inside ScrollView not scrolling smoothly

You can try with both the ways with XML and programmatically. But the issue you may face is (below API 21) by doing it with XML will not work . So it's better to set it programmatically in your Activity / Fragment.

XML code:

<android.support.v7.widget.RecyclerView
      android:id="@+id/recycleView"
      android:layout_width="match_parent"
      android:visibility="gone"
      android:nestedScrollingEnabled="false"
      android:layout_height="wrap_content"
      android:layout_below="@+id/linearLayoutBottomText" /> 

Programmatically:

 recycleView = (RecyclerView) findViewById(R.id.recycleView);
 recycleView.setNestedScrollingEnabled(false);

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

you can also downgrade node js to version less than 12 and remove nodemodule then run npm install again

Combining node.js and Python

I'd consider also Apache Thrift http://thrift.apache.org/

It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/

The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.

getting the screen density programmatically in android?

This also works:

 getResources().getDisplayMetrics().density;

This will give you:

0.75 - ldpi

1.0 - mdpi

1.5 - hdpi

2.0 - xhdpi

3.0 - xxhdpi

4.0 - xxxhdpi

enter image description here

ref: density

enter image description here

ref 2

How to get the current user's Active Directory details in C#

If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the

System.DirectoryServices.AccountManagement namespace.

It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.

Brent

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Android Imagebutton change Image OnClick

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.

Refresh (reload) a page once using jQuery?

You don't have a jQuery refresh function, because this is JavaScript basics.

Try this:

<body onload="if (location.href.indexOf('reload')==-1) location.replace(location.href+'?reload');">

initializing strings as null vs. empty string

There are no gotchas. The default construction of std::string is "". But you cannot compare a string to NULL. The closest you can get is to check whether the string is empty or not, using the std::string::empty method..

Twitter Bootstrap onclick event on buttons-radio

I see a lot of complicated answers, while this is super simple in Bootstrap 3:

Step 1: Use the official example code to create your radio button group, and give the container an id:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

Step 2: Use this jQuery handler:

$("#myButtons :input").change(function() {
    console.log(this); // points to the clicked input button
});

Try the fiddle demo

AddRange to a Collection

Remember that each Add will check the capacity of the collection and resize it whenever necessary (slower). With AddRange, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

You can install SideBarEnhancements plugin, which among other things will give you ability to open file in browser just by clicking F12.

To open exactly in Chrome, you will need to fix up “Side Bar.sublime-settings” file and set "default_browser" to be "chrome".

I also recommend to learn this video tutorial on Sublime Text 2.

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

How to make div appear in front of another?

Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position

CSS: create white glow around image

You can use CSS3 to create an effect like that, but then you're only going to see it in modern browsers that support box shadow, unless you use a polyfill like CSS3PIE. So, for example, you could do something like this: http://jsfiddle.net/cany2/

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.

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

How do I check if a given string is a legal/valid file name under Windows?

I got this idea from someone. - don't know who. Let the OS do the heavy lifting.

public bool IsPathFileNameGood(string fname)
{
    bool rc = Constants.Fail;
    try
    {
        this._stream = new StreamWriter(fname, true);
        rc = Constants.Pass;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Problem opening file");
        rc = Constants.Fail;
    }
    return rc;
}

How do I create a MongoDB dump of my database?

This command will make a dump of given database in json and bson format.

mongodump -d <database name> -o <target directory>

Generating random numbers in Objective-C

For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:

static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

Android - implementing startForeground for a service?

This is my code to set the service to foreground:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

To remove the notification, just call the stopForeground(true);

It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java

Is there an alternative sleep function in C to milliseconds?

#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

vbscript output to console

Create a .vbs with the following code, which will open your main .vbs:

Set objShell = WScript.CreateObject("WScript.shell") 
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""

Here is my main .vbs

Option Explicit
Dim i
for i = 1 To 5
     Wscript.Echo i
     Wscript.Sleep 5000
Next

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Python, print all floats to 2 decimal places in output

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)

Email address validation using ASP.NET MVC data type attributes

if you aren't yet using .net 4.5:

/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
    static EmailAnnotation()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
    }

    /// <summary>
    /// from: http://stackoverflow.com/a/6893571/984463
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
    {
        return "E-mail is not valid";
    }
}

Then you can do this:

    public class ContactEmailAddressDto
    {
        public int ContactId { get; set; }
        [Required]
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }
    }

What is the difference between __str__ and __repr__?

On page 358 of the book Python scripting for computational science by Hans Petter Langtangen, it clearly states that

  • The __repr__ aims at a complete string representation of the object;
  • The __str__ is to return a nice string for printing.

So, I prefer to understand them as

  • repr = reproduce
  • str = string (representation)

from the user's point of view although this is a misunderstanding I made when learning python.

A small but good example is also given on the same page as follows:

Example

In [38]: str('s')
Out[38]: 's'

In [39]: repr('s')
Out[39]: "'s'"

In [40]: eval(str('s'))
Traceback (most recent call last):

  File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>
    eval(str('s'))

  File "<string>", line 1, in <module>

NameError: name 's' is not defined


In [41]: eval(repr('s'))
Out[41]: 's'

Fast way to get the min/max values among properties of object

// 1. iterate through object values and get them
// 2. sort that array of values ascending or descending and take first, 
//    which is min or max accordingly
let obj = { 'a': 4, 'b': 0.5, 'c': 0.35, 'd': 5 }
let min = Object.values(obj).sort((prev, next) => prev - next)[0] // 0.35
let max = Object.values(obj).sort((prev, next) => next - prev)[0] // 5

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Functional style of Java 8's Optional.ifPresent and if-not-Present?

There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:

public class OptionalEx {
    private boolean isPresent;

    private OptionalEx(boolean isPresent) {
        this.isPresent = isPresent;
    }

    public void orElse(Runnable runner) {
        if (!isPresent) {
            runner.run();
        }
    }

    public static <T> OptionalEx ifPresent(Optional<T> opt, Consumer<? super T> consumer) {
        if (opt.isPresent()) {
            consumer.accept(opt.get());
            return new OptionalEx(true);
        }
        return new OptionalEx(false);
    }
}

Then you can use a static import elsewhere to get syntax that is close to what you're after:

import static com.example.OptionalEx.ifPresent;

ifPresent(opt, x -> System.out.println("found " + x))
    .orElse(() -> System.out.println("NOT FOUND"));

Prefer composition over inheritance?

Inheritance creates a strong relationship between a subclass and super class; subclass must be aware of super class'es implementation details. Creating the super class is much harder, when you have to think about how it can be extended. You have to document class invariants carefully, and state what other methods overridable methods use internally.

Inheritance is sometimes useful, if the hierarchy really represents a is-a-relationship. It relates to Open-Closed Principle, which states that classes should be closed for modification but open to extension. That way you can have polymorphism; to have a generic method that deals with super type and its methods, but via dynamic dispatch the method of subclass is invoked. This is flexible, and helps to create indirection, which is essential in software (to know less about implementation details).

Inheritance is easily overused, though, and creates additional complexity, with hard dependencies between classes. Also understanding what happens during execution of a program gets pretty hard due to layers and dynamic selection of method calls.

I would suggest using composing as the default. It is more modular, and gives the benefit of late binding (you can change the component dynamically). Also it's easier to test the things separately. And if you need to use a method from a class, you are not forced to be of certain form (Liskov Substitution Principle).

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

Default argument values in JavaScript functions

ES2015 onwards:

From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,

function A(a, b = 4, c = 5) {
}

or combined with ES2015 destructuring,

function B({c} = {c: 2}, [d, e] = [3, 4]) {
}

For detailed explanation,

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Pre ES2015:

If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN, or null you can simply use

(So, for Objects, Arrays and Functions that you plan never to send null, you can use)

param || DEFAULT_VALUE

for example,

function X(a) {
  a = a || function() {};
}

Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ("", null, NaN, false, 0) too - which makes this method impossible to assign a param the falsy value passed as the argument.

So, in order to handle only undefined values explicitly, the preferred approach would be,

function C(a, b) {
  a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
  b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

What's the HTML to have a horizontal space between two objects?

Well, this is probably frowned upon but you can make a 1px transparent image, then size it as needed in between text.

Some text <img src="spacer.png" height="1px" width="10px"> Some more text

I've run into this issue when one or two spaces just wasn't enough for my design sensibilities.

Remove property for all objects in array

The shortest way in ES6:

array.forEach(e => {delete e.someKey});

Oracle JDBC intermittent Connection Issue

Note that the suggested solution of using /dev/urandom did work the first time for me but didn't work always after that.

DBA at my firm switched of 'SQL* net banners' and that fixed it permanently for me with or without the above.

I don't know what 'SQL* net banners' are, but am hoping by putting this information here that if you have(are) a DBA he(you) would know what to do.

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

How do I parse a string to a float or int?

The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

Node.js on multi-core machines

One method would be to run multiple instances of node.js on the server and then put a load balancer (preferably a non-blocking one like nginx) in front of them.

Using the GET parameter of a URL in JavaScript

If you're already running a php page then

php bit:

    $json   =   json_encode($_REQUEST, JSON_FORCE_OBJECT);
    print "<script>var getVars = $json;</script>";

js bit:

    var param1var = getVars.param1var;

But for Html pages Jose Basilio's solution looks good to me.

Good luck!

How to filter keys of an object with lodash?

A non-lodash way to solve this in a fairly readable and efficient manner:

_x000D_
_x000D_
function filterByKeys(obj, keys = []) {_x000D_
  const filtered = {}_x000D_
  keys.forEach(key => {_x000D_
    if (obj.hasOwnProperty(key)) {_x000D_
      filtered[key] = obj[key]_x000D_
    }_x000D_
  })_x000D_
  return filtered_x000D_
}_x000D_
_x000D_
const myObject = {_x000D_
  a: 1,_x000D_
  b: 'bananas',_x000D_
  d: null_x000D_
}_x000D_
_x000D_
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

jQuery UI - Draggable is not a function?

A common reason occurs is if you don't also load jqueryui after loading jquery.

For example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>

EDIT. Replace the version number for each library with appropriate or latest values for jquery and jqueryui.

If this doesn't solve the issue, review suggestions in the many other answers.

How do I show the number keyboard on an EditText in android?

If you are using your EditText in Dialog or creating dynamically and You can't set it from xml then this example will help you in setting that type of key board while you are using dynamic Edit Text etc

myEditTxt.setInputType(InputType.TYPE_CLASS_NUMBER);

where myEditTxt is the dynamic EDIT TEXT object(name)

Maven: Failed to read artifact descriptor

Had the same issue with IntelliJ IDEA and following worked.

  • Go to File
  • Select Settings
  • Select Build, Execution, Deployments
  • Select Build Tools from drop down
  • Select Maven from drop down
  • Tick the Always update snapshots check box

screen shot of IntelliJ 2017.2 > Preferences/Settings > Build, Execution, Deployment > Build Tools > Maven > Always update snapshots (checkbox)

RelativeLayout center vertical

This maybe because the textview is too high. Change android:layout_height of the textview to wrap_content or use

android:gravity="center_vertical"

SQL Server - Case Statement

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar. You could put your calculation into a derived table:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

A common table expression would work just as well:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

Combining two sorted lists in Python

This is my solution in linear time without editing l1 and l2:

def merge(l1, l2):
  m, m2 = len(l1), len(l2)
  newList = []
  l, r = 0, 0
  while l < m and r < m2:
    if l1[l] < l2[r]:
      newList.append(l1[l])
      l += 1
    else:
      newList.append(l2[r])
      r += 1
  return newList + l1[l:] + l2[r:]

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

Compilation error - missing zlib.h

You are missing zlib.h header file, on Linux install it via:

sudo apt-get install libz-dev

As a matter of fact, the module presents as zlib1g-dev in the apt repo, so this is the up-to-date call (Feb 2019):

sudo apt install zlib1g-dev

On Fedora: sudo dnf install zlib-devel (in older versions: sudo dnf install libz-devel).

This will provide the development support files for a library implementing the deflate compression method found in gzip and PKZIP.

If you've already zlib library, make sure you're compiling your code sources with -lz. See: How to fix undefined references to inflate/deflate functions?.

How to filter rows containing a string pattern from a Pandas dataframe

df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1

Step-by-step explanation (from inner to outer):

  • df['ids'] selects the ids column of the data frame (technically, the object df['ids'] is of type pandas.Series)
  • df['ids'].str allows us to apply vectorized string methods (e.g., lower, contains) to the Series
  • df['ids'].str.contains('ball') checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True or False about the existence of a 'ball' substring.
  • df[df['ids'].str.contains('ball')] applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.
  • na = False removes NA / NaN values from consideration; otherwise a ValueError may be returned.

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

At terminal run this command with root permission:

sudo /etc/init.d/apache2 start

You must be root for starting a webserver otherwise you would get similar error.

Android Completely transparent Status Bar?

Simple and crisp and works with almost all use cases (for API level 16 and above):

  1. Use the following tag in your app theme to make the status bar transparent:

    <item name="android:statusBarColor">@android:color/transparent</item>

  2. And then use this code in your activity's onCreate method.

    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    

That's all you need to do ;)

You can learn more from the developer documentation. I'd also recommend reading this blog post.

KOTLIN CODE:

    val decorView = window.decorView
    decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

Check my another answer here

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Why are primes important in cryptography?

One more resource for you. Security Now! episode 30(~30 minute podcast, link is to the transcript) talks about cryptography issues, and explains why primes are important.

Multiline strings in VB.NET

No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

How to get resources directory path programmatically

Finally, this is what I did:

private File getFileFromURL() {
    URL url = this.getClass().getClassLoader().getResource("/sql");
    File file = null;
    try {
        file = new File(url.toURI());
    } catch (URISyntaxException e) {
        file = new File(url.getPath());
    } finally {
        return file;
    }
}

...

File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();

Importing a Maven project into Eclipse from Git

I would prefer to import projects into Eclipse as maven projects rather than git project. Doing this will still allow the project contents to be recognized as git contents. You can continue to perform git operations from Eclipse. As you have mentioned the reverse is not true.

The nature of a project in Eclipse is not based on the SCM which holds the project, but on the type of project - whether war or jar, etc. - which is automagically determined when the project is imported as maven project.

I would be hesitant to check-in to SCM IDE-specific metadata. Doing so assumes a lot of things - all developers are using the same IDE or version of the IDE, perhaps same version of JDK/JRE, that they continue to use the same version throughout the project lifecycle and so on.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME

How do I insert an image in an activity with android studio?

since you followed the tutorial, I presume you have a screen that says Hello World.

that means you have some code in your layout xml that looks like this

<TextView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/cool_pic"
/>

Is there something like Codecademy for Java

Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).

Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.

The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Android: Vertical alignment for multi line EditText (Text area)

This is similar to CommonsWare answer but with a minor tweak: android:gravity="top|start". Complete code example:

<EditText
    android:id="@+id/EditText02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:lines="5"
    android:gravity="top|start"
    android:inputType="textMultiLine"
    android:scrollHorizontally="false" 
/>

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

Testing javascript with Mocha - how can I use console.log to debug a test?

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?

console.log(msg);

works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

Java socket API: How to tell if a connection has been closed?

I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).

If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.

I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation.

If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:

  • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).
  • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...

I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.

Linux find file names with given string recursively

The find command will take long time because it scans real files in file system.

The quickest way is using locate command, which will give result immediately:

locate "John"

If the command is not found, you need to install mlocate package and run updatedb command first to prepare the search database for the first time.

More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How can I use UIColorFromRGB in Swift?

myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)

How can I generate an apk that can run without server with react-native?

Try below, it will generate an app-debug.apk on your root/android/app/build/outputs/apk/debug folder

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

then go to android folder and run

./gradlew assembleDebug

PowerShell says "execution of scripts is disabled on this system."

If you're using Windows Server 2008 R2 then there is an x64 and x86 version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?

As an Administrator, you can set the execution policy by typing this into your PowerShell window:

Set-ExecutionPolicy RemoteSigned

For more information, see Using the Set-ExecutionPolicy Cmdlet.

When you are done, you can set the policy back to its default value with:

Set-ExecutionPolicy Restricted

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

Oracle Add 1 hour in SQL

Use an interval:

select some_date_column + interval '1' hour 
from your_table;

Display image as grayscale using matplotlib

@unutbu's answer is quite close to the right answer.

By default, plt.imshow() will try to scale your (MxN) array data to 0.0~1.0. And then map to 0~255. For most natural taken images, this is fine, you won't see a different. But if you have narrow range of pixel value image, say the min pixel is 156 and the max pixel is 234. The gray image will looks totally wrong. The right way to show an image in gray is

from matplotlib.colors import NoNorm
...
plt.imshow(img,cmap='gray',norm=NoNorm())
...

Let's see an example:

this is the origianl image: original

this is using defaul norm setting,which is None: wrong pic

this is using NoNorm setting,which is NoNorm(): right pic

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

You can delete all the documents from a collection in MongoDB, you can use the following:

db.users.remove({})

Alternatively, you could use the following method as well:

db.users.deleteMany({})

Follow the following MongoDB documentation, for further details.

To remove all documents from a collection, pass an empty filter document {} to either the db.collection.deleteMany() or the db.collection.remove() method.

HTTP 404 when accessing .svc file in IIS

There are 2 .net framework version are given under the features in add role/ features in server 2012

a. 3.5

b. 4.5

Depending up on used framework you can enable HTTP-Activation under WCF services. :)

What does %w(array) mean?

I think of %w() as a "word array" - the elements are delimited by spaces and it returns an array of strings.

There are other % literals:

  • %r() is another way to write a regular expression.
  • %q() is another way to write a single-quoted string (and can be multi-line, which is useful)
  • %Q() gives a double-quoted string
  • %x() is a shell command
  • %i() gives an array of symbols (Ruby >= 2.0.0)
  • %s() turns foo into a symbol (:foo)

I don't know any others, but there may be some lurking around in there...

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

Check if a value exists in pandas dataframe index

This should do the trick

'g' in df.index

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

What are functional interfaces used for in Java 8?

The documentation makes indeed a difference between the purpose

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.

and the use case

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”

Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:

JLS §9.8. Functional Interfaces:

In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).

So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).

So in one sentence, no, there is no other use case for it in Java 8.

scale Image in an UIButton to AspectFit?

This can now be done through IB's UIButton properties. The key is to set your image as a the background, otherwise it won't work.

enter image description here

How to convert NSData to byte array in iPhone?

You could also just use the bytes where they are, casting them to the type you need.

unsigned char *bytePtr = (unsigned char *)[data bytes];

Adding minutes to date time in PHP

one line mysql datetime format

$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");

Sql Server trigger insert values from new row into another table

In a SQL Server trigger you have available two psdeuotables called inserted and deleted. These contain the old and new values of the record.

So within the trigger (you can look up the create trigger parts easily) you would do something like this:

Insert table2 (user_id, user_name)
select user_id, user_name from inserted i
left join table2 t on i.user_id = t.userid
where t.user_id is null

When writing triggers remember they act once on the whole batch of information, they do not process row-by-row. So account for multiple row inserts in your code.

Bootstrap 3 with remote Modal

For Bootstrap 3

The workflow I had to deal with was loading content with a url context that could change. So by default setup your modal with javascript or the href for the default context you want to show :

$('#myModal').modal({
        show: false,
        remote: 'some/context'
});

Destroying the modal wouldn't work for me because I wasn't loading from the same remote, thus I had to :

$(".some-action-class").on('click', function () {
        $('#myModal').removeData('bs.modal');
        $('#myModal').modal({remote: 'some/new/context?p=' + $(this).attr('buttonAttr') });
        $('#myModal').modal('show');
});

This of course was easily refactored into a js library and gives you a lot of flexibility with loading modals

I hope this saves someone 15 minutes of tinkering.

How to get an input text value in JavaScript

The reason that this doesn't work is because the variable doesn't change with the textbox. When it initially runs the code it gets the value of the textbox, but afterwards it isn't ever called again. However, when you define the variable in the function, every time that you call the function the variable updates. Then it alerts the variable which is now equal to the textbox's input.

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

Find size of object instance in bytes in c#

safe solution with some optimizations CyberSaving/MemoryUsage code. some case:

/* test nullable type */      
TestSize<int?>.SizeOf(null) //-> 4 B

/* test StringBuilder */    
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.Append("??????????");
TestSize<StringBuilder>.SizeOf(sb ) //-> 3132 B

/* test Simple array */    
TestSize<int[]>.SizeOf(new int[100]); //-> 400 B

/* test Empty List<int>*/    
var list = new List<int>();  
TestSize<List<int>>.SizeOf(list); //-> 205 B

/* test List<int> with 100 items*/
for (int i = 0; i < 100; i++) list.Add(i);
TestSize<List<int>>.SizeOf(list); //-> 717 B

It works also with classes:

class twostring
{
    public string a { get; set; }
    public string b { get; set; }
}
TestSize<twostring>.SizeOf(new twostring() { a="0123456789", b="0123456789" } //-> 28 B

How to check for a valid Base64 encoded string

Do decode, re encode and compare the result to original string

public static Boolean IsBase64(this String str)
{
    if ((str.Length % 4) != 0)
    {
        return false;
    }

    //decode - encode and compare
    try
    {
        string decoded = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(str));
        string encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(decoded));
        if (str.Equals(encoded, StringComparison.InvariantCultureIgnoreCase))
        {
            return true;
        }
    }
    catch { }
    return false;
}

Examples for string find in Python

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

How to import a module given the full path?

You can use the

load_source(module_name, path_to_file) 

method from imp module.

A keyboard shortcut to comment/uncomment the select text in Android Studio

To comment/uncomment one line, use: Ctrl + /.

To comment/uncomment a block, use: Ctrl + Shift + /.

How to handle screen orientation change when progress dialog and background thread active?

I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern.

That is, my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts sticky intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the IntentService we can still respond and pick up the data from the calling Activity. ProgressDialogs can work with this pattern quite nicely with onSaveInstanceState().

Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. Do not save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a weak reference in the application object. On orientation change or anything else that causes the Activity to pause (phone call, user hits home etc.) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity.

For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restoring the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things.

So to summarize, putting long-running tasks into an IntentService coupled with judicious use of onSaveInstanceState() allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.

public void doSignIn(View view) {
    waiting=true;
    AppClass app=(AppClass) getApplication();
    String logingon=getString(R.string.signon);
    app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    ...
}

@Override
protected void onSaveInstanceState(Bundle saveState) {
    super.onSaveInstanceState(saveState);
    saveState.putBoolean("waiting",waiting);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState!=null) {
        restoreProgress(savedInstanceState);    
    }
    ...
}

private void restoreProgress(Bundle savedInstanceState) {
    waiting=savedInstanceState.getBoolean("waiting");
    if (waiting) {
        AppClass app=(AppClass) getApplication();
        ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
        refresher.dismiss();
        String logingon=getString(R.string.signon);
        app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    }
}

Path.Combine for URLs?

There is a Todd Menier's comment above that Flurl includes a Url.Combine.

More details:

Url.Combine is basically a Path.Combine for URLs, ensuring one and only one separator character between parts:

var url = Url.Combine(
    "http://MyUrl.com/",
    "/too/", "/many/", "/slashes/",
    "too", "few?",
    "x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2" 

Get Flurl.Http on NuGet:

PM> Install-Package Flurl.Http

Or get the stand-alone URL builder without the HTTP features:

PM> Install-Package Flurl

SQL Server add auto increment primary key to existing table

I had this issue, but couldn't use an identity column (for various reasons). I settled on this:

DECLARE @id INT
SET @id = 0 
UPDATE table SET @id = id = @id + 1 

Borrowed from here.

Read values into a shell variable from a pipe

Piping something into an expression involving an assignment doesn't behave like that.

Instead, try:

test=$(echo "hello world"); echo test=$test

How to open a folder in Windows Explorer from VBA?

Thanks to many of the answers above and elsewhere, this was my solution to a similar problem to the OP. The problem for me was creating a button in Word that asks the user for a network address, and pulls up the LAN resources in an Explorer window.

Untouched, the code would take you to \\10.1.1.1\Test, so edit as you see fit. I'm just a monkey on a keyboard, here, so all comments and suggestions are welcome.

Private Sub CommandButton1_Click()
    Dim ipAddress As Variant
    On Error GoTo ErrorHandler

    ipAddress = InputBox("Please enter the IP address of the network resource:", "Explore a network resource", "\\10.1.1.1")
    If ipAddress <> "" Then
        ThisDocument.FollowHyperlink ipAddress & "\Test"
    End If

    ExitPoint:
        Exit Sub

    ErrorHandler:
        If Err.Number = "4120" Then
            GoTo ExitPoint
        ElseIf Err.Number = "4198" Then
            MsgBox "Destination unavailable"
            GoTo ExitPoint
        End If

        MsgBox "Error " & Err.Number & vbCrLf & Err.Description
        Resume ExitPoint

End Sub

remove item from array using its name / value

Created a handy function for this..

function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      array.splice(index, 1);
    }    
  });
}

//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

how to calculate binary search complexity

Here is the solution using the master theorem, with readable LaTeX.

For each recurrence in the recurrence relation for binary search, we convert the problem into one subproblem, with runtime T(N/2). Therefore:

T(n) = T(n/2)+1

Substituting into the master theorem, we get:

T(n) = aT(n/b) + f(n)

Now, because logba is 0 and f(n) is 1, we can use the second case of the master theorem because:

f(n) = O(1) = O(n0) = O(nlogba)

This means that:

T(n)=O(nlogbalogn) = O(n0logn) = O(logn)

How do I tell matplotlib that I am done with a plot?

There is a clear figure command, and it should do it for you:

plt.clf()

If you have multiple subplots in the same figure

plt.cla()

clears the current axes.

Pause in Python

There's a simple way to do this, you can use keyboard module's wait function. For example, you can do:

import keyboard
print("things before the pause")
keyboard.wait("esc") # esc is just an example, you can obviously put every key you want
print("things after the pause")

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

Pie chart with jQuery

There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:

https://zoomcharts.com/

Example of charts:

interactive pie chart

Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/

What is cool about this lib:

  • Others slice can be expanded
  • Pie offers drill down for hierarchical structures (see example)
  • write your own data source controller easily, or provide simple json file
  • export high res images out of box
  • full touch support, works smoothly on iPad, iPhone, android, etc.

enter image description here

Charts are free for non-commercial use, commercial licenses and technical support available as well.

Also interactive Time charts and Net Charts are there for you to use. enter image description here

enter image description here

Charts come with extensive API and Settings, so you can control every aspect of the charts.

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

jQuery or Javascript - how to disable window scroll without overflow:hidden;

You can use jquery-disablescroll to solve the problem:

  • Disable scrolling: $window.disablescroll();
  • Enable scrolling again: $window.disablescroll("undo");

Supports handleWheel, handleScrollbar, handleKeys and scrollEventKeys.

How do I concatenate two lists in Python?

It's also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

Append value to empty vector in R?

> vec <- c(letters[1:3]) # vec <- c("a","b","c") ; or just empty vector: vec <- c()

> values<- c(1,2,3)

> for (i in 1:length(values)){
      print(paste("length of vec", length(vec))); 
      vec[length(vec)+1] <- values[i]  #Appends value at the end of vector
  }

[1] "length of vec 3"
[1] "length of vec 4"
[1] "length of vec 5"

> vec
[1] "a" "b" "c" "1" "2" "3"

C# 30 Days From Todays Date

string[] servers = new string[] {
        "nist1-ny.ustiming.org",
        "nist1-nj.ustiming.org",
        "nist1-pa.ustiming.org",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "nist1.aol-va.symmetricom.com",
        "nist1.columbiacountyga.gov",
        "nist1-chi.ustiming.org",
        "nist.expertsmi.com",
        "nist.netservicesgroup.com"
        };
string dateStart, dateEnd;

void SetDateToday()
    {
        Random rnd = new Random();
        DateTime result = new DateTime();
        int found = 0;
        foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
        {
            Console.Write(".");
            try
            {
                string serverResponse = string.Empty;
                using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
                {
                    serverResponse = reader.ReadToEnd();
                    Console.WriteLine(serverResponse);
                }

                if (!string.IsNullOrEmpty(serverResponse))
                {
                    string[] tokens = serverResponse.Split(' ');
                    string[] date = tokens[1].Split(' ');
                    string time = tokens[2];
                    string properTime;

                    dateStart = date[2] + "/" + date[0] + "/" + date[1];

                    int month = Convert.ToInt16(date[0]), day = Convert.ToInt16(date[2]), year = Convert.ToInt16(date[1]);
                    day = day + 30;
                    if ((month % 2) == 0)
                    {
                        //MAX DAYS IS 30
                        if (day > 30)
                        {
                            day = day - 30;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    else
                    {
                        //MAX DAYS IS 31
                        if (day > 31)
                        {
                            day = day - 31;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    string sday, smonth;
                    if (day < 10)
                    {
                        sday = "0" + day;
                    }
                    if (month < 10)
                    {
                        smonth = "0" + month;
                    }
                    dateEnd = sday + "/" + smonth + "/" + year.ToString();

                }

            }
            catch
            {
                // Ignore exception and try the next server
            }
        }
        if (found == 0)
        {
            MessageBox.Show(this, "Internet Connection is required to complete Registration. Please check your internet connection and try again.", "Not connected", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Success = false;
        }
    }

I saw that code in some part of some website. Doing the example above exposes a glitch: Changing the current Time and Date to the start date would prolong the application expiration.

The solution? Refer to a online time server.

How to add a changed file to an older (not last) commit in Git

You can try a rebase --interactive session to amend your old commit (provided you did not already push those commits to another repo).

Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.

Start it with the last commit you want to retain as-is:

git rebase -i <after-this-commit>

An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:

pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...

The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

Do I need to explicitly call the base virtual destructor?

What the others said, but also note that you do not have to declare the destructor virtual in the derived class. Once you declare a destructor virtual, as you do in the base class, all derived destructors will be virtual whether you declare them so or not. In other words:

struct A {
   virtual ~A() {}
};

struct B : public A {
   virtual ~B() {}   // this is virtual
};

struct C : public A {
   ~C() {}          // this is virtual too
};

How do I resolve this "ORA-01109: database not open" error?

If your database is down then during login as SYSDBA you can assume this. While login command will be executed like sqlplus sys/sys_password as sysdba that time you will get "connected to idle instance" reply from database. This message indicates your database is down. You should need to check first alert.log file about why database is down. If you found it was downed normally then you can issue "startup" command for starting database and after that execute your create user command. If you found database is having issue like missing datafile or something else then you need to recover database first and open database for executing your create user command.

"alter database open" command only accepted by database while it is on Mount stage. If database is down then it won't accept "alter database open" command.

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

The magic of pipes;

head -10 log.txt | grep <whatever>

Python 3: ImportError "No Module named Setuptools"

The distribute package provides a Python 3-compatible version of setuptools: http://pypi.python.org/pypi/distribute

Also, use pip to install the modules. It automatically finds dependencies and installs them for you.

It works just fine for me with your package:

[~] pip --version                                                              
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors                                                
Downloading/unpacking ansicolors
  Downloading ansicolors-1.0.2.tar.gz
  Running setup.py egg_info for package ansicolors

Installing collected packages: ansicolors
  Running setup.py install for ansicolors

Successfully installed ansicolors
Cleaning up...
[~]

Installing MySQL-python

this worked for me on python 3

pip install mysqlclient

MessageBox Buttons?

This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
            if (d == DialogResult.Yes)
            {
                //Contents
            }
            else if (d == DialogResult.No)
            {
                //Contents
            }

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

Return current date plus 7 days

Here is how you can do it using strtotime(),

<?php
    $date = strtotime("3 October 2005");
    $d = strtotime("+7 day", $date);
    echo "Created date is " . date("Y-m-d h:i:sa", $d) . "<br>";
?>

Error on renaming database in SQL Server 2008 R2

That's because someone else is accessing the database. Put the database into single user mode then rename it.

This link might help:
http://msdn.microsoft.com/en-IN/library/ms345378(v=sql.105).aspx

and also:
http://msdn.microsoft.com/en-us/library/ms345378.aspx

How to check if an user is logged in Symfony2 inside a controller?

Try this:

if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
    // authenticated (NON anonymous)
}

Further information:

"Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role."

Source: http://symfony.com/doc/current/book/security.html

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Processing Symbol Files in Xcode

I know that this is not a technical solution but I had my iphone connected with the computer by cable and disconnecting the device from the computer and connecting it again (by cable again) worked for me as I could not solved it with the solutions that are provided before.

How to set Python's default version to 3.x on OS X?

I'm not sure if this is available on OS X, but on linux I would make use of the module command. See here.

Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):

module load python3.3

This will make it so that your paths get switched around as required when you log in without impacting any system defaults.

How do I pass a unique_ptr argument to a constructor or a function?

Yes you have to if you take the unique_ptr by value in the constructor. Explicity is a nice thing. Since unique_ptr is uncopyable (private copy ctor), what you wrote should give you a compiler error.

Get value of a specific object property in C# without knowing the class behind

Simply try this for all properties of an object,

foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
   var propertyName = prop.Name;
   var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);

   //Debug.Print(prop.Name);
   //Debug.Print(Functions.convertNullableToString(propertyValue));

   Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}

NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.

Extract parameter value from url using regular expressions

I know the question is Old and already answered but this can also be a solution

\b[\w-]+$

and I checked these two URLs

http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos

DEMO

Convert String with Dot or Comma as decimal separator to number in JavaScript

The perfect solution

accounting.js is a tiny JavaScript library for number, money and currency formatting.

Check this for ref

Convert string to float?

String s = "3.14";
float f = Float.parseFloat(s);

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

How to generate access token using refresh token through google drive API?

Just posting my answer in case it helps anyone as I spent an hour to figure it out :)

First of all two very helpful link related to google api and fetching data from any of google services:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php

https://developers.google.com/identity/protocols/OAuth2WebServer

Furthermore, when using the following method:

$client->setAccessToken($token)

The $token needs to be the full object returned by the google when making authorization request, not the only access_token which you get inside the object so if you get the object lets say:

{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}

then you need to give:

$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')

Not

$client->setAccessToken('xyz')

And then even if your access_token is expired, google will refresh it itself by using the refresh_token in the access_token object.

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

Extract Month and Year From Date in R

Here's another solution using a package solely dedicated to working with dates and times in R:

library(tidyverse)
library(lubridate)

(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#>      ID Date      
#>   <int> <chr>     
#> 1     1 2004-02-06
#> 2     2 2006-03-14
#> 3     3 2007-07-16

df %>%
  mutate(
    Date = ymd(Date),
    Month_Yr = format_ISO8601(Date, precision = "ym")
  )
#> # A tibble: 3 x 3
#>      ID Date       Month_Yr
#>   <int> <date>     <chr>   
#> 1     1 2004-02-06 2004-02 
#> 2     2 2006-03-14 2006-03 
#> 3     3 2007-07-16 2007-07

Created on 2020-09-01 by the reprex package (v0.3.0)

Set Locale programmatically

There is a super simple way.

in BaseActivity, Activity or Fragment override attachBaseContext

 override fun attachBaseContext(context: Context) {
    super.attachBaseContext(context.changeLocale("tr"))
}

extension

fun Context.changeLocale(language:String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)
    val config = this.resources.configuration
    config.setLocale(locale)
    return createConfigurationContext(config)
}

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

Ruby 'require' error: cannot load such file

The problem is that require does not load from the current directory. This is what I thought, too but then I found this thread. For example I tried the following code:

irb> f = File.new('blabla.rb')
=> #<File:blabla.rb>
irb> f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
LoadError: cannot load such file -- blabla.rb
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from (irb):24
        from D:/dev/Ruby193/bin/irb:12:in `<main>'

As it can be seen it read the file ok, but I could not require it (the path was not recognized). and here goes code that works:

irb f = File.new('D://blabla.rb')
=> #<File:D://blabla.rb>
irb f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
=> true

As you can see if you specify the full path the file loads correctly.

SQL update fields of one table from fields of another one

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

Clear and reset form input fields

Very easy:

_x000D_
_x000D_
handleSubmit(e){_x000D_
    e.preventDefault();_x000D_
    e.target.reset();_x000D_
}
_x000D_
<form onSubmit={this.handleSubmit.bind(this)}>_x000D_
  ..._x000D_
</form>
_x000D_
_x000D_
_x000D_

Good luck :)

JavaScript window resize event

You can use following approach which is ok for small projects

<body onresize="yourHandler(event)">

_x000D_
_x000D_
function yourHandler(e) {
  console.log('Resized:', e.target.innerWidth)
}
_x000D_
<body onresize="yourHandler(event)">
  Content... (resize browser to see)
</body>
_x000D_
_x000D_
_x000D_

Android: ProgressDialog.show() crashes with getApplicationContext

For Android 2.2
Use this code:

//activity is an instance of a class which extends android.app.Activity
Dialog dialog = new Dialog(activity);

instead of this code:

// this code produces an ERROR:
//android.view.WindowManager$BadTokenException: 
//Unable to add window -- token null is not for an application
Context mContext = activity.getApplicationContext();
Dialog dialog = new Dialog(mContext);

Remark: My custom dialog is created outside activity.onCreateDialog(int dialogId) method.

Multiprocessing: How to use Pool.map on a function defined in a class?

Here is a boilerplate I wrote for using multiprocessing Pool in python3, specifically python3.7.7 was used to run the tests. I got my fastest runs using imap_unordered. Just plug in your scenario and try it out. You can use timeit or just time.time() to figure out which works best for you.

import multiprocessing
import time

NUMBER_OF_PROCESSES = multiprocessing.cpu_count()
MP_FUNCTION = 'starmap'  # 'imap_unordered' or 'starmap' or 'apply_async'

def process_chunk(a_chunk):
    print(f"processig mp chunk {a_chunk}")
    return a_chunk


map_jobs = [1, 2, 3, 4]

result_sum = 0

s = time.time()
if MP_FUNCTION == 'imap_unordered':
    pool = multiprocessing.Pool(processes=NUMBER_OF_PROCESSES)
    for i in pool.imap_unordered(process_chunk, map_jobs):
        result_sum += i
elif MP_FUNCTION == 'starmap':
    pool = multiprocessing.Pool(processes=NUMBER_OF_PROCESSES)
    try:
        map_jobs = [(i, ) for i in map_jobs]
        result_sum = pool.starmap(process_chunk, map_jobs)
        result_sum = sum(result_sum)
    finally:
        pool.close()
        pool.join()
elif MP_FUNCTION == 'apply_async':
    with multiprocessing.Pool(processes=NUMBER_OF_PROCESSES) as pool:
        result_sum = [pool.apply_async(process_chunk, [i, ]).get() for i in map_jobs]
    result_sum = sum(result_sum)
print(f"result_sum is {result_sum}, took {time.time() - s}s")

In the above scenario imap_unordered actually seems to perform the worst for me. Try out your case and benchmark it on the machine you plan to run it on. Also read up on Process Pools. Cheers!

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

Unit testing private methods in C#

In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

Error in Swift class: Property not initialized at super.init call

Add nil to the end of the declaration.


// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil

// Init the view
override init(frame: CGRect)
    super.init(frame: frame)
    ...

This worked for my case, but may not work for yours

if A vs if A is not None:

python >= 2.6,

if we write such as

if A:

will generate warning as,

FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.

So we can use

if A is not None:

Deadly CORS when http://localhost is the origin

Quick and dirty Chrome extension fix:

Moesif Orign & CORS Changer

However, Chrome does support cross-origin requests from localhost. Make sure to add a header for Access-Control-Allow-Origin for localhost.

Compress files while reading data from STDIN

Yes, gzip will let you do this. If you simply run gzip > foo.gz, it will compress STDIN to the file foo.gz. You can also pipe data into it, like some_command | gzip > foo.gz.

How to post data in PHP using file_get_contents?

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

I can think of different method to achieve the same

IList<SelectableEnumItem> result= array;

or (i had some situation that this one didn't work well)

var result = (List<SelectableEnumItem>) array;

or use linq extension

var result = array.CastTo<List<SelectableEnumItem>>();

or

var result= array.Select(x=> x).ToArray<SelectableEnumItem>();

or more explictly

var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });

please pay attention in above solution I used dynamic Object

I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.

Myself I use the first one

How to list all the files in a commit?

I thought I would share a summary of my alias.. also I find using 'zsh' great with git it chroma keys everything nicely and tells you want branch are in all of the time by changing the command prompt.

For those covering from SVN you will find this useful: (this is a combination of ideas from different threads, I only take credit of knowing how to use copy/paste)

.gitconfig:
        ls = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative --name-status

>>git ls
* 99f21a6 - (HEAD -> swift) New Files from xcode 7 (11 hours ago) Jim Zucker| 
| A     icds.xcodeproj/project.pbxproj
| A     icds.xcodeproj/project.xcworkspace/contents.xcworkspacedata
| A     icds/AppDelegate.m
| A     icds/Assets.xcassets/AppIcon.appiconset/Contents.json

* e0a1bb6 - Move everything to old (11 hours ago) Jim Zucker| 
| D     Classes/AppInfoViewControler.h
| D     Classes/AppInfoViewControler.m
| D     Classes/CurveInstrument.h


.gitconfig: 
       lt = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative

>>git lt
* 99f21a6 - (HEAD -> swift) New Files from xcode 7 (11 hours ago) Jim Zucker
* e0a1bb6 - Move everything to old (11 hours ago) Jim Zucker
* 778bda6 - Cleanup for new project (11 hours ago) Jim Zucker
* 7373b5e - clean up files from old version (11 hours ago) Jim Zucker
* 14a8d53 - (tag: 1.x, origin/swift, origin/master, master) Initial Commit (16 hours ago) Jim Zucker


.gitconfig
lt = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative

>> git lt

commit 99f21a61de832bad7b2bdb74066a08cac3d0bf3c
Author: Jim Zucker <[email protected]>
Date:   Tue Dec 1 22:23:10 2015 -0800

    New Files from xcode 7

A       icds.xcodeproj/project.pbxproj
A       icds.xcodeproj/project.xcworkspace/contents.xcworkspacedata


commit e0a1bb6b59ed6a4f9147e894d7f7fe00283fce8d
Author: Jim Zucker <[email protected]>
Date:   Tue Dec 1 22:17:00 2015 -0800

    Move everything to old

D       Classes/AppInfoViewControler.h
D       Classes/AppInfoViewControler.m
D       Classes/CurveInstrument.h
D       Classes/CurveInstrument.m

Retrieve filename from file descriptor in C

I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

We do, instead, have a F_GETPATH command for fcntl:

 F_GETPATH          Get the path of the file descriptor Fildes.  The argu-
                    ment must be a buffer of size MAXPATHLEN or greater.

So to get the file associated to a file descriptor, you can use this snippet:

#include <sys/syslimits.h>
#include <fcntl.h>

char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
    // do something with the file path
}

Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.

Using UPDATE in stored procedure with optional parameters

   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

Pretty-Print JSON in Java

Now this can be achieved with the JSONLib library:

http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html

If (and only if) you use the overloaded toString(int indentationFactor) method and not the standard toString() method.

I have verified this on the following version of the API:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

Accept server's self-signed ssl certificate in Java client

There's a better alternative to trusting all certificates: Create a TrustStore that specifically trusts a given certificate and use this to create a SSLContext from which to get the SSLSocketFactory to set on the HttpsURLConnection. Here's the complete code:

File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());

You can alternatively load the KeyStore directly from a file or retrieve the X.509 Certificate from any trusted source.

Note that with this code, the certificates in cacerts will not be used. This particular HttpsURLConnection will only trust this specific certificate.