Programs & Examples On #Browser based

How does Google reCAPTCHA v2 work behind the scenes?

My Bots are running well against ReCaptcha.

Here my Solution.

Let your Bot do this Steps:

First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.

Also use for better results a VPN like https://www.purevpn.com

For every Recpatcha do these Steps:

  1. If you use VPN switch IP first

  2. Clear all Browser Cookies

  3. Clear all Browser Cache

  4. Set one of these Useragents by Random:

    a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

    b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange

  1. Then Click ever with random delay between

    WM_LBUTTONDOWN

    and

    WM_LBUTTONUP

  2. Take Screenshot from Image Captcha

  3. Send Screenshot to

    http://www.deathbycaptcha.com

    or

    https://2captcha.com

and let they solve.

  1. After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images

  2. Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button

In 75% all trys Recaptcha will solved

Chears Google

Tom

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Can you control how an SVG's stroke-width is drawn?

I found an easy way, which has a few restrictions, but worked for me:

  • define the shape in defs
  • define a clip path referencing the shape
  • use it and double the stroke with as the outside is clipped

Here a working example:

_x000D_
_x000D_
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
 <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
 <clipPath id="clip">_x000D_
  <use xlink:href="#ld"/>_x000D_
 </clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
 <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How can I stream webcam video with C#?

If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.

If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.

In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.

Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

Setting default values for columns in JPA

This isn't possible in JPA.

Here's what you can do with the Column annotation: http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html

Deny access to one specific folder in .htaccess

In an .htaccess file you need to use

Deny from  all

Put this in site/includes/.htaccess to make it specific to the includes directory

If you just wish to disallow a listing of directory files you can use

Options -Indexes 

How do I run a PowerShell script when the computer starts?

I have a script that starts a file system watcher as well, but once the script window is closed the watcher dies. It will run all day if I start it from a powershell window and leave it open, but the minute I close it the script stops doing what it is supposed to.
You need to start the script and have it keep powershell open.
I tried numerous ways to do this, but the one that actually worked was from http://www.methos-it.com/blogs/keep-your-powershell-script-open-when-executed

param ( $Show )
if ( !$Show ) 
{
    PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
    return
}

Pasting that to the top of the script is what made it work.
I start the script from command line with

powershell.exe -noexit -command "& \path\to\script.ps1"

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

How to get the first word in the string

If you want to feel especially sly, you can write it as this:

(firstWord, rest) = yourLine.split(maxsplit=1)

This is supposed to bring the best from both worlds:

I kind of fell in love with this solution and it's general unpacking capability, so I had to share it.

Python circular importing?

When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import is just a command like any other (assignment, a function call, def, class). Assuming your imports occur at the top of the script, then here's what's happening:

  • When you try to import World from world, the world script gets executed.
  • The world script imports Field, which causes the entities.field script to get executed.
  • This process continues until you reach the entities.post script because you tried to import Post
  • The entities.post script causes physics module to be executed because it tries to import PostBody
  • Finally, physics tries to import Post from entities.post
  • I'm not sure whether the entities.post module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post member because it hasn't finished executing to define Post
  • Either way, an error occurs because Post is not there to be imported

So no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

Why should Java 8's Optional not be used in arguments

This is because we have different requirements to an API user and an API developer.

A developer is responsible for providing a precise specification and a correct implementation. Therefore if the developer is already aware that an argument is optional the implementation must deal with it correctly, whether it being a null or an Optional. The API should be as simple as possible to the user, and null is the simplest.

On the other hand, the result is passed from the API developer to the user. However the specification is complete and verbose, there is still a chance that the user is either unaware of it or just lazy to deal with it. In this case, the Optional result forces the user to write some extra code to deal with a possible empty result.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

NOW() function in PHP

Try this:

date("Y-m-d H:i:s");

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

How do I overload the [] operator in C#

I believe this is what you are looking for:

Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get => arr[i];
        set => arr[i] = value;
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

Why do I need to override the equals and hashCode methods in Java?

Equals and Hashcode methods in Java

They are methods of java.lang.Object class which is the super class of all the classes (custom classes as well and others defined in java API).

Implementation:

public boolean equals(Object obj)

public int hashCode()

enter image description here

public boolean equals(Object obj)

This method simply checks if two object references x and y refer to the same object. i.e. It checks if x == y.

It is reflexive: for any reference value x, x.equals(x) should return true.

It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.

For any non-null reference value x, x.equals(null) should return false.

public int hashCode()

This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method.

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

This integer need not remain consistent from one execution of an application to another execution of the same application.

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

Resources:

JavaRanch

Picture

Is there a way to use use text as the background with CSS?

Using pure CSS:

(But use this in rare occasions, because HTML method is PREFERRED WAY).

_x000D_
_x000D_
.container{_x000D_
 position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
 content:"";_x000D_
 width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1;  top: 0;   left: 0;_x000D_
 background: black;_x000D_
}_x000D_
.container::after{ _x000D_
 content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red;    text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
 animation-name: blinking;_x000D_
 animation-duration: 1s;_x000D_
 animation-iteration-count: infinite;_x000D_
 animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
 0% {opacity: 0;}_x000D_
 100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
_x000D_
_x000D_

PHP post_max_size overrides upload_max_filesize

change in php.ini max_input_vars 1000

How to allow users to check for the latest app version from inside the app?

add compile 'org.jsoup:jsoup:1.10.2' to dependencies in APP LEVEL build.gradle

&

Just add below code and you are good to go.

private class GetVersionCode extends AsyncTask<Void, String, String> {
    @Override
    protected String doInBackground(Void... voids) {

        try {
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.this.getPackageName() + "&hl=it")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div[itemprop=softwareVersion]")
                    .first()
                    .ownText();
            return newVersion;
        } catch (Exception e) {
            return newVersion;
        }
    }

    @Override
    protected void onPostExecute(String onlineVersion) {
        super.onPostExecute(onlineVersion);

        if (!currentVersion.equalsIgnoreCase(onlineVersion)) {
            //show dialog
            new AlertDialog.Builder(context)
                    .setTitle("Updated app available!")
                    .setMessage("Want to update app?")
                    .setPositiveButton("Update", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                            final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
                            try {
                                Toast.makeText(getApplicationContext(), "App is in BETA version cannot update", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                            } catch (ActivityNotFoundException anfe) {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                            }
                        }
                    })
                    .setNegativeButton("Later", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                            dialog.dismiss();
                            new MyAsyncTask().execute();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

        }
    }
}

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

Get Insert Statement for existing row in MySQL

In PHPMyAdmin you can:

  1. click copy on the row you want to know its insert statements SQL:

Select copy

  1. click Preview SQL:

Select Preview

  1. you will get the created insert statement that generates it

You can apply that on many rows at once if you select them and click copy from the bottom of the table and then Preview SQl

How to hide only the Close (x) button?

We can hide close button on form by setting this.ControlBox=false;

Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.

How to find a user's home directory on linux or unix?

If your are trying to do this for a user name that you cannot hard code, it can be challenging. Sure echo ~rbronosky would tell you the path to my home dir /home/rbronosky, but what if rbronosky is in a variable? If you do name=rbronosky; echo ~$name you get ~rbronosky

Here is a real world case and the solution:

You have a script that the user has to run via sudo. The script has to access the user's home folder. You can't reference ~/.ssh or else it will expand to /root/.ssh. Instead you do:

# Up near the top of your script add
export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
# Then you can use $HOME like you would expect
cat rsa_key.pub >> $HOME/.ssh/authorized_keys

The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~". It still works as you' expect.

If you use set -o nounset, which you should be using, the variable reference ${SUDO_USER:-} will default to blank, where $SUDO_USER or ${SUDO_USER} would give an error (because it is unset) if not run via sudo.

error: command 'gcc' failed with exit status 1 while installing eventlet

try this :

sudo apt-get install libblas-dev libatlas-base-dev

I had a similar issue on Ubuntu 14.04. For me the following Ubuntu packages

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Counting the number of occurences of characters in a string

public class StringTest{
public static void main(String[] args){

    String s ="aaabbbbccccccdd";
    String result="";
    StringBuilder sb = new StringBuilder(s);


    while(sb.length() != 0){
        int count = 0;
        char test = sb.charAt(0);
        while(sb.indexOf(test+"") != -1){
            sb.deleteCharAt(sb.indexOf(test+""));
            count++;
        }
        //System.out.println(test+" is repeated "+count+" number of times");
        result=result+test+count;
    }
    System.out.println(result);         
}
}

What is the use of ByteBuffer in Java?

Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.

We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.

ByteBuffer is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect() API on Buffer.

Java Documentation of Byte Buffer has useful information.

python replace single backslash with double backslash

Let me make it simple and clear. Lets use the re module in python to escape the special characters.

Python script :

import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)

Output :

C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop

Explanation :

Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.

