Programs & Examples On #Xmlformview

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

automatically execute an Excel macro on a cell change

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.

Add new field to every document in a MongoDB collection

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

HTTP Status 504

One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.

endforeach in loops?

It's the end statement for the alternative syntax:

foreach ($foo as $bar) :
    ...
endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>
    <div ...>
        ...
    </div>
<?php endforeach; ?>

How can I get column names from a table in Oracle?

The other answers sufficiently answer the question, but I thought I would share some additional information. Others describe the "DESCRIBE table" syntax in order to get the table information. If you want to get the information in the same format, but without using DESCRIBE, you could do:

SELECT column_name as COLUMN_NAME, nullable || '       ' as BE_NULL,
  SUBSTR(data_type || '(' || data_length || ')', 0, 10) as TYPE
 FROM all_tab_columns WHERE table_name = 'TABLENAME';

Probably doesn't matter much, but I wrote it up earlier and it seems to fit.

How to clear File Input

In my case other solutions did not work than this way:

$('.bootstrap-filestyle :input').val('');

However, if you will have more than 1 file input on page, it will reset the text on all of them.

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

My issue is resolved when I use the below code:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:1521/servicename","userName","Password");

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

How to hide navigation bar permanently in android activity?

Its a security issue: https://stackoverflow.com/a/12605313/1303691

therefore its not possible to hide the Navigation on a tablet permanently with one single call at the beginning of the view creation. It will be hidden, but it will pop up when touching the Screen. So just the second touch to your screen can cause a onClickEvent on your layout. Therefore you need to intercept this call, but i haven't managed it yet, i will update my answer when i found it out. Or do you now the answer already?

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Don't use your browser to test your API.

Instead, try to use an HTTP client that allows you to specify your request, such as CURL, or even Fiddler.

The problem with this issue is in the client, not in the API. The web API behaves correctly, according to the browser's request.

How to get everything after last slash in a URL?

urlparse is fine to use if you want to (say, to get rid of any query string parameters).

import urllib.parse

urls = [
    'http://www.test.com/TEST1',
    'http://www.test.com/page/TEST2',
    'http://www.test.com/page/page/12345',
    'http://www.test.com/page/page/12345?abc=123'
]

for i in urls:
    url_parts = urllib.parse.urlparse(i)
    path_parts = url_parts[2].rpartition('/')
    print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))

Output:

URL: http://www.test.com/TEST1
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

URL: http://www.test.com/page/page/12345?abc=123
returns: 12345

Unable to merge dex

./gradlew :app:assembleStubLiveDebug -debug -stacktrace

Or similar (get the task name (:app:assembleStubLiveDebug) from Android Studio).

Launch Pycharm from command line (terminal)

The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE

How to set the UITableView Section title programmatically (iPhone/iPad)?

Nothing wrong with the other answers but this one offers a non-programmatic solution that may be useful in situations where one has a small static table. The benefit is that one can organize the localizations using the storyboard. One may continue to export localizations from Xcode via XLIFF files. Xcode 9 also has several new tools to make localizations easier.

(original)

I had a similar requirement. I had a static table with static cells in my Main.storyboard(Base). To localize section titles using .string files e.g. Main.strings(German) just select the section in storyboard and note the Object ID

Object ID

Afterwards go to your string file, in my case Main.strings(German) and insert the translation like:

"MLo-jM-tSN.headerTitle" = "Localized section title";

Additional Resources:

<img>: Unsafe value used in a resource URL context

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.

I have created the pipe SanitizeUrlPipe for this

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustResourceUrl(v);
    }
}

and this is how you can use

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

If you want to add HTML, then SanitizeHtmlPipe can help

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustHtml(v);
    }
}

Read more about angular security here.

How do I expire a PHP session after 30 minutes?

It's actually easy with a function like the following. It uses database table name 'sessions' with fields 'id' and 'time'.

Every time when the user visits your site or service again you should invoke this function to check if its return value is TRUE. If it's FALSE the user has expired and the session will be destroyed (Note: This function uses a database class to connect and query the database, of course you could also do it inside your function or something like that):

function session_timeout_ok() {
    global $db;
    $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
    $ok = false;
    $session_id = session_id();
    $sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
    $rows = $db->query($sql);
    if ($rows === false) {
        //Timestamp could not be read
        $ok = FALSE;
    }
    else {
        //Timestamp was read succesfully
        if (count($rows) > 0) {
            $zeile = $rows[0];
            $time_past = $zeile['time'];
            if ( $timeout + $time_past < time() ) {
                //Time has expired
                session_destroy();
                $sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
                $affected = $db -> query($sql);
                $ok = FALSE;
            }
            else {
                //Time is okay
                $ok = TRUE;
                $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
                $erg = $db -> query($sql);
                if ($erg == false) {
                    //DB error
                }
            }
        }
        else {
            //Session is new, write it to database table sessions
            $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
            $res = $db->query($sql);
            if ($res === FALSE) {
                //Database error
                $ok = false;
            }
            $ok = true;
        }
        return $ok;
    }
    return $ok;
}

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

Center/Set Zoom of Map to cover all visible Markers?

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

How to convert string to integer in UNIX

Use this:

#include <stdlib.h>
#include <string.h>

int main()
{
    const char *d1 = "11";
    int d1int = atoi(d1);
    printf("d1 = %d\n", d1);
    return 0;
}

etc.

Custom Cell Row Height setting in storyboard is not responding

On dynamic cells, rowHeight set on the UITableView always overrides the individual cells' rowHeight.

But on static cells, rowHeight set on individual cells can override UITableView's.

Not sure if it's a bug, Apple might be intentionally doing this?

C++ templates that accept only certain types

I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:

template<typename T>
class ObservableList {
    BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
    ...
};

In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:

template<typename T> class my_template;     // Declare, but don't define

// int is a valid type
template<> class my_template<int> {
    ...
};

// All pointer types are valid
template<typename T> class my_template<T*> {
    ...
};

// All other types are invalid, and will cause linker error messages.

[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]

Python: split a list based on a condition?

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

Check this

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

Warning: push.default is unset; its implicit value is changing in Git 2.0

Brought my answer over from other thread that may close as a duplicate...

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

Generating random strings with T-SQL

If you are running SQL Server 2008 or greater, you could use the new cryptographic function crypt_gen_random() and then use base64 encoding to make it a string. This will work for up to 8000 characters.

declare @BinaryData varbinary(max)
    , @CharacterData varchar(max)
    , @Length int = 2048

set @BinaryData=crypt_gen_random (@Length) 

set @CharacterData=cast('' as xml).value('xs:base64Binary(sql:variable("@BinaryData"))', 'varchar(max)')

print @CharacterData

Java get last element of a collection

There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

Split string into string array of single characters

I believe this is what you're looking for:

char[] characters = "this is a test".ToCharArray();

Converting XML to JSON using Python?

You can use declxml. It has advanced features like multi attributes and complex nested support. You just need to write a simple processor for it. Also with the same code, you can convert back to JSON as well. It is fairly straightforward and the documentation is awesome.

Link: https://declxml.readthedocs.io/en/latest/index.html

Eclipse 3.5 Unable to install plugins

I had similar problem. I changed Direct connection to Native and it worked.

Preferences ? General ? Network Connections.

Reading from text file until EOF repeats last line

The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.

What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.

I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.

  • 0

So add a prime read and move the loop's read to the end:

int x;

iFile >> x; // prime read here
while (!iFile.eof()) {
    cerr << x << endl;
    iFile >> x;
}

Getting value of select (dropdown) before change

Best solution:

$('select').on('selectric-before-change', function (event, element, selectric) {
    var current = element.state.currValue; // index of current value before select a new one
    var selected = element.state.selectedIdx; // index of value that will be selected

    // choose what you need
    console.log(element.items[current].value);
    console.log(element.items[current].text);
    console.log(element.items[current].slug);
});

GetElementByID - Multiple IDs