Hope this helps you.

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Adding Google Play services version to your app's manifest?

Simply removing the google play services library from the project and adding once again from sdk->extras->google folder solved my problem perfectly.

JavaScript blob filename without link

window.location.assign did not work for me. it downloads fine but downloads without an extension for a CSV file on Windows platform. The following worked for me.

    var blob = new Blob([csvString], { type: 'text/csv' });
    //window.location.assign(window.URL.createObjectURL(blob));
    var link = window.document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // Construct filename dynamically and set to link.download
    link.download = link.href.split('/').pop() + '.' + extension; 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Is key-value observation (KVO) available in Swift?

You can use KVO in Swift, but only for dynamic properties of NSObject subclass. Consider that you wanted to observe the bar property of a Foo class. In Swift 4, specify bar as dynamic property in your NSObject subclass:

class Foo: NSObject {
    @objc dynamic var bar = 0
}

You can then register to observe changes to the bar property. In Swift 4 and Swift 3.2, this has been greatly simplified, as outlined in Using Key-Value Observing in Swift:

class MyObject {
    private var token: NSKeyValueObservation

    var objectToObserve = Foo()

    init() {
        token = objectToObserve.observe(\.bar) { [weak self] object, change in  // the `[weak self]` is to avoid strong reference cycle; obviously, if you don't reference `self` in the closure, then `[weak self]` is not needed
            print("bar property is now \(object.bar)")
        }
    }
}

Note, in Swift 4, we now have strong typing of keypaths using the backslash character (the \.bar is the keypath for the bar property of the object being observed). Also, because it's using the completion closure pattern, we don't have to manually remove observers (when the token falls out of scope, the observer is removed for us) nor do we have to worry about calling the super implementation if the key doesn't match. The closure is called only when this particular observer is invoked. For more information, see WWDC 2017 video, What's New in Foundation.

In Swift 3, to observe this, it's a bit more complicated, but very similar to what one does in Objective-C. Namely, you would implement observeValue(forKeyPath keyPath:, of object:, change:, context:) which (a) makes sure we're dealing with our context (and not something that our super instance had registered to observe); and then (b) either handle it or pass it on to the super implementation, as necessary. And make sure to remove yourself as an observer when appropriate. For example, you might remove the observer when it is deallocated:

In Swift 3:

class MyObject: NSObject {
    private var observerContext = 0

    var objectToObserve = Foo()

    override init() {
        super.init()

        objectToObserve.addObserver(self, forKeyPath: #keyPath(Foo.bar), options: [.new, .old], context: &observerContext)
    }

    deinit {
        objectToObserve.removeObserver(self, forKeyPath: #keyPath(Foo.bar), context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard context == &observerContext else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }

        // do something upon notification of the observed object

        print("\(keyPath): \(change?[.newKey])")
    }

}

Note, you can only observe properties that can be represented in Objective-C. Thus, you cannot observe generics, Swift struct types, Swift enum types, etc.

For a discussion of the Swift 2 implementation, see my original answer, below.


Using the dynamic keyword to achieve KVO with NSObject subclasses is described in the Key-Value Observing section of the Adopting Cocoa Design Conventions chapter of the Using Swift with Cocoa and Objective-C guide:

Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects. You can use key-value observing with a Swift class, as long as the class inherits from the NSObject class. You can use these three steps to implement key-value observing in Swift.

  1. Add the dynamic modifier to any property you want to observe. For more information on dynamic, see Requiring Dynamic Dispatch.

    class MyObjectToObserve: NSObject {
        dynamic var myDate = NSDate()
        func updateDate() {
            myDate = NSDate()
        }
    }
    
  2. Create a global context variable.

    private var myContext = 0
    
  3. Add an observer for the key-path, and override the observeValueForKeyPath:ofObject:change:context: method, and remove the observer in deinit.

    class MyObserver: NSObject {
        var objectToObserve = MyObjectToObserve()
        override init() {
            super.init()
            objectToObserve.addObserver(self, forKeyPath: "myDate", options: .New, context: &myContext)
        }
    
        override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
            if context == &myContext {
                if let newValue = change?[NSKeyValueChangeNewKey] {
                    print("Date changed: \(newValue)")
                }
            } else {
                super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
            }
        }
    
        deinit {
            objectToObserve.removeObserver(self, forKeyPath: "myDate", context: &myContext)
        }
    }
    

[Note, this KVO discussion has subsequently been removed from the Using Swift with Cocoa and Objective-C guide, which has been adapted for Swift 3, but it still works as outlined at the top of this answer.]


It's worth noting that Swift has its own native property observer system, but that's for a class specifying its own code that will be performed upon observation of its own properties. KVO, on the other hand, is designed to register to observe changes to some dynamic property of some other class.

How do you read scanf until EOF in C?

Scanf is pretty much always more trouble than it's worth. Here are two better ways to do what you're trying to do. This first one is a more-or-less direct translation of your code. It's longer, but you can look at it and see clearly what it does, unlike with scanf.

#include <stdio.h>
#include <ctype.h>
int main(void)
{
    char buf[1024], *p, *q;
    while (fgets(buf, 1024, stdin))
    {
        p = buf;
        while (*p)
        {
            while (*p && isspace(*p)) p++;
            q = p;
            while (*q && !isspace(*q)) q++;
            *q = '\0';
            if (p != q)
                puts(p);
            p = q;
        }
    }
    return 0;
}

And here's another version. It's a little harder to see what this does by inspection, but it does not break if a line is longer than 1024 characters, so it's the code I would use in production. (Well, really what I would use in production is tr -s '[:space:]' '\n', but this is how you implement something like that.)

#include <stdio.h>
#include <ctype.h>
int main(void)
{
    int ch, lastch = '\0';
    while ((ch = getchar()) != EOF)
    {
        if (!isspace(ch))
            putchar(ch);
        if (!isspace(lastch))
            putchar('\n');
        lastch = ch;
    }
    if (lastch != '\0' && !isspace(lastch))
        putchar('\n');
    return 0;
}

What is the C# equivalent of NaN or IsNumeric?

public static bool IsNumeric(string anyString)
{
    if (anyString == null)
    {
        anyString = "";
    }

    if (anyString.Length > 0)
    {
        double dummyOut = new double();
        System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
        return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
    }
    else
    {
        return false;
    }
}

java.lang.IllegalArgumentException: View not attached to window manager

Here is my "bullet proof" solution, which is compilation of all good answers that I found on this topic (thanks to @Damjan and @Kachi). Here the exception is swallowed only if all other ways of detection did not succeeded. In my case I need to close the dialog automatically and this is the only way to protect the app from crash. I hope it will help you! Please, vote and leave comments if you have remarks or better solution. Thank you!

public void dismissWithCheck(Dialog dialog) {
        if (dialog != null) {
            if (dialog.isShowing()) {

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

                // if the Context used here was an activity AND it hasn't been finished or destroyed
                // then dismiss it
                if (context instanceof Activity) {

                    // Api >=17
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
                            dismissWithTryCatch(dialog);
                        }
                    } else {

                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        if (!((Activity) context).isFinishing()) {
                            dismissWithTryCatch(dialog);
                        }
                    }
                } else
                    // if the Context used wasn't an Activity, then dismiss it too
                    dismissWithTryCatch(dialog);
            }
            dialog = null;
        }
    }

    public void dismissWithTryCatch(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (final IllegalArgumentException e) {
            // Do nothing.
        } catch (final Exception e) {
            // Do nothing.
        } finally {
            dialog = null;
        }
    }

Regular Expression - 2 letters and 2 numbers in C#

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}

How can I save multiple documents concurrently in Mongoose/Node.js?

You can use the promise returned by mongoose save, Promise in mongoose does not have all, but you can add the feature with this module.

Create a module that enhance mongoose promise with all.

var Promise = require("mongoose").Promise;

Promise.all = function(promises) {
  var mainPromise = new Promise();
  if (promises.length == 0) {
    mainPromise.resolve(null, promises);
  }

  var pending = 0;
  promises.forEach(function(p, i) {
    pending++;
    p.then(function(val) {
      promises[i] = val;
      if (--pending === 0) {
        mainPromise.resolve(null, promises);
      }
    }, function(err) {
      mainPromise.reject(err);
    });
  });

  return mainPromise;
}

module.exports = Promise;

Then use it with mongoose:

var Promise = require('./promise')

...

var tasks = [];

for (var i=0; i < docs.length; i++) {
  tasks.push(docs[i].save());
}

Promise.all(tasks)
  .then(function(results) {
    console.log(results);
  }, function (err) {
    console.log(err);
  })

Credentials for the SQL Server Agent service are invalid

I solved using as credential built-in accounts as the NetworkService this article point me out in the right direction http://www.sqlcoffee.com/SQLServer2008_0013.htm