As stated by jfriend00,

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.

However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.

function safelyGetElementsByIds(ids){
    if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
    ids = ids.split(",");
    let elements = [];
    for(let i=0, len = ids.length; i<len; i++){
        const currId = ids[i];
        const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
        if(currElement instanceof Error) return [currElement];
        elements.push(currElement);
    };
    return elements;
}

safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]

error: request for member '..' in '..' which is of non-class type

If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write

 type substance1();

but

 type substance;

Android Studio : unmappable character for encoding UTF-8

Check all 'C' characters. There are may be some cyrillic 'C's in english-looking word.
Reason for this is that in both english and russian keyboards 'C' occupies same physical button.

Event when window.location.href changes

Well there is 2 ways to change the location.href. Either you can write location.href = "y.html", which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.

If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick. So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
var uglyHax = function (){
    var done = function (){
        uglyHax();
        callBacks.forEach(function (cb){
            cb();
        });
    };
    win.addEventListener("unload", function unloadListener(){
        win.removeEventListener("unload", unloadListener); // Firefox remembers, other browsers don't
        setTimeout(function (){
            // IE10, IE11, Opera, PhantomJS, Chrome has a complete new document at this point
            // Chrome on Karma, Firefox has a loading new document at this point
            win.document.readyState; // IE10 and IE11 sometimes fails if I don't access it twice, idk. how or why
            if (win.document.readyState === "complete")
                done();
            else
                win.addEventListener("load", function (){
                    setTimeout(done, 0);
                });
        }, 0);
    });
};
uglyHax();


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
win.addEventListener("unload", function unloadListener(){
    setTimeout(function (){
        callBacks.forEach(function (cb){
            cb();
        });
    }, 0);
});


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    // be aware that the page is in loading readyState, 
    // so if you rewrite the location here, the actual page will be never loaded, just the new one
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange and the popstate events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

Android - set TextView TextStyle programmatically?

Let's say you have a style called RedHUGEText on your values/styles.xml:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

Just create your TextView as usual in the XML layout/your_layout.xml file, let's say:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" />

And in the java code of your Activity you do this:

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);

It worked for me! And it applied color, size, gravity, etc. I've used it on handsets and tablets with Android API Levels from 8 to 17 with no problems. Note that as of Android 23, that method has been deprecated. The context argument has been dropped, so the last line would need to be:

textViewTitle.setTextAppearance(R.style.RedHUGEText);

Remember... this is useful only if the style of the text really depends on a condition on your Java logic or you are building the UI "on the fly" with code... if it doesn't, it is better to just do:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" 
    style="@style/RedHUGEText" />

You can always have it your way!

Python regex to match dates

As the question title asks for a regex that finds many dates, I would like to propose a new solution, although there are many solutions already.

In order to find all dates of a string that are in this millennium (2000 - 2999), for me it worked the following:

dates = re.findall('([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])(.|-|\/)([1-9]|1[0-2]|0[0-9])(.|-|\/)(20[0-9][0-9])',dates_ele)

dates = [''.join(dates[i]) for i in range(len(dates))]

This regex is able to find multiple dates in the same string, like bla Bla 8.05/2020 \n BLAH bla15/05-2020 blaa. As one could observe, instead of / the date can have . or -, not necessary at the same time.

Some explaining

More specifically it can find dates of format day , moth year. Day is an one digit integer or a zero followed by one digit integer or 1 or 2 followed by an one digit integer or a 3 followed by 0 or 1. Month is an one digit integer or a zero followed by one digit integer or 1 followed by 0, 1, or 2. Year is the number 20 followed by any number between 00 and 99.

Useful notes

One can add more date splitting symbols by adding | symbol at the end of both (.|-|\/). For example for adding -- one would do (.|-|\/|--)

To have years outside of this millennium one has to modify (20[0-9][0-9]) to ([0-9][0-9][0-9][0-9])

Iterating C++ vector from the end to the beginning

I like the backwards iterator at the end of Yakk - Adam Nevraumont's answer, but it seemed complicated for what I needed, so I wrote this:

template <class T>
class backwards {
    T& _obj;
public:
    backwards(T &obj) : _obj(obj) {}
    auto begin() {return _obj.rbegin();}
    auto end() {return _obj.rend();}
};

I'm able to take a normal iterator like this:

for (auto &elem : vec) {
    // ... my useful code
}

and change it to this to iterate in reverse:

for (auto &elem : backwards(vec)) {
    // ... my useful code
}

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

how to make twitter bootstrap submenu to open on the left side?

If you have only one level and you use bootstrap 3 add pull-right to the ul element

<ul class="dropdown-menu pull-right" role="menu">

Git - deleted some files locally, how do I get them from a remote repository

You need to check out a previous version from before you deleted the files. Try git checkout HEAD^ to checkout the last revision.

Can I send a ctrl-C (SIGINT) to an application on Windows?

        void SendSIGINT( HANDLE hProcess )
        {
            DWORD pid = GetProcessId(hProcess);
            FreeConsole();
            if (AttachConsole(pid))
            {
                // Disable Ctrl-C handling for our program
                SetConsoleCtrlHandler(NULL, true);

                GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // SIGINT

                //Re-enable Ctrl-C handling or any subsequently started
                //programs will inherit the disabled state.
                SetConsoleCtrlHandler(NULL, false);

                WaitForSingleObject(hProcess, 10000);
            }
        }

How to get row number from selected rows in Oracle

There is no inherent ordering to a table. So, the row number itself is a meaningless metric.

However, you can get the row number of a result set by using the ROWNUM psuedocolumn or the ROW_NUMBER() analytic function, which is more powerful.

As there is no ordering to a table both require an explicit ORDER BY clause in order to work.

select rownum, a.*
  from ( select *
           from student
          where name like '%ram%'
          order by branch
                ) a

or using the analytic query

select row_number() over ( order by branch ) as rnum, a.*
  from student
 where name like '%ram%'

Your syntax where name is like ... is incorrect, there's no need for the IS, so I've removed it.

The ORDER BY here relies on a binary sort, so if a branch starts with anything other than B the results may be different, for instance b is greater than B.

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

Database, Table and Column Naming Conventions?

I hear the argument all the time that whether or not a table is pluralized is all a matter of personal taste and there is no best practice. I don't believe that is true, especially as a programmer as opposed to a DBA. As far as I am aware, there are no legitimate reasons to pluralize a table name other than "It just makes sense to me because it's a collection of objects," while there are legitimate gains in code by having singular table names. For example:

  1. It avoids bugs and mistakes caused by plural ambiguities. Programmers aren't exactly known for their spelling expertise, and pluralizing some words are confusing. For example, does the plural word end in 'es' or just 's'? Is it persons or people? When you work on a project with large teams, this can become an issue. For example, an instance where a team member uses the incorrect method to pluralize a table he creates. By the time I interact with this table, it is used all over in code I don't have access to or would take too long to fix. The result is I have to remember to spell the table wrong every time I use it. Something very similar to this happened to me. The easier you can make it for every member of the team to consistently and easily use the exact, correct table names without errors or having to look up table names all the time, the better. The singular version is much easier to handle in a team environment.

  2. If you use the singular version of a table name AND prefix the primary key with the table name, you now have the advantage of easily determining a table name from a primary key or vice versa via code alone. You can be given a variable with a table name in it, concatenate "Id" to the end, and you now have the primary key of the table via code, without having to do an additional query. Or you can cut off "Id" from the end of a primary key to determine a table name via code. If you use "id" without a table name for the primary key, then you cannot via code determine the table name from the primary key. In addition, most people who pluralize table names and prefix PK columns with the table name use the singular version of the table name in the PK (for example statuses and status_id), making it impossible to do this at all.

  3. If you make table names singular, you can have them match the class names they represent. Once again, this can simplify code and allow you to do really neat things, like instantiating a class by having nothing but the table name. It also just makes your code more consistent, which leads to...

  4. If you make the table name singular, it makes your naming scheme consistent, organized, and easy to maintain in every location. You know that in every instance in your code, whether it's in a column name, as a class name, or as the table name, it's the same exact name. This allows you to do global searches to see everywhere that data is used. When you pluralize a table name, there will be cases where you will use the singular version of that table name (the class it turns into, in the primary key). It just makes sense to not have some instances where your data is referred to as plural and some instances singular.

To sum it up, if you pluralize your table names you are losing all sorts of advantages in making your code smarter and easier to handle. There may even be cases where you have to have lookup tables/arrays to convert your table names to object or local code names you could have avoided. Singular table names, though perhaps feeling a little weird at first, offer significant advantages over pluralized names and I believe are best practice.

What is Bootstrap?

Bootstrap, as I know it, is a well defined CSS. Although using Bootstrap you could also use JavaScript, jQuery etc. But the main difference is that, using Bootstrap you can just call the class name and then you get the output on the HTML form. for eg. coloring of buttons shaping of text, using layouts. For all this you do not have to write a CSS file rather you just have to use the correct class name for shaping your HTML form.

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

How do I use spaces in the Command Prompt?

Just add Quotation Mark

Example:"C:\Users\User Name"

Hope it got Solved!

Set Locale programmatically

Put this code in your activity

 if (id==R.id.uz)
    {
        LocaleHelper.setLocale(MainActivity.this, mLanguageCode);

        //It is required to recreate the activity to reflect the change in UI.
        recreate();
        return true;
    }
    if (id == R.id.ru) {

        LocaleHelper.setLocale(MainActivity.this, mLanguageCode);

        //It is required to recreate the activity to reflect the change in UI.
        recreate();
    }

Write to text file without overwriting in Java

try this one

_x000D_
_x000D_
public void writeFile(String arg1,String arg2) {_x000D_
  try {_x000D_
   if (!dir.exists()) {_x000D_
_x000D_
    if (dir.mkdirs()) {_x000D_
_x000D_
     Toast.makeText(getBaseContext(), "Directory created",_x000D_
       Toast.LENGTH_SHORT).show();_x000D_
    } else {_x000D_
     Toast.makeText(getBaseContext(),_x000D_
       "Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
       .show();_x000D_
    }_x000D_
   }_x000D_
_x000D_
   else {_x000D_
_x000D_
    File file = new File(dir, filename);_x000D_
    if (!file.exists()) {_x000D_
     file.createNewFile();_x000D_
    }_x000D_
    _x000D_
    FileWriter fileWritter = new FileWriter(file, true);_x000D_
    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
    bufferWritter.write(arg1 + "\n");_x000D_
    bufferWritter.close();_x000D_
_x000D_
            } catch (Exception e) {_x000D_
   e.printStackTrace();_x000D_
   Toast.makeText(getBaseContext(),_x000D_
     "Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
     .show();_x000D_
  }_x000D_
_x000D_
 }
_x000D_
_x000D_
_x000D_

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Try

(n+10).toString(36)

_x000D_
_x000D_
chr = n=>(n+10).toString(36);_x000D_
_x000D_
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);
_x000D_
_x000D_
_x000D_

Display Images Inline via CSS

Place this css in your page:

<style>
   #client_logos {
    display: inline-block;
    width:100%;
    }
  </style>

Replace

<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>

To

<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>

How to set gradle home while importing existing project in Android studio

In Ubuntu 14.04 after $ sudo apt-get install gradle I've got

$ whereis gradle
gradle: /usr/bin/gradle /usr/bin/X11/gradle /usr/share/gradle /usr/share/man/man1/gradle.1.gz

The path to Gradle was /usr/share/gradle

Android Drawing Separator/Divider Line in Layout?

Here is the code " a horizontal divider line between two Text Views". Try this

    <TextView
        android:id="@id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="5dp"
        android:inputType="textPersonName"
        android:text:"address" />


    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/black"/>


    <TextView
        android:id="@id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName" 
        android:text:"Upload File" />/>

Using "like" wildcard in prepared statement

String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";


PreparedStatement preparedStatement=con.prepareStatement(query);


// where seleced and SelectedStr are String Variables in my program

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

How do I select a sibling element using jQuery?

$(this).siblings(".bidbutton")

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

What is the native keyword in Java for?

Straight from the Java Language Specification:

A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN,or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

SQL Server Regular expressions in T-SQL

There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.

How to get a list of images on docker registry v2

For the latest (as of 2015-07-31) version of Registry V2, you can get this image from DockerHub:

docker pull distribution/registry:master

List all repositories (effectively images):

curl -X GET https://myregistry:5000/v2/_catalog
> {"repositories":["redis","ubuntu"]}

List all tags for a repository:

curl -X GET https://myregistry:5000/v2/ubuntu/tags/list
> {"name":"ubuntu","tags":["14.04"]}

Completely removing phpMyAdmin

I had to run the following command:

sudo apt-get autoremove phpmyadmin

Then I cleared my cache and it worked!

SVN Repository Search

Painfully slow (and crudely implemented) but a combination of svn log and svn cat works if you are searching the history of single files or small repositories:

svn log filetosearch |
    grep '^r' |
    cut -f1 -d' ' |
    xargs -i bash -c "echo '{}'; svn cat filetosearch -'{}'" 

will output each revision number where file changed and the file. You could always cat each revision into a different file and then grep for changes.

PS. Massive upvotes to anyone that shows me how to do this properly!

Replace text in HTML page with jQuery

...I have a string "-9o0-9909" and I want to replace it with another string.

The code below will do that.

var str = '-9o0-9909';

str = 'new string';

Jokes aside, replacing text nodes is not trivial with JavaScript.

I've written a post about this: Replacing text with JavaScript.

Force Java timezone as GMT/UTC

I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();

-Duser.timezone=America/Los_Angeles

Or your appropriate time zone. Finding a list of time zones proved to be a bit challenging also...

Here are two list;

http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm

Can't type in React input text field

You haven't properly cased your onchange prop in the input. It needs to be onChange in JSX.

<input
  type="text"
  value={this.props.searchString}
  ref="searchStringInput"
  onchange={this.handleChange} <--[should be onChange]
/>  

The topic of passing a value prop to an <input>, and then somehow changing the value passed in response to user interaction using an onChange handler is pretty well-considered in the docs.

They refer to such inputs as Controlled Components, and refer to inputs that instead let the DOM natively handle the input's value and subsequent changes from the user as Uncontrolled Components.

Whenever you set the value prop of an input to some variable, you have a Controlled Component. This means you must change the value of the variable by some programmatic means or else the input will always hold that value and will never change, even when you type -- the native behaviour of the input, to update its value on typing, is overridden by React here.

So, you're correctly taking that variable from state, and have a handler to update the state all set up fine. The problem was because you have onchange and not the correct onChange the handler was never being called and so the value was never being updated when you type into the input. When you do use onChange the handler is called, the value is updated when you type, and you see your changes.

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

From rxjs 5.5 onwards, you can use the pipeable operators

import { map } from 'rxjs/operators';

What is wrong with the import 'rxjs/add/operator/map';

When we use this approach map operator will be patched to observable.prototype and becomes a part of this object.

If later on, you decide to remove map operator from the code that handles the observable stream but fail to remove the corresponding import statement, the code that implements map remains a part of the Observable.prototype.

When the bundlers tries to eliminate the unused code (a.k.a. tree shaking), they may decide to keep the code of the map operator in the Observable even though it’s not being used in the application.

Solution - Pipeable operators

Pipeable operators are pure functions and do not patch the Observable. You can import operators using the ES6 import syntax import { map } from "rxjs/operators" and then wrap them into a function pipe() that takes a variable number of parameters, i.e. chainable operators.

Something like this:

getHalls() {
    return this.http.get(HallService.PATH + 'hall.json')
    .pipe(
        map((res: Response) => res.json())
    );
}

What is the difference between .text, .value, and .value2?

Except first answer form Bathsheba, except MSDN information for:

.Value
.Value2
.Text

you could analyse these tables for better understanding of differences between analysed properties.

enter image description here

Regex for not empty and not whitespace

A little late, but here's a regex I found that returns 0 matches for empty or white spaces:

/^(?!\s*$).+/

You can test this out at regex101

c# why can't a nullable int be assigned null as a value

Another option is to use

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

I like this one most.

Plugin with id 'com.google.gms.google-services' not found

In the app build.gradle dependency, you must add the following code

classpath 'com.google.gms:google-services:$last_version'

And then please check the Google Play Service SDK tools installing status.

Can I add color to bootstrap icons only using CSS?

I thought that I might add this snippet to this old post. This is what I had done in the past, before the icons were fonts:

<i class="social-icon linkedin small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>
<i class="social-icon facebook small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>

This is very similar to @frbl 's sneaky answer, yet it does not use another image. Instead, this sets the background-color of the <i> element to white and uses the CSS property border-radius to make the entire <i> element "rounded." If you noticed, the value of the border-radius (7.5px) is exactly half that of the width and height property (both 15px, making the icon square), making the <i> element circular.

Regular expression for address field validation

I have succesfully used ;

Dim regexString = New stringbuilder
    With regexString
       .Append("(?<h>^[\d]+[ ])(?<s>.+$)|")                'find the 2013 1st ambonstreet 
       .Append("(?<s>^.*?)(?<h>[ ][\d]+[ ])(?<e>[\D]+$)|") 'find the 1-7-4 Dual Ampstreet 130 A
       .Append("(?<s>^[\D]+[ ])(?<h>[\d]+)(?<e>.*?$)|")    'find the Terheydenlaan 320 B3 
       .Append("(?<s>^.*?)(?<h>\d*?$)")                    'find the 245e oosterkade 9
    End With

    Dim Address As Match = Regex.Match(DataRow("customerAddressLine1"), regexString.ToString(), RegexOptions.Multiline)

    If Not String.IsNullOrEmpty(Address.Groups("s").Value) Then StreetName = Address.Groups("s").Value
    If Not String.IsNullOrEmpty(Address.Groups("h").Value) Then HouseNumber = Address.Groups("h").Value
    If Not String.IsNullOrEmpty(Address.Groups("e").Value) Then Extension = Address.Groups("e").Value

The regex will attempt to find a result, if there is none, it move to the next alternative. If no result is found, none of the 4 formats where present.

Assignment makes pointer from integer without cast

strToLower should return a char * instead of a char. Something like this would do.

char *strToLower(char *cString)

Responsive font size in CSS

 h1 { font-size: 2.25em; } 
 h2 { font-size: 1.875em; }
 h3 { font-size: 1.5em; }
 h4 { font-size: 1.125em; }
 h5 { font-size: 0.875em; }
 h6 { font-size: 0.75em; }

Conda command is not recognized on Windows 10

If you have installed Visual studio 2017 (profressional)

The install location:

C:\ProgramData\Anaconda3\Scripts

If you do not want the hassle of putting this in your path environment variable on windows and restarting you can run it by simply:

C:\>"C:\ProgramData\Anaconda3\Scripts\conda.exe" update qt pyqt

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

How to increment variable under DOS?

Coming to the party very very late, but from my old memory of DOS batch files, you can keep adding a character to the string each loop then look for a string of that many of that character. for 250 iterations, you either have a very long "cycles" string, or you have one loop inside using one set of variables counting to 10, then another loop outside that uses another set of variable counting to 25.

Here is the basic loop to 30:

@echo off
rem put how many dots you want to loop
set cycles=..............................
set cntr=
:LOOP
set cntr=%cntr%.
echo around we go again
if "%cycles%"=="%cntr%" goto done
goto loop
:DONE
echo around we went

Java Scanner class reading strings

This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().

Here is my code:

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];