What is the purpose of Order By 1 in SQL select statement?

As mentioned in other answers ORDER BY 1 orders by the first column.

I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name in the below.

SELECT Name, Name FROM Segment ORDER BY 1

How do I reference the input of an HTML <textarea> control in codebehind?

First make sure you have the runat="server" attribute in your textarea tag like this

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

Then you can access the content via:

string body = TextArea1.value;

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Difference between "read commited" and "repeatable read"

Repeatable Read

The state of the database is maintained from the start of the transaction. If you retrieve a value in session1, then update that value in session2, retrieving it again in session1 will return the same results. Reads are repeatable.

session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron

session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;

session1> SELECT firstname FROM names WHERE id = 7;
Aaron

Read Committed

Within the context of a transaction, you will always retrieve the most recently committed value. If you retrieve a value in session1, update it in session2, then retrieve it in session1again, you will get the value as modified in session2. It reads the last committed row.

session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron

session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;

session1> SELECT firstname FROM names WHERE id = 7;
Bob

Makes sense?

Display HTML form values in same page after submit using Ajax

_x000D_
_x000D_
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
  modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
  if (event.target == modal) {_x000D_
    modal.style.display = "none";_x000D_
  }_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
  var temp = 'style .fa fa-trash';_x000D_
  tasks.push(document.getElementById("taskname").value);_x000D_
  descs.push(document.getElementById("taskdesc").value);_x000D_
  var table = document.getElementById("tasksTable");_x000D_
  var row = table.insertRow(rowCount);_x000D_
  var cell1 = row.insertCell(0);_x000D_
  var cell2 = row.insertCell(1);_x000D_
  var cell3 = row.insertCell(2);_x000D_
  var cell4 = row.insertCell(3);_x000D_
  cell1.innerHTML = tasks[rowCount - 1];_x000D_
  cell2.innerHTML = descs[rowCount - 1];_x000D_
  cell3.innerHTML = getDate();_x000D_
  cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
  rowCount++;_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
  var today = new Date();_x000D_
  var dd = today.getDate();_x000D_
  var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
  var yyyy = today.getFullYear();_x000D_
_x000D_
  if (dd < 10) {_x000D_
    dd = '0' + dd;_x000D_
  }_x000D_
  if (mm < 10) {_x000D_
    mm = '0' + mm;_x000D_
  }_x000D_
  var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
  return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <!-- Trigger/Open The Modal -->_x000D_
  <div style="background-color:#0F0F8C ;height:45px">_x000D_
    <h2 style="color: white">LOGO</h2>_x000D_
  </div>_x000D_
  <div>_x000D_
    <button id="myBtn">&emsp;+ Add Task &emsp;</button>_x000D_
  </div>_x000D_
  <div>_x000D_
    <table id="tasksTable">_x000D_
      <thead>_x000D_
        <tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
          <th style="width: 150px;">Name</th>_x000D_
          <th style="width: 250px;">Desc</th>_x000D_
          <th style="width: 120px">Date</th>_x000D_
          <th style="width: 120px class=fa fa-trash"></th>_x000D_
        </tr>_x000D_
_x000D_
      </thead>_x000D_
      <tbody></tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
  <!-- The Modal -->_x000D_
  <div id="myModal" class="modal">_x000D_
_x000D_
    <!-- Modal content -->_x000D_
    <div class="modal-content">_x000D_
_x000D_
      <div class="modal-header">_x000D_
_x000D_
        <span class="close">&times;</span>_x000D_
        <h3> Add Task</h3>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-body">_x000D_
        <table style="padding: 28px 50px">_x000D_
          <tr>_x000D_
            <td style="width:150px">Name:</td>_x000D_
            <td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              Desc:_x000D_
            </td>_x000D_
            <td>_x000D_
              <textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-footer">_x000D_
        <button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
        <br>_x000D_
        <br>_x000D_
        <br>_x000D_
      </div>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Checking images for similarity with OpenCV

A little bit off topic but useful is the pythonic numpy approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):

A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by

import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))

After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:

1) If you compare similar pictures the sum will return 1:

In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0

2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):

In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822

Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.

Convert integer to hexadecimal and back again

int to hex:

int a = 72;

Console.WriteLine("{0:X}", a);

hex to int:

int b = 0xB76;

Console.WriteLine(b);

Numpy matrix to array

If you'd like something a bit more readable, you can do this:

A = np.squeeze(np.asarray(M))

Equivalently, you could also do: A = np.asarray(M).reshape(-1), but that's a bit less easy to read.

How to send FormData objects with Ajax-requests in jQuery?

I believe you could do it like this :

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Notes:

  • Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

  • Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

WAMP Cannot access on local network 403 Forbidden

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.

Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Require local
    Require ip 192.168.0

The Require local allows access from these ip's 127.0.0.1 & localhost & ::1.

The statement Require ip 192.168.0 will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so you have to make the access privilage amendements in the Virtual Host definition config file

First dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Hopefully you will have created a Virtual Host for your project and not be using the wamp\www folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.

Dont forget to restart Apache after making this change

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Regex to remove all special characters from string?

Depending on your definition of "special character", I think "[^a-zA-Z0-9]" would probably do the trick. That would find anything that is not a small letter, a capital letter, or a digit.

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

CSS white space at bottom of page despite having both min-height and height tag

This will remove the margin and padding from your page elements, since there is a paragraph with a script inside that is causing an added margin. this way you should reset it and then you can style the other elements of your page, or you could give that paragraph an id and set margin to zero only for it.

<style>
* {
   margin: 0;
   padding: 0;
}
</style>

Try to put this as the first style.

Image style height and width not taken in outlook mails

This works for me in Outlook:

<img src="image.jpg" width="120" style="display:block;width:100%" />

I hope it works for you.

What is the difference between Python and IPython?

From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd and ls don't work alone in base Python. However they will work if prefaced with a % such as: %pwd and %ls.

Also, in IPython, you can run the cd command like: cd C:\Users\... This doesn't seem to work in base python, even when prefaced with a % however.

Get domain name from given url

import java.net.*;
import java.io.*;

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

    URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                       + "/index.html?name=networking#DOWNLOADING");

    System.out.println("protocol = " + aURL.getProtocol()); //http
    System.out.println("authority = " + aURL.getAuthority()); //example.com:80
    System.out.println("host = " + aURL.getHost()); //example.com
    System.out.println("port = " + aURL.getPort()); //80
    System.out.println("path = " + aURL.getPath()); //  /docs/books/tutorial/index.html
    System.out.println("query = " + aURL.getQuery()); //name=networking
    System.out.println("filename = " + aURL.getFile()); ///docs/books/tutorial/index.html?name=networking
    System.out.println("ref = " + aURL.getRef()); //DOWNLOADING
  }
}

Read more

Use custom build output folder when using create-react-app

webpack =>

renamed as build to dist

output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

What is the purpose of XSD files?

XSDs constrain the vocabulary and structure of XML documents.

  • Without an XSD, an XML document need only follow the rules for being well-formed as given in the W3C XML Recommendation.
  • With an XSD, an XML document must adhere to additional constraints placed upon the names and values of its elements and attributes in order to be considered valid against the XSD per the W3C XML Schema Recommendation.

XML is all about agreement, and XSDs provide the means for structuring and communicating the agreement beyond the basic definition of XML itself.

Python "expected an indented block"

The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

src: ##

##https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator

Selecting with complex criteria from pandas.DataFrame

You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)

df[['A']][df.B.gt(50) & df.C.ne(900)]

df[['A']] will give you back column A in DataFrame format.

pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.

Can you control how an SVG's stroke-width is drawn?

Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:

var getStrokeOffsets = function(stroke){

        var strokeFloor =       Math.floor(stroke / 2),                                                                 // max offset
            strokeCeil =        Math.ceil(stroke / 2);                                                                  // min offset

        if($.browser.mozilla){                                                                                          // Mozilla offsets

            return {
                bottom:     strokeFloor,
                left:       strokeFloor,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }else if($.browser.webkit){                                                                                     // WebKit offsets

            return {
                bottom:     strokeCeil,
                left:       strokeFloor,
                top:        strokeFloor,
                right:      strokeCeil
            };

        }else{                                                                                                          // default offsets

            return {
                bottom:     strokeCeil,
                left:       strokeCeil,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }

    };

How to set border's thickness in percentages?

You can use em for percentage instead of pixels,

Example:

border:10PX dotted #c1a9ff; /* In Pixels */
border:0.75em dotted #c1a9ff; /* Exact same as above in Percentage */

Condition within JOIN or WHERE

WHERE will filter after the JOIN has occurred.

Filter on the JOIN to prevent rows from being added during the JOIN process.

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

What is bootstrapping?

Bootstrapping has yet another meaning in the context of reinforcement learning that may be useful to know for developers, in addition to its use in software development (most answers here, e.g. by kdgregory) and its use in statistics as discussed by Dirk Eddelbuettel.

From Sutton and Barto:

Widrow, Gupta, and Maitra (1973) modified the Least-Mean-Square (LMS) algorithm of Widrow and Hoff (1960) to produce a reinforcement learning rule that could learn from success and failure signals instead of from training examples. They called this form of learning “selective bootstrap adaptation” and described it as “learning with a critic” instead of “learning with a teacher.” They analyzed this rule and showed how it could learn to play blackjack. This was an isolated foray into reinforcement learning by Widrow, whose contributions to supervised learning were much more influential.

The book describes various reinforcement algorithms where the target value is based on a previous approximation as bootstrap methods:

Finally, we note one last special property of DP [Dynamic Programming] methods. All of them update estimates of the values of states based on estimates of the values of successor states. That is, they update estimates on the basis of other estimates. We call this general idea bootstrapping. Many reinforcement learning methods perform bootstrapping, even those that do not require, as DP requires, a complete and accurate model of the environment.

Note that this differs from bootstrap aggregating and intelligence explosion that is mentioned on the wikipedia page on bootstrapping.

convert iso date to milliseconds in javascript

Try this

_x000D_
_x000D_
var date = new Date("11/21/1987 16:00:00"); // some mock date_x000D_
var milliseconds = date.getTime(); _x000D_
// This will return you the number of milliseconds_x000D_
// elapsed from January 1, 1970 _x000D_
// if your date is less than that date, the value will be negative_x000D_
_x000D_
console.log(milliseconds);
_x000D_
_x000D_
_x000D_

EDIT

You've provided an ISO date. It is also accepted by the constructor of the Date object

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var result = myDate.getTime();_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Edit

The best I've found is to get rid of the offset manually.

_x000D_
_x000D_
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var offset = myDate.getTimezoneOffset() * 60 * 1000;_x000D_
_x000D_
var withOffset = myDate.getTime();_x000D_
var withoutOffset = withOffset - offset;_x000D_
console.log(withOffset);_x000D_
console.log(withoutOffset);
_x000D_
_x000D_
_x000D_

Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.

EDIT

Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.

Is it correct to use alt tag for an anchor link?

Such things are best answered by looking at the official specification:

  1. go to the specification: https://www.w3.org/TR/html5/

  2. search for "a element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element

  3. check "Content attributes", which lists all allowed attributes for the a element:

    • Global attributes
    • href
    • target
    • download
    • rel
    • hreflang
    • type
  4. check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes

As you will see, the alt attribute is not allowed on the a element.
Also you’d notice that the src attribute isn’t allowed either.

By validating your HTML, errors like these are reported to you.


Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a element can have another attribute in HTML 5.1: rev.

You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.

What is :: (double colon) in Python when subscripting sequences?

Explanation

s[i:j:k] is, according to the documentation, "slice of s from i to j with step k". When i and j are absent, the whole sequence is assumed and thus s[::k] means "every k-th item".

Examples

First, let's initialize a list:

>>> s = range(20)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Let's take every 3rd item from s:

>>> s[::3]
[0, 3, 6, 9, 12, 15, 18]

Let's take every 3rd item from s[2:]:

>>> s[2:]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> s[2::3]
[2, 5, 8, 11, 14, 17]

Let's take every 3rd item from s[5:12]:

>>> s[5:12]
[5, 6, 7, 8, 9, 10, 11]
>>> s[5:12:3]
[5, 8, 11]

Let's take every 3rd item from s[:10]:

>>> s[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s[:10:3]
[0, 3, 6, 9]

How can I get the browser's scrollbar sizes?

window.scrollBarWidth = function() {
  document.body.style.overflow = 'hidden'; 
  var width = document.body.clientWidth;
  document.body.style.overflow = 'scroll'; 
  width -= document.body.clientWidth; 
  if(!width) width = document.body.offsetWidth - document.body.clientWidth;
  document.body.style.overflow = ''; 
  return width; 
} 

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Static array vs. dynamic array in C++

Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.

int arr[] = { 1, 3, 4 }; // static integer array.   
int* arr = new int[3]; // dynamic integer array.

What is difference between monolithic and micro kernel?

Monolithic kernel

All the parts of a kernel like the Scheduler, File System, Memory Management, Networking Stacks, Device Drivers, etc., are maintained in one unit within the kernel in Monolithic Kernel

Advantages

•Faster processing

Disadvantages

•Crash Insecure •Porting Inflexibility •Kernel Size explosion

Examples •MS-DOS, Unix, Linux

Micro kernel

Only the very important parts like IPC(Inter process Communication), basic scheduler, basic memory handling, basic I/O primitives etc., are put into the kernel. Communication happen via message passing. Others are maintained as server processes in User Space

Advantages

•Crash Resistant, Portable, Smaller Size

Disadvantages

•Slower Processing due to additional Message Passing

Examples •Windows NT

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

try

html, body {
  overflow-x:hidden 
} 

instead of just

body {
  overflow-x:hidden 
}

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

ASP.NET MVC Razor render without encoding

HTML RAW :

@Html.Raw(yourString)

String to Binary in C#

The following will give you the hex encoding for the low byte of each character, which looks like what you're asking for:

StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
    uint i = (uint)c;
    sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

Constructor in an Interface?

An interface defines a contract for an API, that is a set of methods that both implementer and user of the API agree upon. An interface does not have an instanced implementation, hence no constructor.

The use case you describe is akin to an abstract class in which the constructor calls a method of an abstract method which is implemented in an child class.

The inherent problem here is that while the base constructor is being executed, the child object is not constructed yet, and therfore in an unpredictable state.

To summarize: is it asking for trouble when you call overloaded methods from parent constructors, to quote mindprod:

In general you must avoid calling any non-final methods in a constructor. The problem is that instance initialisers / variable initialisation in the derived class is performed after the constructor of the base class.

Reinitialize Slick js after successful ajax call

The best way would be to use the unslick setting or function(depending on your version of slick) as stated in the other answers but that did not work for me. I'm getting some errors from slick that seem to be related to this.

What did work for now, however, is removing the slick-initialized and slick-slider classes from the container before reinitializing slick, like so:

function slickCarousel() {
    $('.skills_section').removeClass("slick-initialized slick-slider");
    $('.skills_section').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1
    });
}

Removing the classes doesn't seem to initiate the destroy event(not tested but makes sense) but does cause the later slick() call to behave properly so as long as you don't have any triggers on destroy, you should be good.

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

Placing/Overlapping(z-index) a view above another view in android

Try this in a RelativeLayout:

ImageView image = new ImageView(this);
image.SetZ(float z);

It works for me.

Multiple left joins on multiple tables in one query

You can do like this

SELECT something
FROM
    (a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'

How do you execute an arbitrary native command from a string?

The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression after all.

I finally came across this nice template for seeing how to execute uninstall strings:

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path | 
    Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} | 
    ForEach-Object -process {$apps.Set_Item(
        $_.getvalue('UninstallString'),
        $_.getvalue('DisplayName'))
    }

foreach ($uninstall_string in $apps.GetEnumerator()) {
    $uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
    & $uninstall_app $uninstall_arg
}

This works for me, namely because $app is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.

Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe, so there's that too.

How can I display just a portion of an image in HTML/CSS?

As mentioned in the question, there is the clip css property, although it does require that the element being clipped is position: absolute; (which is a shame):

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
}_x000D_
#clip {_x000D_
  position: absolute;_x000D_
  clip: rect(0, 100px, 200px, 0);_x000D_
  /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path, which has replaced the now-deprecated clip property.

The clip-path property allows a range of options (more-so than the original clip), of:

  • inset — rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left).
  • circlecircle(diameter at x-coordinate y-coordinate).
  • ellipseellipse(x-axis-length y-axis-length at x-coordinate y-coordinate).
  • polygon — defined by a series of x/y coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]).
  • url — this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.

_x000D_
_x000D_
div.container {_x000D_
  display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
  -webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
  clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
  -webkit-clip-path: circle(75px at 50% 50%);_x000D_
  clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
  -webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
  clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
  -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
  clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
  <img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

References:

Adding IN clause List to a JPA Query

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

Laravel use same form for create and edit

I like to use form model binding so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user model for example):