for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

Regex for numbers only

^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Spring Boot - Loading Initial Data

In Spring Boot 2 data.sql was not working with me as in spring boot 1.5

import.sql

In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop).

Note very important if you insert Keys cannot be duplicated do not use ddl-auto property is set to update because with each restart will insert same data again

For more information you vist spring websit

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

What are the differences between a superkey and a candidate key?

Super key is the combination of fields by which the row is uniquely identified and the candidate key is the minimal super key.

How to convert HH:mm:ss.SSS to milliseconds?

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

Rails find_or_create_by more than one attribute?

By passing a block to find_or_create, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.

Assuming:

class GroupMember < ActiveRecord::Base
    validates_presence_of :name
end

then

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }

will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4 and group_id 7

How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

How do I print the full value of a long string in gdb?

The printf command will print the complete strings:

(gdb) printf "%s\n", string

How to define an optional field in protobuf 3

In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.

If you need a "null" state (and there is no out-of-range value that you can use for this) then you will instead need to encode this as a separate field. For instance, you could do:

message Foo {
  bool has_baz = 1;  // always set this to "true" when using baz
  int32 baz = 2;
}

Alternatively, you could use oneof:

message Foo {
  oneof baz {
    bool baz_null = 1;  // always set this to "true" when null
    int32 baz_value = 2;
  }
}

The oneof version is more explicit and more efficient on the wire but requires understanding how oneof values work.

Finally, another perfectly reasonable option is to stick with proto2. Proto2 is not deprecated, and in fact many projects (including inside Google) very much depend on proto2 features which are removed in proto3, hence they will likely never switch. So, it's safe to keep using it for the foreseeable future.

callback to handle completion of pipe

I found an a bit different solution of my problem regarding this context. Thought worth sharing.

Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
                    callback();
                });
// message.value --> value/text to write in write.txt 
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );
    sftp.end();
    }
);

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"
        sftp.end();
        }
);

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString = Object.prototype.toString.call(data);
    console.log('type of data:', toString);
    console.log( "- file transferred" );
});

jsonStream.pipe( writeStream );

Separating class code into a header and cpp file

A2DD.h

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);

  int getSum();
};

A2DD.cpp

  A2DD::A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int A2DD::getSum()
  {
    return gx + gy;
  }

The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.

And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.

How to convert CSV file to multiline JSON?

You can use Pandas DataFrame to achieve this, with the following Example:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

What is the right way to check for a null string in Objective-C?

@interface NSString (StringFunctions)
- (BOOL) hasCharacters;
@end

@implementation NSString (StringFunctions)
- (BOOL) hasCharacters {
    if(self == (id)[NSNull null]) {
        return NO;
    }else {
        if([self length] == 0) {
            return NO;
        }
    }
    return YES;
}
@end

NSString *strOne = nil;
if([strOne hasCharacters]) {
    NSLog(@"%@",strOne);
}else {
    NSLog(@"String is Empty");
}

This would work with the following cases, NSString *strOne = @"" OR NSString *strOne = @"StackOverflow" OR NSString *strOne = [NSNull null] OR NSString *strOne.

PHP - Insert date into mysql

How to debug SQL queries when you stuck

Print you query and run it directly in mysql or phpMyAdmin

$date = "2012-08-06";
$query= "INSERT INTO data_table (title, date_of_event) 
             VALUES('". $_POST['post_title'] ."',
                    '". $date ."')";
echo $query;
mysql_query($query) or die(mysql_error()); 

that way you can make sure that the problem is not in your PHP-script, but in your SQL-query

How to submit questions on SQ-queries

Make sure that you provided enough closure

  • Table schema
  • Query
  • Error message is any

How do I detect unsigned integer multiply overflow?

mozilla::CheckedInt<T> provides overflow-checked integer math for integer type T (using compiler intrinsics on clang and gcc as available). The code is under MPL 2.0 and depends on three (IntegerTypeTraits.h, Attributes.h and Compiler.h) other header-only non-standard library headers plus Mozilla-specific assertion machinery. You probably want to replace the assertion machinery if you import the code.

Popup Message boxes

JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);

btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it

How to check if JavaScript object is JSON

The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof

function isJson(obj) {
    var t = typeof obj;
    return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}

'this' vs $scope in AngularJS controllers

Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.

To bring back this behaviour (does anyone know why was it changed?) you can add:

return angular.extend($scope, this);

at the end of your controller function (provided that $scope was injected to this controller function).

This has a nice effect of having access to parent scope via controller object that you can get in child with require: '^myParentDirective'

Clear image on picturebox

Its so simple! You can go with your button click event, I used it with a button property Name: "btnClearImage"

// Note 1a:
// after clearing the picture box 
// you can also disable clear button 
// by inserting follwoing one line of code:

btnClearImage.Enabled = false   

// Note 1b:
// you should set your button Enabled property
// to "False"
// after that you will need to Insert 
// the following line to concerned event or button
// that load your image into picturebox1 
// code line is as follows:

btnClearImage.Enabled = true;

How can I start an Activity from a non-Activity class?

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this: ((Activity) mContext).startActivity(...)

Python conditional assignment operator

There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:

x = true_value if condition else false_value

For further reference, check out the Python 2.5 docs.

How to set commands output as a variable in a batch file

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

Tested on Win 10 CMD.

Parser Error when deploy ASP.NET application

Try changing CodeBehind="Default.aspx.cs" to CodeFile="Default.aspx.cs"

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

The connection to adb is down, and a severe error has occurred

It's also possible to get this error if you are running the test project using JUnit instead of Android JUnit. Naturally, the solution is just to change how you run it.

Run a vbscript from another vbscript

Just to complete, you could send 3 arguments like this:

objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo" 

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

In short, it is used in decorator syntax and for matrix multiplication.

In the context of decorators, this syntax:

@decorator
def decorated_function():
    """this function is decorated"""

is equivalent to this:

def decorated_function():
    """this function is decorated"""

decorated_function = decorator(decorated_function)

In the context of matrix multiplication, a @ b invokes a.__matmul__(b) - making this syntax:

a @ b

equivalent to

dot(a, b)

and

a @= b

equivalent to

a = dot(a, b)

where dot is, for example, the numpy matrix multiplication function and a and b are matrices.

How could you discover this on your own?

I also do not know what to search for as searching Python docs or Google does not return relevant results when the @ symbol is included.

If you want to have a rather complete view of what a particular piece of python syntax does, look directly at the grammar file. For the Python 3 branch:

~$ grep -C 1 "@" cpython/Grammar/Grammar 

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
--
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
            '<<=' | '>>=' | '**=' | '//=')
--
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power

We can see here that @ is used in three contexts:

  • decorators
  • an operator between factors
  • an augmented assignment operator

Decorator Syntax:

A google search for "decorator python docs" gives as one of the top results, the "Compound Statements" section of the "Python Language Reference." Scrolling down to the section on function definitions, which we can find by searching for the word, "decorator", we see that... there's a lot to read. But the word, "decorator" is a link to the glossary, which tells us:

decorator

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.

So, we see that

@foo
def bar():
    pass

is semantically the same as:

def bar():
    pass

bar = foo(bar)

They are not exactly the same because Python evaluates the foo expression (which could be a dotted lookup and a function call) before bar with the decorator (@) syntax, but evaluates the foo expression after bar in the other case.

(If this difference makes a difference in the meaning of your code, you should reconsider what you're doing with your life, because that would be pathological.)

Stacked Decorators

If we go back to the function definition syntax documentation, we see:

@f1(arg)
@f2
def func(): pass

is roughly equivalent to

def func(): pass
func = f1(arg)(f2(func))

This is a demonstration that we can call a function that's a decorator first, as well as stack decorators. Functions, in Python, are first class objects - which means you can pass a function as an argument to another function, and return functions. Decorators do both of these things.

If we stack decorators, the function, as defined, gets passed first to the decorator immediately above it, then the next, and so on.

That about sums up the usage for @ in the context of decorators.

The Operator, @

In the lexical analysis section of the language reference, we have a section on operators, which includes @, which makes it also an operator:

The following tokens are operators:

+       -       *       **      /       //      %      @
<<      >>      &       |       ^       ~
<       >       <=      >=      ==      !=

and in the next page, the Data Model, we have the section Emulating Numeric Types,

object.__add__(self, other)
object.__sub__(self, other) 
object.__mul__(self, other) 
object.__matmul__(self, other) 
object.__truediv__(self, other) 
object.__floordiv__(self, other)

[...] These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, [...]

And we see that __matmul__ corresponds to @. If we search the documentation for "matmul" we get a link to What's new in Python 3.5 with "matmul" under a heading "PEP 465 - A dedicated infix operator for matrix multiplication".

it can be implemented by defining __matmul__(), __rmatmul__(), and __imatmul__() for regular, reflected, and in-place matrix multiplication.

(So now we learn that @= is the in-place version). It further explains:

Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

instead of:

S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

While this operator can be overloaded to do almost anything, in numpy, for example, we would use this syntax to calculate the inner and outer product of arrays and matrices:

>>> from numpy import array, matrix
>>> array([[1,2,3]]).T @ array([[1,2,3]])
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
>>> array([[1,2,3]]) @ array([[1,2,3]]).T
array([[14]])
>>> matrix([1,2,3]).T @ matrix([1,2,3])
matrix([[1, 2, 3],
        [2, 4, 6],
        [3, 6, 9]])
>>> matrix([1,2,3]) @ matrix([1,2,3]).T
matrix([[14]])

Inplace matrix multiplication: @=

While researching the prior usage, we learn that there is also the inplace matrix multiplication. If we attempt to use it, we may find it is not yet implemented for numpy:

>>> m = matrix([1,2,3])
>>> m @= m.T
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: In-place matrix multiplication is not (yet) supported. Use 'a = a @ b' instead of 'a @= b'.

When it is implemented, I would expect the result to look like this:

>>> m = matrix([1,2,3])
>>> m @= m.T
>>> m
matrix([[14]])

How to convert an image to base64 encoding?

I think that it should be:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

Can't operator == be applied to generic types in C#?

In general, EqualityComparer<T>.Default.Equals should do the job with anything that implements IEquatable<T>, or that has a sensible Equals implementation.

If, however, == and Equals are implemented differently for some reason, then my work on generic operators should be useful; it supports the operator versions of (among others):

  • Equal(T value1, T value2)
  • NotEqual(T value1, T value2)
  • GreaterThan(T value1, T value2)
  • LessThan(T value1, T value2)
  • GreaterThanOrEqual(T value1, T value2)
  • LessThanOrEqual(T value1, T value2)

Spin or rotate an image on hover

here is the automatic spin and rotating zoom effect using css3

#obj1{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj1.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj2{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj2.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj6{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj6.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

/* Standard syntax */
@keyframes mymove {
    50% {transform: rotate(30deg);
}
<div style="width:100px; float:right; ">
    <div id="obj2"></div><br /><br /><br />
    <div id="obj6"></div><br /><br /><br />
    <div id="obj1"></div><br /><br /><br />
</div>

Here is the demo

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

Reverting to a previous revision using TortoiseSVN

The Revert command in the context menu ignores your edits and returns the working copy to its previous state. You may also select the desired revision other than the "Head" when you "CheckOut" from the repository.

Example of SOAP request authenticated with WS-UsernameToken

May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "

How do you completely remove the button border in wpf?

You may have to change the button template, this will give you a button with no frame what so ever, but also without any press or disabled effect:

    <Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Background="Transparent">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And the button:

<Button Style="{StaticResource TransparentStyle}"/>

POST string to ASP.NET Web Api application - returns null

You seem to have used some [Authorize] attribute on your Web API controller action and I don't see how this is relevant to your question.

So, let's get into practice. Here's a how a trivial Web API controller might look like:

public class TestController : ApiController
{
    public string Post([FromBody] string value)
    {
        return value;
    }
}

and a consumer for that matter:

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var data = "=Short test...";
            var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
            Console.WriteLine(result);
        }
    }
}