@if(isset($user))
    {{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
@else
    {{ Form::open(['route' => 'createroute']) }}
@endif

    {{ Form::text('fieldname1', Input::old('fieldname1')) }}
    {{ Form::text('fieldname2', Input::old('fieldname2')) }}
    {{-- More fields... --}}
    {{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}

So, for example, from a controller, I basically use the same form for creating and updating, like:

// To create a new user
public function create()
{
    // Load user/createOrUpdate.blade.php view
    return View::make('user.createOrUpdate');
}

// To update an existing user (load to edit)
public function edit($id)
{
    $user = User::find($id);
    // Load user/createOrUpdate.blade.php view
    return View::make('user.createOrUpdate')->with('user', $user);
}

Regex Email validation

This one prevents invalid emails mentioned by others in the comments:

[email protected]
[email protected]
name@hotmail
[email protected]
[email protected]

It also prevents emails with double dots:

[email protected]

Try testing it with as many invalid email addresses as you can find.

using System.Text.RegularExpressions;

public static bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
        && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}

See validate email address using regular expression in C#.

Check object empty

I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.

To check for Collection be empty or null

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

or use Apache Commons CollectionUtils.isEmpty()

To check if Map is empty or null

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

or use Apache Commons MapUtils.isEmpty()

To check for String empty or null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

or use Apache Commons StringUtils.isBlank()

To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

In Postgres, you can make almost any single value query return a value or null by wrapping it:

SELECT (SELECT <query>) AS value

and hence avoid complexity in the caller.

Keep the order of the JSON keys during JSON conversion to CSV

The most safe way is probably overriding keys method that is used to generate output:

new JSONObject(){
  @Override
  public Iterator keys(){
    TreeSet<Object> sortedKeys = new TreeSet<Object>();
    Iterator keys = super.keys();
    while(keys.hasNext()){
      sortedKeys.add(keys.next());
    }
    return sortedKeys.iterator();
  }
};

jQuery: Setting select list 'selected' based on text, failing strangely

If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:

    <select id="selectcountry">
    <option value="1">India</option>
    <option value="2">Ireland</option>
    </select>
    <script>
     var country_name ='India'
     $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
    </script>

How to insert values in two dimensional array programmatically?

In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

In this case you could use a Map of Strings to Lists of Strings:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
        Map<String, List<String>> shades = new HashMap<>();

        ArrayList<String> shadesOfGrey = new ArrayList<>();
        shadesOfGrey.add("lightgrey");
        shadesOfGrey.add("dimgray");
        shadesOfGrey.add("sgi gray 92");

        ArrayList<String> shadesOfBlue = new ArrayList<>();
        shadesOfBlue.add("dodgerblue 2");
        shadesOfBlue.add("steelblue 2");
        shadesOfBlue.add("powderblue");

        ArrayList<String> shadesOfYellow = new ArrayList<>();
        shadesOfYellow.add("yellow 1");
        shadesOfYellow.add("gold 1");
        shadesOfYellow.add("darkgoldenrod 1");

        ArrayList<String> shadesOfRed = new ArrayList<>();
        shadesOfRed.add("indianred 1");
        shadesOfRed.add("firebrick 1");
        shadesOfRed.add("maroon 1");

        shades.put("greys", shadesOfGrey);
        shades.put("blues", shadesOfBlue);
        shades.put("yellows", shadesOfYellow);
        shades.put("reds", shadesOfRed);

        System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
    }
}

How to validate white spaces/empty spaces? [Angular 2]

If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

and then in your component typescript file use the validator like this for example.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});

No Android SDK found - Android Studio

Here is the solution just copy your SDK Manager.exe file at the root folder of your android studio's installation, Sync your project and cheers... here is the link for details. running Android Studio on Windows 7 fails, no Android SDK found

Comparing Class Types in Java

Try this:

MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true

Because of inheritance this is valid for interfaces, too:

class Animal {}
class Dog extends Animal {}    

Dog obj = new Dog();
Animal animal = new Dog();
if(obj instanceof Animal){System.out.println("true");} //true
if(animal instanceof Animal){System.out.println("true");} //true
if(animal instanceof Dog){System.out.println("true");} //true

For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

How to set the authorization header using curl

http://curl.haxx.se/docs/httpscripting.html

See part 6. HTTP Authentication

HTTP Authentication

HTTP Authentication is the ability to tell the server your username and password so that it can verify that you're allowed to do the request you're doing. The Basic authentication used in HTTP (which is the type curl uses by default) is plain text based, which means it sends username and password only slightly obfuscated, but still fully readable by anyone that sniffs on the network between you and the remote server.

To tell curl to use a user and password for authentication:

curl --user name:password http://www.example.com

The site might require a different authentication method (check the headers returned by the server), and then --ntlm, --digest, --negotiate or even --anyauth might be options that suit you.

Sometimes your HTTP access is only available through the use of a HTTP proxy. This seems to be especially common at various companies. A HTTP proxy may require its own user and password to allow the client to get through to the Internet. To specify those with curl, run something like:

curl --proxy-user proxyuser:proxypassword curl.haxx.se

If your proxy requires the authentication to be done using the NTLM method, use --proxy-ntlm, if it requires Digest use --proxy-digest.

If you use any one these user+password options but leave out the password part, curl will prompt for the password interactively.

Do note that when a program is run, its parameters might be possible to see when listing the running processes of the system. Thus, other users may be able to watch your passwords if you pass them as plain command line options. There are ways to circumvent this.

It is worth noting that while this is how HTTP Authentication works, very many web sites will not use this concept when they provide logins etc. See the Web Login chapter further below for more details on that.

Could not install packages due to an EnvironmentError: [Errno 13]

Regarding the permissions command, try using sudo in front of your terminal command:

sudo pip install --upgrade pip

Sudo allows you to run the command with the privileges of the superuser and will install the package for the global, system-wide Python installation. Ideally, you should create a virtual environment for the project you are working on. Have a look at this

Regarding the python Try running pip as an executable like this:

python3.6 -m pip install <package>

How can I check if an element exists in the visible DOM?

I liked this approach:

var elem = document.getElementById('elementID');

if (elem)
    do this
else
    do that

Also

var elem = ((document.getElementById('elemID')) ? true:false);

if (elem)
    do this
else
    do that

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

In Python, how do I use urllib to see if a website is 404 or 200?

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

How to set the Android progressbar's height?

<ProgressBar  
android:minHeight="20dip" 
android:maxHeight="20dip"/>

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

In my case it was fixed by adding a reference to the constraint-layout package

    implementation 'com.android.support.constraint:constraint-layout:1.1.0'

Finding duplicate values in a SQL table

SELECT id, COUNT(id) FROM table1 GROUP BY id HAVING COUNT(id)>1;

I think this will work properly to search repeated values in a particular column.

How can I hide an HTML table row <tr> so that it takes up no space?

I would really like to see your TABLE's styling. E.g. "border-collapse"

Just a guess, but it might affect how 'hidden' rows are being rendered.

Excel date to Unix timestamp

None of the current answers worked for me because my data was in this format from the unix side:

2016-02-02 19:21:42 UTC

I needed to convert this to Epoch to allow referencing other data which had epoch timestamps.

  1. Create a new column for the date part and parse with this formula

    =DATEVALUE(MID(A2,6,2) & "/" & MID(A2,9,2) & "/" & MID(A2,1,4)) 
    
  2. As other Grendler has stated here already, create another column

    =(B2-DATE(1970,1,1))*86400 
    
  3. Create another column with just the time added together to get total seconds:

    =(VALUE(MID(A2,12,2))*60*60+VALUE(MID(A2,15,2))*60+VALUE(MID(A2,18,2)))
    
  4. Create a last column that just adds the last two columns together:

    =C2+D2
    

How to programmatically set drawableLeft on Android button?

You can use the setCompoundDrawables method to do this. See the example here. I used this without using the setBounds and it worked. You can try either way.

UPDATE: Copying the code here incase the link goes down

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);

or

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);

or

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

Absolute positioning ignoring padding of parent

I would set the child's width this way:

.child {position: absolute; width: calc(100% - padding);}

Padding, in the formula, is the sum of the left and right parent's padding. I admit it is probably not very elegant, but in my case, a div with the function of an overlay, it worked.

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

How to make gradient background in android

Following link may help you http://angrytools.com/gradient/ .This will create custom gradient background in android as like in photoshop.

How to use code to open a modal in Angular 2?

Simply, npm install --save @types/bootstrap try to match typing version with your bootstrap version. E.g. you have Bootstrap 4.3.1 then npm install --save @types/[email protected]

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

How to write a cron that will run a script every day at midnight?

from the man page

linux$ man -S 5 crontab

   cron(8) examines cron entries once every minute.

   The time and date fields are:

          field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sun, or use names)
   ...
   # run five minutes after midnight, every day
   5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
   ...

It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.

   # Run once after reboot.
   @reboot         /usr/local/sbin/run_only_once_after_reboot.sh

You can also use this trick to run your cron job multiple times per minute.

   # Run every minute at 0, 20, and 40 second intervals
   * * * * *       sleep 00; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 20; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 40; /usr/local/sbin/run_3times_per_minute.sh

To add a cron job, you can do one of three things:

  1. add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).

    • edit a user's crontab as root with crontab -e -u <username>
    • or edit the current user's crontab with just crontab -e
    • You can set the editor with the EDITOR environment variable
      • env EDITOR=nano crontab -e -u <username>
      • or set the value of EDITOR for your entire shell session
        1. export EDITOR=vim
        2. crontab -e
    • Make scripts executable with chmod a+x <file>


  1. create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly directories

    • anacron /etc/cron.*ly directories:
      • /etc/cron.daily
      • /etc/cron.hourly
      • /etc/cron.monthly
      • /etc/cron.weekly
    • as in:
      • /etc/cron.daily/script_runs_daily.sh
      • chmod a+x /etc/cron.daily/script_runs_daily.sh -- make it executable
    • See also the anacron man page: man anacron
    • Make scripts executable with chmod a+x <file>
    • When do these cron.*ly script run?
      • For RHEL/CentOS 5.x, they are configured in /etc/crontab or /etc/anacrontab to run at a set time
      • RHEL/CentOS 6.x+ and Fedora 17+ Linux systems only define this in /etc/anacrontab, and define cron.hourly in /etc/cron.d/0hourly


  1. Or, One can create system crontables in /etc/cron.d.

    • The previously described crontab syntax (with additionally providing a user to execute each job as) is put into a file, and the file is dropped into the /etc/cron.d directory.
    • These are easy to manage in system packaging (e.g. RPM packages), so may usually be application specific.
    • The syntax difference is that a user must be specified for the cron job after the time/date fields and before the command to execute.
    • The files added to /etc/cron.d do not need to be executable.
    • Here is an example job that is executed as the user someuser, and the use of /bin/bash as the shell is forced.


   File: /etc/cron.d/myapp-cron
   # use /bin/bash to run commands, no matter what /etc/passwd says
   SHELL=/bin/bash
   # Execute a nightly (11:00pm) cron job to scrub application records
   00 23 * * * someuser /opt/myapp/bin/scrubrecords.php

Beginner Python Practice?

Try this site full of Python Practice Problems. It leans towards problems that has already been solved so that you'll have reference solutions.

localhost refused to connect Error in visual studio

In my case, Visual Studio 2017 > Tools > Options

In Debugging menu in the side list find Edit and Continue

Uncheck the Enable Edit and Continue check box

This resolves my problem.

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

Try/catch does not seem to have an effect

This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.

try {
    Set-Location "$YourPath" -ErrorAction Stop;
} catch {
    Write-Host "Exception has been caught";
}

How to remove an iOS app from the App Store

What you need to do is this.

  1. Go to “Manage Your Applications” and select the app.
  2. Click “Rights and Pricing” (blue button at the top right.
  3. Below the availability date and price tier section, you should see a grid of checkboxes for the various countries your app is available in. Click the blue “Deselect All” button.
  4. Click “Save Changes” at the bottom.

Your app's state will then be “Developer Removed From Sale”, and it will no longer be available on the App Store in any country.

How to suspend/resume a process in Windows?

I use (a very old) process explorer from SysInternals (procexp.exe). It is a replacement / addition to the standard Task manager, you can suspend a process from there.

Edit: Microsoft has bought over SysInternals, url: procExp.exe

Other than that you can set the process priority to low so that it does not get in the way of other processes, but this will not suspend the process.

How does ApplicationContextAware work in Spring?

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.

So, it seemed to be invoked when Spring container has started, if you want to do something at that time.

It just has one method to set the context, so you will get the context and do something to sth now already in context I think.

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

How do you put an image file in a json object?

To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.

Tell me which backend technology are you using? I can give more suggestions based on that.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

App.Config change value

    private static string GetSetting(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }

    private static void SetSetting(string key, string value)
    {
        Configuration configuration =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save(ConfigurationSaveMode.Full, true);
        ConfigurationManager.RefreshSection("appSettings");
    }

What is the maximum length of a table name in Oracle?

In Oracle 12.1 and below: 30 char (bytes, really, as has been stated).

But do not trust me; try this for yourself:

SQL> create table I23456789012345678901234567890 (my_id number);

Table created.



SQL> create table I234567890123456789012345678901(my_id number);


ERROR at line 1:

ORA-00972: identifier is too long

Updated: as stated above, in Oracle 12.2 and later, the maximum object name length is now 128 bytes.

jquery ajax get responsetext from http url

First you have to download a JQuery plugin to allow Cross-domain requests. Download it here: https://github.com/padolsey/jQuery-Plugins/downloads

Import the file called query.xdomainsajax.js into your project and include it with this code:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

To get the html of an external web page in text form you can write this:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});

Convert JSON array to an HTML table in jQuery

Make a HTML Table from a JSON array of Objects by extending $ as shown below

$.makeTable = function (mydata) {
    var table = $('<table border=1>');
    var tblHeader = "<tr>";
    for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
    tblHeader += "</tr>";
    $(tblHeader).appendTo(table);
    $.each(mydata, function (index, value) {
        var TableRow = "<tr>";
        $.each(value, function (key, val) {
            TableRow += "<td>" + val + "</td>";
        });
        TableRow += "</tr>";
        $(table).append(TableRow);
    });
    return ($(table));
};

and use as follows:

var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");

where TableCont is some div

Does VBA contain a comment block syntax?

prefix the comment with a single-quote. there is no need for an "end" tag.

'this is a comment

Extend to multiple lines using the line-continuation character, _:

'this is a multi-line _
   comment

This is an option in the toolbar to select a line(s) of code and comment/uncomment:

enter image description here

Notification Icon with the new Firebase Cloud Messaging system

I'm triggering my notifications from FCM console and through HTTP/JSON ... with the same result.

I can handle the title, full message, but the icon is always a default white circle:

Notification screenshot

Instead of my custom icon in the code (setSmallIcon or setSmallIcon) or default icon from the app:

 Intent intent = new Intent(this, MainActivity.class);
    // use System.currentTimeMillis() to have a unique ID for the pending intent
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    if (Build.VERSION.SDK_INT < 16) {
        Notification n  = new Notification.Builder(this)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true).getNotification();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //notificationManager.notify(0, n);
        notificationManager.notify(id, n);
    } else {
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        Notification n  = new Notification.Builder(this)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setLargeIcon(bm)
                .setContentIntent(pIntent)
                .setAutoCancel(true).build();

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //notificationManager.notify(0, n);
        notificationManager.notify(id, n);
    }

ImportError: No module named requests

In the terminal/command-line:

pip install requests 

then use it inside your Python script by:

import requests

or else if you want to use pycharm IDE to install a package:

  1. go to setting from File in menu
  2. next go to Python interpreter
  3. click on pip
  4. search for requests package and install it

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.

It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER.

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

How to decode JWT Token?

  var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  var claims = new[]
  {
      new Claim(JwtRegisteredClaimNames.Email, model.UserName),
      new Claim(JwtRegisteredClaimNames.NameId, model.Id.ToString()),
  };
  var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      _config["Jwt:Issuer"],
      claims,
      expires: DateTime.Now.AddMinutes(30),
      signingCredentials: creds);

Then extract content

 var handler = new JwtSecurityTokenHandler();
 string authHeader = Request.Headers["Authorization"];
 authHeader = authHeader.Replace("Bearer ", "");
 var jsonToken = handler.ReadToken(authHeader);
 var tokenS = handler.ReadToken(authHeader) as JwtSecurityToken;
 var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;

Editor does not contain a main type

For me, in Eclipse 3.6, this problem occurs when my main method is not public. I caused the problem by having a main method like this:

static void main(String[] args) 

The dubugger was unable to detect this by itself. I am pretty suprised Eclipse overlooked this.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

You may use Oracle pipelined functions

Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.

Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?

create type array
as table of number;


create function  gen_numbers(n in number default null)
return array
PIPELINED
as
begin
  for i in 1 .. nvl(n,999999999)
  loop
     pipe row(i);
 end loop;
 return;
end;

Suppose we needed three rows for something. We can now do that in one of two ways:

select * from TABLE(gen_numbers(3));

COLUMN_VALUE


       1
       2
       3

or

select * from TABLE(gen_numbers)
 where rownum <= 3;

COLUMN_VALUE


       1
       2
       3

pipelied Functions1 pipelied Functions2

Need to navigate to a folder in command prompt

In MS-DOS COMMAND.COM shell, you have to use:

d:

cd \windows\movie

If by chance you actually meant "Windows command prompt" (which is not MS-DOS and not DOS at all), then you can use cd /d d:\windows\movie.

std::vector versus std::array in C++

If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.

Given the following declarations:

int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc;      // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc;    // initialized to [3][5]

A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.

A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.

This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.

This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.

How to create a file on Android Internal Storage?

I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

If you execute the following statement:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();

It will resolve the path to the root /data/ somewhere higher up in Android.

I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();

A quick fix would be to change your following code:

File f = new File(getLocalPath().replace("/data/data/", "/"));

Hope this helps