You will undoubtedly notice the [FromBody] decoration of the Web API controller attribute as well as the = prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.

As far as the [Authorize] attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post that I wrote on this topic interesting to get you started.

And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.

Is it possible to declare a public variable in vba and assign a default value?

This is what I do when I need Initialized Global Constants:
1. Add a module called Globals
2. Add Properties like this into the Globals module:

Property Get PSIStartRow() As Integer  
    PSIStartRow = Sheets("FOB Prices").Range("F1").Value  
End Property  
Property Get PSIStartCell() As String  
    PSIStartCell = "B" & PSIStartRow  
End Property

Deny direct access to all .php files except index.php

How about keeping all .php-files except for index.php above the web root? No need for any rewrite rules or programmatic kludges.

Adding the includes-folder to your include path will then help to keep things simple, no need to use absolute paths etc.

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Failed to connect to camera service

The problem is related to permission. Copy following code into onCreate() method. The issue will get solved.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
    }
}

After that wait for the user action and handle his decision.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Start your camera handling here
            } else {
                AppUtils.showUserMessage("You declined to allow the app to access your camera", this);
            }
    }
}

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Where does it fail?

I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.

Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.

Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.

Trim down your results.

get current date from [NSDate date] but set the time to 10:00 am

NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

Not tested in xcode though :)

Switch statement: must default be the last case?

yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.

Is there a way to remove unused imports and declarations from Angular 2+?

There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.

In the article the author explains it like this:

Make a stand alone tslint file that has the following in it:

{
  "extends": ["tslint-etc"],
  "rules": {
    "no-unused-declaration": true
  }
}

Then run the following command to fix the imports:

 tslint --config tslint-imports.json --fix --project .

Consider fixing any other errors it throws. (I did)

Then check the project works by building it:

ng build

or

ng build name_of_project --configuration=production 

End: If it builds correctly, you have successfully removed imports automatically!

NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.

How to remove all debug logging calls before building the release version of an Android app?

If you want to use a programmatic approach instead of using ProGuard, then by creating your own class with two instances, one for debug and one for release, you can choose what to log in either circumstances.

So, if you don't want to log anything when in release, simply implement a Logger that does nothing, like the example below:

import android.util.Log

sealed class Logger(defaultTag: String? = null) {
    protected val defaultTag: String = defaultTag ?: "[APP-DEBUG]"

    abstract fun log(string: String, tag: String = defaultTag)

    object LoggerDebug : Logger() {
        override fun log(string: String, tag: String) {
            Log.d(tag, string)
        }
    }

    object LoggerRelease : Logger() {
        override fun log(string: String, tag: String) {}
    }

    companion object {
        private val isDebugConfig = BuildConfig.DEBUG

        val instance: Logger by lazy {
            if(isDebugConfig)
            LoggerDebug
            else
                LoggerRelease
        }

    }
}

Then to use your logger class:

class MainActivity : AppCompatActivity() {

private val logger = Logger.instance

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    logger.log("Activity launched...")
    ...
    myView.setOnClickListener {
        ...

        logger.log("My View clicked!", "View-click")
    }
}

== UPDATE ==

If we want to avoid string concatenations for better performances, we can add an inline function with a lambda that will be called only in debug config:

// Add this function to the Logger class.
inline fun commit(block: Logger.() -> Unit) {
    if(this is LoggerDebug)
        block.invoke(this)
}

And then:

 logger.commit {
     log("Logging without $myVar waste of resources"+ "My fancy concat")
 }

Since we are using an inline function, there are no extra object allocation and no extra virtual method calls.

How to draw border on just one side of a linear layout?

Borders of different colors. I used 3 items.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
        </shape>
    </item>
    <item android:top="3dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/light_grey" />
        </shape>
    </item>
    <item
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
</layer-list>

Is there a RegExp.escape function in JavaScript?

The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).