Instagram API - How can I retrieve the list of people a user is following on Instagram

Shiva's answer doesn't apply anymore. The API call "/users/{user-id}/follows" is not supported by Instagram for some time (it was disabled in 2016).

For a while you were able to get only your own followers/followings with "/users/self/follows" endpoint, but Instagram disabled that feature in April 2018 (with the Cambridge Analytica issue). You can read about it here.

As far as I know (at this moment) there isn't a service available (official or unofficial) where you can get the followers/followings of a user (even your own).

Best way to parse command line arguments in C#?

I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.\n" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}

How to present a simple alert message in java?

Call "setWarningMsg()" Method and pass the text that you want to show.

exm:- setWarningMsg("thank you for using java");


public static void setWarningMsg(String text){
    Toolkit.getDefaultToolkit().beep();
    JOptionPane optionPane = new JOptionPane(text,JOptionPane.WARNING_MESSAGE);
    JDialog dialog = optionPane.createDialog("Warning!");
    dialog.setAlwaysOnTop(true);
    dialog.setVisible(true);
}

Or Just use

JOptionPane optionPane = new JOptionPane("thank you for using java",JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true); // to show top of all other application
dialog.setVisible(true); // to visible the dialog

You can use JOptionPane. (WARNING_MESSAGE or INFORMATION_MESSAGE or ERROR_MESSAGE)

Adding a newline into a string in C#

Based on your replies to everyone else, something like this is what you're looking for.

string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

using (StreamWriter writer = new StreamWriter(file))
{
    foreach (string line in lines)
    {
        writer.WriteLine(line + "@");
    }
}

Activating Anaconda Environment in VsCode

I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.

So your only python path in env var should be like:

"C:\Anaconda3\envs\py34\", or wherever the python executable lives

If you need more details I don't mind explaining. :)

How can we print line numbers to the log in java

Below code is tested code for logging line no class name and method name from where logging method is called

public class Utils {
/*
 * debug variable enables/disables all log messages to logcat
 * Useful to disable prior to app store submission
 */
public static final boolean debug = true;

/*
 * l method used to log passed string and returns the
 * calling file as the tag, method and line number prior
 * to the string's message
 */
public static void l(String s) {
    if (debug) {
        String[] msg = trace(Thread.currentThread().getStackTrace(), 3);
        Log.i(msg[0], msg[1] + s);
    } else {
        return;
    }
}

/*
 * l (tag, string)
 * used to pass logging messages as normal but can be disabled
 * when debug == false
 */
public static void l(String t, String s) {
    if (debug) {
        Log.i(t, s);
    } else {
        return;
    }
}

/*
 * trace
 * Gathers the calling file, method, and line from the stack
 * returns a string array with element 0 as file name and 
 * element 1 as method[line]
 */
public static String[] trace(final StackTraceElement e[], final int level) {
    if (e != null && e.length >= level) {
        final StackTraceElement s = e[level];
        if (s != null) { return new String[] {
                e[level].getFileName(), e[level].getMethodName() + "[" + e[level].getLineNumber() + "]"
        };}
    }
    return null;
}
}

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

Missing styles. Is the correct theme chosen for this layout?

This is because you select not a theme of your project. Try to do next:

enter image description here

Adding Apostrophe in every field in particular column for excel

I'm going to suggest the non-obvious. There is a fantastic (and often under-used) tool called the Immediate Window in Visual Basic Editor. Basically, you can write out commands in VBA and execute them on the spot, sort of like command prompt. It's perfect for cases like this.

Press ALT+F11 to open VBE, then Control+G to open the Immediate Window. Type the following and hit enter:

for each v in range("K2:K5000") : v.value = "'" & v.value : next

And boom! You are all done. No need to create a macro, declare variables, no need to drag and copy, etc. Close the window and get back to work. The only downfall is to undo it, you need to do it via code since VBA will destroy your undo stack (but that's simple).

Cannot load properties file from resources directory

I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this

ProjectRoot
         src
         bin
         myconf.properties

Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path

Get the first element of each tuple in a list in Python

The functional way of achieving this is to unzip the list using:

sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)

(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)

Sublime Text 2 - View whitespace characters

A "quick and dirty" way is to use the find function and activate regular expressions.

Then just search for : \s for highlighting spaces \t for tabs \n for new-lines etc.

How to disable text selection highlighting

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and its earlier versions (but sadly still needs a vendor prefix).


These are all of the available correct CSS variations:

_x000D_
_x000D_
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}
_x000D_
<p>
  Selectable text.
</p>
<p class="noselect">
  Unselectable text.
</p>
_x000D_
_x000D_
_x000D_


Note that user-select is in standardization process (currently in a W3C working draft). It is not guaranteed to work everywhere and there might be differences in implementation among browsers. Also browsers can drop support for it in the future.


More information can be found in Mozilla Developer Network documentation.

How to convert UTF-8 byte[] to string?

A Linq one-liner for converting a byte array byteArrFilename read from a file to a pure ascii C-style zero-terminated string would be this: Handy for reading things like file index tables in old archive formats.

String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
                              .Select(x => x < 128 ? (Char)x : '?').ToArray());

I use '?' as default char for anything not pure ascii here, but that can be changed, of course. If you want to be sure you can detect it, just use '\0' instead, since the TakeWhile at the start ensures that a string built this way cannot possibly contain '\0' values from the input source.

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

Qt Creator color scheme

I found a way to change the Application Output theme and everything that can't be edited from .css.

If you use osX:

  1. Navigate to your Qt install directory.
  2. Right click Qt Creator application and select "Show Package Contents"
  3. Copy the following file to your desktop> Contents/Resources/themes/dark.creatortheme or /default.creatortheme. Depending on if you are using dark theme or default theme.
  4. Edit the file in text editor.
  5. Under [Palette], there is a line that says error=ffff0000.
  6. Set a new color, save, and override the original file.

Get last 30 day records from today date in SQL Server

I dont know why all these complicated answers are on here but this is what I would do

where pdate >= CURRENT_TIMESTAMP -30

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

How to split a data frame?

If you want to split by values in one of the columns, you can use lapply. For instance, to split ChickWeight into a separate dataset for each chick:

data(ChickWeight)
lapply(unique(ChickWeight$Chick), function(x) ChickWeight[ChickWeight$Chick == x,])

Selenium WebDriver.get(url) does not open the URL

I had the similar problem. All I had to do was delete the existing geckodriver.exe and download the latest release of the same. You can find the latest release here https://github.com/mozilla/geckodriver/releases.

Show/Hide Div on Scroll

$(window).scroll(function () {
  var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});

What is Ruby's double-colon `::`?

:: Lets you access a constant, module, or class defined inside another class or module. It is used to provide namespaces so that method and class names don't conflict with other classes by different authors.

When you see ActiveRecord::Base in Rails it means that Rails has something like

module ActiveRecord
  class Base
  end
end

i.e. a class called Base inside a module ActiveRecord which is then referenced as ActiveRecord::Base (you can find this in the Rails source in activerecord-n.n.n/lib/active_record/base.rb)

A common use of :: is to access constants defined in modules e.g.

module Math
  PI = 3.141 # ...
end

puts Math::PI

The :: operator does not allow you to bypass visibility of methods marked private or protected.

What is difference between @RequestBody and @RequestParam?

@RequestParam makes Spring to map request parameters from the GET/POST request to your method argument.

GET Request

http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia

public String getCountryFactors(@RequestParam(value = "city") String city, 
                    @RequestParam(value = "country") String country){ }

POST Request

@RequestBody makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.

http://testwebaddress.com/getInformation.do

You have JSON data as such coming from the front end and hits your controller class

{
   "city": "Sydney",
   "country": "Australia"
}

Java Code - backend (@RequestBody)

public String getCountryFactors(@RequestBody Country countryFacts)
    {
        countryFacts.getCity();
        countryFacts.getCountry();
    }


public class Country {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

CocoaPods Errors on Project Build

update: a podfile.lock is necessary and should not be ignored by version control, it keeps track of the versions of libraries installed at a certain pod install. (It's similar to gemfile.lock and composer.lock for rails and php dependency management, respectively). To learn more please read the docs. Credit goes to cbowns.


In my case, what I did was that I was doing some house cleaning for my project (ie branching out the integration tests as a git submodule.. removing duplicate files etc).. and pushed the final result to a git remote repo.. all the clients who cloned my repo suffered from the above error. Inspired by Hlung's comment above, I realized that there were some dangling pod scripts that were attempting to run against some non-existent files. So I went to my target build phase, and deleted all the remaining phases that had anything to do with cocoa pods (and Hlung's comment he suggests deleting Copy Pods Manifest.lock and copy pod resources.. mine were named different maybe b/c I'm using Xcode 5.. the point being is to delete those dangling build phases)..

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I ran into this problem today when Xcode crashed during a branch merge. Somehow the file was uploaded to the svn repository but it wasn't recorded in the svn db properly. I ran the following commands in the directory where the file existed locally:

svn revert bad.file
svn del svn://my.svnserver.com/svnDB/path/to/the/offending/file/bad.file

Then I re-added the file from my local system:

svn add bad.file
svn commit -m "Re adding bad.file"

Success!

How to dynamically add and remove form fields in Angular 2

add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact

userForm: FormGroup;
  public contactList: FormArray;
  // returns all form groups under contacts
  get contactFormGroup() {
    return this.userForm.get('funds') as FormArray;
  }
  ngOnInit() {
    this.submitUser();
  }
  constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
  // contact formgroup
  createContact(): FormGroup {
    return this.fb.group({
      fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
      allocation: [null, Validators.compose([Validators.required])]
    });
  }


  // triggered to change validation of value field type
  changedFieldType(index) {
    let validators = null;

    validators = Validators.compose([
      Validators.required,
      Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
    ]);

    this.getContactsFormGroup(index).controls['allocation'].setValidators(
      validators
    );

    this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
  }

  // get the formgroup under contacts form array
  getContactsFormGroup(index): FormGroup {
    // this.contactList = this.form.get('contacts') as FormArray;
    const formGroup = this.contactList.controls[index] as FormGroup;
    return formGroup;
  }

  submitUser() {
    this.userForm = this.fb.group({
      first_name: ['', [Validators.required]],
      last_name: [''],
      email: ['', [Validators.required]],
      company_name: ['', [Validators.required]],
      license_start_date: ['', [Validators.required]],
      license_end_date: ['', [Validators.required]],
      gender: ['Male'],
      funds: this.fb.array([this.createContact()])
    })
    this.contactList = this.userForm.get('funds') as FormArray;
  }
  addContact() {
    this.contactList.push(this.createContact());
  }
  removeContact(index) {
    this.contactList.removeAt(index);
  }

Array Length in Java

First of all, length is a property, so it would be arr.length instead of arr.length().

And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.

How to use OR condition in a JavaScript IF statement?

One can use regular expressions, too:

_x000D_
_x000D_
var thingToTest = "B";_x000D_
if (/A|B/.test(thingToTest)) alert("Do something!")
_x000D_
_x000D_
_x000D_

Here's an example of regular expressions in general:

_x000D_
_x000D_
var myString = "This is my search subject"_x000D_
if (/my/.test(myString)) alert("Do something here!")
_x000D_
_x000D_
_x000D_

This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.

As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.

_x000D_
_x000D_
var myString = "This is my search subject"_x000D_
if (/my/ig.test(myString)) alert("Do something here");
_x000D_
_x000D_
_x000D_

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

You can just pass your URL,

NSURL *url = [NSURL URLWithString:@"http://www.myurl.com/1.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                    yourimageview.image = image;
            });
        }
    }
}];
[task resume];

How do I declare and assign a variable on a single line in SQL

Here goes:

DECLARE @var nvarchar(max) = 'Man''s best friend';

You will note that the ' is escaped by doubling it to ''.

Since the string delimiter is ' and not ", there is no need to escape ":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

The second example in the MSDN page on DECLARE shows the correct syntax.

Use <Image> with a local file

Using React Native 0.41 (in March 2017), targeting iOS, I just found it as easy as:

<Image source={require('./myimage.png')} />

The image file must exist in the same folder as the .js file requiring it.

I didn't have to change anything in the XCode project. It just worked. Maybe things have changed a lot in 2 years!

Note that if the filename has anything other than lower-case letters, or the path is anything more than "./", then for me, it started failing. Not sure what the restrictions are, but start simple and work forward.

Hope this helps someone, as many other answers here seem overly complex and full of (naughty) off-site links.

UPDATE: BTW - The official documentation for this is here: https://facebook.github.io/react-native/docs/images.html

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

How to change pivot table data source in Excel?

  • Right click on the pivot table, choose PivotTable Wizard.
  • Click the 'back' button twice.
  • Choose External Data Source,click next.
  • Click Get Data
  • In the first tab, Databases the first option is 'New Data Source'

Where is the Java SDK folder in my computer? Ubuntu 12.04

For me, on Ubuntu, the various versions of JDK were in /usr/lib/jvm.

How much should a function trust another function

Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

Is so simple,only add your java path for example:

C:\Program Files\Java\jdk1.8.0_121\bin

in PATH system variable

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;
}

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.

function get24hTime(str){
    str = String(str).toLowerCase().replace(/\s/g, '');
    var has_am = str.indexOf('am') >= 0;
    var has_pm = str.indexOf('pm') >= 0;
    // first strip off the am/pm, leave it either hour or hour:minute
    str = str.replace('am', '').replace('pm', '');
    // if hour, convert to hour:00
    if (str.indexOf(':') < 0) str = str + ':00';
    // now it's hour:minute
    // we add am/pm back if striped out before 
    if (has_am) str += ' am';
    if (has_pm) str += ' pm';
    // now its either hour:minute, or hour:minute am/pm
    // put it in a date object, it will convert to 24 hours format for us 
    var d = new Date("1/1/2011 " + str);
    // make hours and minutes double digits
    var doubleDigits = function(n){
        return (parseInt(n) < 10) ? "0" + n : String(n);
    };
    return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}

console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11

How do I make bootstrap table rows clickable?

There is a javascript plugin that adds this feature to bootstrap.

When rowlink.js is included you can do:

<table data-link="row">
  <tr><td><a href="foo.html">Foo</a></td><td>This is Foo</td></tr>
  <tr><td><a href="bar.html">Bar</a></td><td>Bar is good</td></tr>
</table>

The table will be converted so that the whole row can be clicked instead of only the first column.

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Is it possible to get a list of files under a directory of a website? How?

DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.

Validating email addresses using jQuery and regex

I would recommend that you use the jQuery plugin for Verimail.js.

Why?

  • IANA TLD validation
  • Syntax validation (according to RFC 822)
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

How?

Include verimail.jquery.js on your site and use the function:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

Unable to read repository at http://download.eclipse.org/releases/indigo

That URL works fine. The message you report is normal when you look at it in a browser. My copy of Eclipse has no problems talking to it. If yours does, I suspect a proxy configuration error in your copy of eclipse.

How to change text and background color?

SetConsoleTextAttribute.

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);

This would produce red text on a white background.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Exchange rate from Euro to NOK on the first of January 2016:

=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)

The INDEX() function is used because GOOGLEFINANCE() function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.

Laravel redirect back to original destination after login

Did you try this in your routes.php ?

Route::group(['middleware' => ['web']], function () {
    //
    Route::get('/','HomeController@index');
});

NLTK and Stopwords Fail #lookuperror

If you want to manually install NLTK Corpus.

1) Go to http://www.nltk.org/nltk_data/ and download your desired NLTK Corpus file.

2) Now in a Python shell check the value of nltk.data.path

3) Choose one of the path that exists on your machine, and unzip the data files into the corpora sub directory inside.

4) Now you can import the data from nltk.corpos import stopwords

Reference: https://medium.com/@satorulogic/how-to-manually-download-a-nltk-corpus-f01569861da9

Can't compare naive and aware datetime.now() <= challenge.datetime_end

So the way I would solve this problem is to make sure the two datetimes are in the right timezone.

I can see that you are using datetime.now() which will return the systems current time, with no tzinfo set.

tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()

seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.

Take a look at Delorean, it makes dealing with this sort of thing much easier.

How can I check if a string is a number?

Regex.IsMatch(stringToBeChecked, @"^\d+$")

Regex.IsMatch("141241", @"^\d+$")  // True

Regex.IsMatch("232a23", @"^\d+$")  // False

Regex.IsMatch("12412a", @"^\d+$")  // False

Creating multiline strings in JavaScript

You have to use the concatenation operator '+'.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="demo"></p>
    <script>
        var str = "This "
                + "\n<br>is "
                + "\n<br>multiline "
                + "\n<br>string.";
        document.getElementById("demo").innerHTML = str;
     </script>
</body>
</html>

By using \n your source code will look like -

This 
 <br>is
 <br>multiline
 <br>string.

By using <br> your browser output will look like -

This
is
multiline
string.

Remove Null Value from String array in java

If you actually want to add/remove items from an array, may I suggest a List instead?

String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
    if (!s.equals(""))
        list.add(s);

Then, if you really need to put that back into an array:

firstArray = list.toArray(new String[list.size()]);

Embed an External Page Without an Iframe?

Or you could use the object tag:

http://jsfiddle.net/7MaXx/

<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->

<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).

Once you find the htaccess file add the following line:

  1. Header set Access-Control-Allow-Origin "*" Just to see if it works. Warning: Do not use this line on a production server

It should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.

  1. Once you do have the above working change the * to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.