If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (., ?, +, *, ^, $, |, \) or start something ((, [, {) is all you need:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

Difference between Spring MVC and Struts MVC

Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts

how much memory can be accessed by a 32 bit machine?

Yes, a 32-bit architecture is limited to addressing a maximum of 4 gigabytes of memory. Depending on the operating system, this number can be cut down even further due to reserved address space.

This limitation can be removed on certain 32-bit architectures via the use of PAE (Physical Address Extension), but it must be supported by the processor. PAE eanbles the processor to access more than 4 GB of memory, but it does not change the amount of virtual address space available to a single process—each process would still be limited to a maximum of 4 GB of address space.

And yes, theoretically a 64-bit architecture can address 16.8 million terabytes of memory, or 2^64 bytes. But I don't believe the current popular implementations fully support this; for example, the AMD64 architecture can only address up to 1 terabyte of memory. Additionally, your operating system will also place limitations on the amount of supported, addressable memory. Many versions of Windows (particularly versions designed for home or other non-server use) are arbitrarily limited.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Number of regex matches

I know this is a little old, but this but here is a concise function for counting regex patterns.

def regex_cnt(string, pattern):
    return len(re.findall(pattern, string))

string = 'abc123'

regex_cnt(string, '[0-9]')

Programmatically trigger "select file" dialog box

There is no cross browser way of doing it, for security reasons. What people usually do is overlay the input file over something else and set it's visibility to hidden so it gets triggered on it's own. More info here.

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

After experimenting on that case: android:textColor="@colors/text_color" is wrong since @color is not filename dependant. You can name your resource file foobar.xml, it doesn't matter but if you have defined some colors in it you can access them using @color/some_color.

Update:

file location: res/values/colors.xml The filename is arbitrary. The element's name will be used as the resource ID. (Source)

Using PHP variables inside HTML tags?

There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:

<html>
  <body>
    <?php
      $link = "http://www.google.com";
    ?>
    <a href="<?= $link ?>">Click here to go to Google.</a>
  </body>
</html>

This will evaluate the variable as a string, in essence shorthand for echo $link;

How can I listen to the form submit event in javascript?

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.

HTML

<form>
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}

An object reference is required to access a non-static member

You should make your audioSounds and minTime members static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

But I would consider using singleton objects instead of static members instead:

public class SoundManager : MonoBehaviour
{

    public List<AudioSource> audioSounds = new List<AudioSource>();
    public double minTime = 0.5;

    public static SoundManager Instance { get; private set; }

    void Awake()
    {
        Instance = this;
    }

    public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
    {    
        bool playsound = false;
        foreach (AudioSource sound in audioSounds) // Loop through List with foreach
        {  
            if (sourceSound.name != sound.name && sound.time <= minTime)
            {
                playsound = true;
            }
        }

        if(playsound) {
            AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
        }

    }
}

Update from September 2020:

Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.

If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Creating an instance using the class name and calling constructor

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.

Uncaught ReferenceError: angular is not defined - AngularJS not working

You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular does not exist yet. This is an error (see your dev tools console).

In this line:

var app = angular.module(`

you are attempting to access a variable called angular. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.

  <h1>{{2+3}}</h1>

  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  -->
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

      <script>
        var app = angular.module('myApp',[]);

        app.directive('myDirective',function(){

            return function(scope, element,attrs) {
                element.bind('click',function() {alert('click')});
            };

        });
    </script>

For completeness, it is true that your directive is similar to the already existing directive ng-click, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.

Click in OK button inside an Alert (Selenium IDE)

about Selenium IDE, I am not an expert but you have to add the line "choose ok on next confirmation" before the event which trigger the alert/confirm dialog box as you can see into this screenshot:

Selenium IDE order matter

How to set specific Java version to Maven

I did not have success on mac with just setting JAVA_HOME in the console but I was successful with this approach

  • Create .mavenrc file at your at your home directory (so the file will path will be ~/.mavenrc
  • Into that file paste export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

Make an Android button change background on click through XML

I used this to change the background for my button

            button.setBackground(getResources().getDrawable(R.drawable.primary_button));

"button" is the variable holding my Button, and the image am setting in the background is primary_button

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

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

  • call is blocking:

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

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

"’" showing on page instead of " ' "

The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:

htmlText = htmlText.Replace('–', '-');

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

Grunt watch error - Waiting...Fatal error: watch ENOSPC

In my case I found that I have an aggressive plugin for Vim, just restarted it.

Python Infinity - Any caveats?

A VERY BAD CAVEAT : Division by Zero

in a 1/x fraction, up to x = 1e-323 it is inf but when x = 1e-324 or little it throws ZeroDivisionError

>>> 1/1e-323
inf

>>> 1/1e-324
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero

so be cautious!

How to install XNA game studio on Visual Studio 2012?

There seems to be some confusion over how to get this set up for the Express version specifically. Using the Windows Desktop (WD) version of VS Express 2012, I followed the instructions in Steve B's and Rick Martin's answers with the modifications below.

  • In step 2 rather than copying to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0", copy to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WDExpressExtensions\Microsoft\XNA Game Studio 4.0"
  • In step 4, after making the changes also add the line <Edition>WDExpress</Edition> (you should be able to see where it makes sense)
  • In step 5, replace devenv.exe with WDExpress.exe
  • In Rick Martin's step, replace "%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions" with "%LocalAppData%\Microsoft\WDExpress\11.0\Extensions"

I haven't done a lot of work since then, but I did manage to create a new game project and it seems fine so far.

Moving Panel in Visual Studio Code to right side

Hope this will help someone.

-> open to keyboard shortcut

-> search for "workbench.action.togglePanelPosition"

-> assign your desired shortcut

I've assigned keybinding "cmd+`"

{
  "key": "cmd+`",
  "command": "workbench.action.togglePanelPosition"
}

now I can toggle the terminal by pressing "cmd + `"

Open CSV file via VBA (performance)

I have the same issue, I'm not able to open a CSV file in Excel. I've found a solution that worked for me in this question Opening a file in excel via Workbooks.OpenText

That question helped me to figure out a code that works for me. The code looks more or less like this:

Private Sub OpenCSVFile(filename as String)
    Dim datasourceFilename As String
    Dim currentPath As String

    datasourceFilename = "\" & filename & ".csv"
    currentPath = ActiveWorkbook.Path

    Workbooks.OpenText Filename:=currentPath & datasourceFilename, _
                       Origin:=xlWindows, _
                       StartRow:=1, _
                       DataType:=xlDelimited, _
                       TextQualifier:=xlDoubleQuote, _
                       ConsecutiveDelimiter:=False, _
                       Tab:=False, _
                       Semicolon:=False, _
                       Comma:=True, _
                       Space:=False, _
                       Other:=False, _
                       FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
                       DecimalSeparator:=".", _
                       ThousandsSeparator:=",", _
                       TrailingMinusNumbers:=True
End Sub

At least, it helped me to know about lots of parameters I can use with Workbooks.OpenText method.

How to find the length of a string in R

You could also use the stringr package:

library(stringr)
str_length("foo")
[1] 3

How do I vertically align something inside a span tag?

The flexbox way:

.foo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
}

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

What exactly is Apache Camel?

In plain English, camel gets (many) things done without much of boiler plate code.

Just to give you a perspective, the Java DSL given below will create a REST endpoint which will be able to accept an XML consisting of List of Products and splits it into multiple products and invoke Process method of BrandProcessor with it. And just by adding .parallelProcessing (note the commented out part) it will parallel process all the Product Objects. (Product class is JAXB/XJC generated Java stub from the XSD which the input xml is confined to.) This much code (along with few Camel dependencies) will get the job done which used to take 100s of lines of Java code.

from("servlet:item-delta?matchOnUriPrefix=true&httpMethodRestrict=POST")
.split(stax(Product.class))
/*.parallelProcessing()*/
.process(itemDeltaProcessor);

After adding the route ID and logging statement

from("servlet:item-delta?matchOnUriPrefix=true&httpMethodRestrict=POST")
.routeId("Item-DeltaRESTRoute")
.log(LoggingLevel.INFO, "Item Delta received on Item-DeltaRESTRoute")
.split(stax(Product.class))
.parallelProcessing()
.process(itemDeltaProcessor);

This is just a sample, Camel is much more than just REST end point. Just take a look the pluggable component list http://camel.apache.org/components.html

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

Ansible - read inventory hosts and variables to group_vars/all file

If you want to refer one host define under /etc/ansible/host in a task or role, the bellow link might help:

https://www.middlewareinventory.com/blog/ansible-get-ip-address/

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

Display curl output in readable JSON format in Unix shell script

This is to add to of Gilles' Answer. There are many ways to get this done but personally I prefer something lightweight, easy to remember and universally available (e.g. come with standard LTS installations of your preferred Linux flavor or easy to install) on common *nix systems.

Here are the options in their preferred order:

Python Json.tool module

echo '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool

pros: almost available everywhere; cons: no color coding


jq (may require one time installation)

echo '{"foo": "lorem", "bar": "ipsum"}' | jq

cons: needs to install jq; pros: color coding and versatile


json_pp (available in Ubuntu 16.04 LTS)

echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp

For Ruby users

gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty

Android TextView Text not getting wrapped

Even-though this is an old thread, i'd like to share my experience as it helped me. My application was working fine for OS 2.0 & 4.0+ but for a HTC phone running OS 3.x the text was not wrapping. What worked for me was to include both of these tags.

android:maxLines="100"
android:scrollHorizontally="false"

If you eliminate either it was not working for only the os 3.0 device. "ellipsize" parameter had neutral effect. Here is the full textview tag below

<TextView
                android:id="@+id/cell_description"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingTop="5dp"
                android:maxLines="100"
                android:scrollHorizontally="false"
                android:textStyle="normal"
                android:textSize="11sp"
                android:textColor="@color/listcell_detail"/>

Hope this would help someone.

Datatables Select All Checkbox

You can use Checkboxes extension for jQuery Datatables.

var table = $('#example').DataTable({
   'ajax': 'https://api.myjson.com/bins/1us28',
   'columnDefs': [
      {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
      }
   ],
   'select': {
      'style': 'multi'
   },
   'order': [[1, 'asc']]
});

See this example for code and demonstration.

See Checkboxes project page for more examples and documentation.

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

How to create .ipa file using Xcode?

Click Product > Archive from the menu, once this is complete open up the Organiser and click the latest version > Distribute > Save for Enterprise or Ad-Hoc Deployment > Choose correct signing > Save to destination

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

In IntelliJ Community Edition 2019.02, Changing the following settings worked for me

  1. Update File->Project structure->Project Settings->Project->Project Language level to Java 11 (update to the java version that you wish to use in your project) using drop down.

  2. Update File->Project structure->Project Settings->Modules->Language level

  3. Update File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Project ByteCode Version to java 11.

  4. Update Target version for all the entries under File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Per module Byte Code Version.

SQLite add Primary Key

As long as you are using CREATE TABLE, if you are creating the primary key on a single field, you can use:

CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER PRIMARY KEY,
field3 BLOB,
);

With CREATE TABLE, you can also always use the following approach to create a primary key on one or multiple fields:

CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER,
field3 BLOB,
PRIMARY KEY (field2, field1)
);

Reference: http://www.sqlite.org/lang_createtable.html

This answer does not address table alteration.

Embed an External Page Without an Iframe?

HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/

How to use double or single brackets, parentheses, curly braces

I just wanted to add these from TLDP:

~:$ echo $SHELL
/bin/bash

~:$ echo ${#SHELL}
9

~:$ ARRAY=(one two three)

~:$ echo ${#ARRAY}
3

~:$ echo ${TEST:-test}
test

~:$ echo $TEST


~:$ export TEST=a_string

~:$ echo ${TEST:-test}
a_string

~:$ echo ${TEST2:-$TEST}
a_string

~:$ echo $TEST2


~:$ echo ${TEST2:=$TEST}
a_string

~:$ echo $TEST2
a_string

~:$ export STRING="thisisaverylongname"

~:$ echo ${STRING:4}
isaverylongname

~:$ echo ${STRING:6:5}
avery

~:$ echo ${ARRAY[*]}
one two one three one four

~:$ echo ${ARRAY[*]#one}
two three four

~:$ echo ${ARRAY[*]#t}
one wo one hree one four

~:$ echo ${ARRAY[*]#t*}
one wo one hree one four

~:$ echo ${ARRAY[*]##t*}
one one one four

~:$ echo $STRING
thisisaverylongname

~:$ echo ${STRING%name}
thisisaverylong

~:$ echo ${STRING/name/string}
thisisaverylongstring

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

Remove duplicated rows

The function distinct() in the dplyr package performs arbitrary duplicate removal, either from specific columns/variables (as in this question) or considering all columns/variables. dplyr is part of the tidyverse.

Data and package

library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))

Remove rows duplicated in a specific column (e.g., columna)

Note that .keep_all = TRUE retains all columns, otherwise only column a would be retained.

distinct(dat, a, .keep_all = TRUE)

  a b
1 1 A
2 2 B

Remove rows that are complete duplicates of other rows:

distinct(dat)

  a b
1 1 A
2 2 B
3 1 C
4 2 D

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

What is difference between arm64 and armhf?

armhf stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.

On the beaglebone black, for example:

:~$ dpkg --print-architecture
armhf

Although other commands (such as uname -a or arch) will just show armv7l

:~$ cat /proc/cpuinfo 
processor       : 0
model name      : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 995.32
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...

The vfpv3 listed under Features is what refers to the floating point support.

Incidentally, armhf, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.

Android Completely transparent Status Bar?

The following code will make your status bar along with the navigation bar transparent (note that this will make your layout a full screen layout like the layouts used in games):

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables sticky immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE_STICKY.
    // Or for regular immersive mode replace it with SYSTEM_UI_FLAG_IMMERSIVE
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

To learn more, visit this link.

Setting the default page for ASP.NET (Visual Studio) server configuration

One way to achieve this is to add a DefaultDocument settings in the Web.config.

  <system.webServer>
   <defaultDocument>
    <files>
      <clear />
      <add value="DefaultPage.aspx" />
    </files>
   </defaultDocument>
  </system.webServer>

Convert DOS line endings to Linux line endings in Vim

To run directly in a Linux console:

vim file.txt +"set ff=unix" +wq

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

Current time formatting with Javascript

To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.

Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

Build Android Studio app via command line

note, you can also do this within Android Studio by clicking the gradle window, and then the 'elephant' button. This will open a new window called "run anything" (can also be found by searching for that name in 'search everywhere') where you can manually type any gradle command you want in. Not "quite" command line, but often provides more of what I need than windows command line.

This allows you to give optional params to gradle tasks, etc.

SHA-256 or MD5 for file integrity

The underlying MD5 algorithm is no longer deemed secure, thus while md5sum is well-suited for identifying known files in situations that are not security related, it should not be relied on if there is a chance that files have been purposefully and maliciously tampered. In the latter case, the use of a newer hashing tool such as sha256sum is highly recommended.

So, if you are simply looking to check for file corruption or file differences, when the source of the file is trusted, MD5 should be sufficient. If you are looking to verify the integrity of a file coming from an untrusted source, or over from a trusted source over an unencrypted connection, MD5 is not sufficient.

Another commenter noted that Ubuntu and others use MD5 checksums. Ubuntu has moved to PGP and SHA256, in addition to MD5, but the documentation of the stronger verification strategies are more difficult to find. See the HowToSHA256SUM page for more details.

How to insert date values into table

let suppose we create a table Transactions using SQl server management studio

txn_id int,

txn_type_id varchar(200),

Account_id int,

Amount int,

tDate date

);

with date datatype we can insert values in simple format: 'yyyy-mm-dd'

INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');

Moreover we can have differet time formats like

DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS 

get unique machine id

You should not use MAC, its bad way. Because some OS just changeing it every day. My expirience : Tools.CpuID.ProcessorId() + volumeSerial;

string volumeSerial = "";
    try {
        ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""C:""");
        dsk.Get();
        volumeSerial = dsk["VolumeSerialNumber"].ToString();
    } catch {
        try {
            ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""D:""");
            dsk.Get();
            volumeSerial = dsk["VolumeSerialNumber"].ToString();
        } catch { File.WriteAllText("disk.mising","need C or D"); Environment.Exit(0); }
    }

public class CpuID
    {
        [DllImport("user32", EntryPoint = "CallWindowProcW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        private static extern IntPtr CallWindowProcW([In] byte[] bytes, IntPtr hWnd, int msg, [In, Out] byte[] wParam, IntPtr lParam);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool VirtualProtect([In] byte[] bytes, IntPtr size, int newProtect, out int oldProtect);

        const int PAGE_EXECUTE_READWRITE = 0x40;



        public static string ProcessorId()
        {
            byte[] sn = new byte[8];

            if (!ExecuteCode(ref sn))
                return "ND";

            return string.Format("{0}{1}", BitConverter.ToUInt32(sn, 4).ToString("X8"), BitConverter.ToUInt32(sn, 0).ToString("X8"));
        }

        private static bool ExecuteCode(ref byte[] result)
    {
        int num;

        /* The opcodes below implement a C function with the signature:
         * __stdcall CpuIdWindowProc(hWnd, Msg, wParam, lParam);
         * with wParam interpreted as an 8 byte unsigned character buffer.
         * */

        byte[] code_x86 = new byte[] {
            0x55,                      /* push ebp */
            0x89, 0xe5,                /* mov  ebp, esp */
            0x57,                      /* push edi */
            0x8b, 0x7d, 0x10,          /* mov  edi, [ebp+0x10] */
            0x6a, 0x01,                /* push 0x1 */
            0x58,                      /* pop  eax */
            0x53,                      /* push ebx */
            0x0f, 0xa2,                /* cpuid    */
            0x89, 0x07,                /* mov  [edi], eax */
            0x89, 0x57, 0x04,          /* mov  [edi+0x4], edx */
            0x5b,                      /* pop  ebx */
            0x5f,                      /* pop  edi */
            0x89, 0xec,                /* mov  esp, ebp */
            0x5d,                      /* pop  ebp */
            0xc2, 0x10, 0x00,          /* ret  0x10 */
        };
        byte[] code_x64 = new byte[] {
            0x53,                                     /* push rbx */
            0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, /* mov rax, 0x1 */
            0x0f, 0xa2,                               /* cpuid */
            0x41, 0x89, 0x00,                         /* mov [r8], eax */
            0x41, 0x89, 0x50, 0x04,                   /* mov [r8+0x4], edx */
            0x5b,                                     /* pop rbx */
            0xc3,                                     /* ret */
        };

        byte[] code;

        if (IsX64Process())
            code = code_x64;
        else 
            code = code_x86;

        IntPtr ptr = new IntPtr(code.Length);

        if (!VirtualProtect(code, ptr, PAGE_EXECUTE_READWRITE, out num))
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

        ptr = new IntPtr(result.Length);

        try {
            return (CallWindowProcW(code, IntPtr.Zero, 0, result, ptr) != IntPtr.Zero);
        } catch { System.Windows.Forms.MessageBox.Show("?????? ??????????"); return false; }
    }

        private static bool IsX64Process()
        {
            return IntPtr.Size == 8;
        }

    }

Fatal error: Class 'ZipArchive' not found in

For CentOS based server use

yum install php-pecl-zip.x86_64

Enable it by running: echo "extension=zip.so" >> /etc/php.d/zip.ini

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

How do operator.itemgetter() and sort() work?

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1])

Or just an ordinary function:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python