Programs & Examples On #Dijit.form

The Dojo Toolkit dijit.form package contains “form widgets”.

Int or Number DataType for DataAnnotation validation attribute

Use regex in data annotation

[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int MaxJsonLength { get; set; }

Throwing exceptions from constructors

It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:

class A
{
public:
  A () {
    throw int ();
  }
};

A a;     // Implementation defined behaviour if exception is thrown (15.3/13)

int main ()
{
  try
  {
    // Exception for 'a' not caught here.
  }
  catch (int)
  {
  }
}

Best JavaScript compressor

Here's the source code of an HttpHandler which does that, maybe it'll help you

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

jQuery val is undefined?

You probably included your JavaScript before the HTML: example.

You should either execute your JavaScript when the window loads (or better, when the DOM is fully loaded), or you should include your JavaScript after your HTML: example.

Object of class stdClass could not be converted to string - laravel

$data is indeed an array, but it's made up of objects.

Convert its content to array before creating it:

$data = array();
foreach ($results as $result) {
   $result->filed1 = 'some modification';
   $result->filed2 = 'some modification2';
   $data[] = (array)$result;  
   #or first convert it and then change its properties using 
   #an array syntax, it's up to you
}
Excel::create(....

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

JQuery, select first row of table

late in the game , but this worked for me:

$("#container>table>tbody>tr:first").trigger('click');

How to get label of select option with jQuery?

I found this helpful

$('select[name=users] option:selected').text()

When accessing the selector using the this keyword.

$(this).find('option:selected').text()

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

Adding files to java classpath at runtime

My solution:

File jarToAdd = new File("/path/to/file");

new URLClassLoader(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()) {
    @Override
    public void addURL(URL url) {
         super.addURL(url);
    }
}.addURL(jarToAdd.toURI().toURL());

&& (AND) and || (OR) in IF statements

Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.

An interesting fact is that Java also uses the & and | as logic operands (they are overloaded, with int types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.

Regex remove all special characters except numbers?

to remove symbol use tag [ ]

step:1

[]

step 2:place what symbol u want to remove eg:@ like [@]

[@]

step 3:

var name = name.replace(/[@]/g, "");

thats it

_x000D_
_x000D_
var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

Extra Tips

To remove space (give one space into square bracket like []=>[ ])

[@ ]

It Remove Everything (using except)

[^place u dont want to remove]

eg:i remove everyting except alphabet (small and caps)

[^a-zA-Z ]

_x000D_
_x000D_
var name="ggggg33333@#$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Use a content script to access the page context variables and functions

Underlying cause:
Content scripts are executed in an "isolated world" environment.

Solution::
To access functions/variables of the page context ("main world") you have to inject the code into the page itself using DOM. Same thing if you want to expose your functions/variables to the page context (in your case it's the state() method).

  • Note in case communication with the page script is needed:
    Use DOM CustomEvent handler. Examples: one, two, and three.

  • Note in case chrome API is needed in the page script:
    Since chrome.* APIs can't be used in the page script, you have to use them in the content script and send the results to the page script via DOM messaging (see the note above).

Safety warning:
A page may redefine or augment/hook a built-in prototype so your exposed code may fail if the page did it in an incompatible fashion. If you want to make sure your exposed code runs in a safe environment then you should either a) declare your content script with "run_at": "document_start" and use Methods 2-3 not 1, or b) extract the original native built-ins via an empty iframe, example. Note that with document_start you may need to use DOMContentLoaded event inside the exposed code to wait for DOM.

Table of contents

  • Method 1: Inject another file
  • Method 2: Inject embedded code
  • Method 2b: Using a function
  • Method 3: Using an inline event
  • Dynamic values in the injected code

Method 1: Inject another file

This is the easiest/best method when you have lots of code. Include your actual JS code in a file within your extension, say script.js. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

Note: For security reasons, Chrome prevents loading of js files. Your file must be added as a "web_accessible_resources" item (example) :

// manifest.json must include: 
"web_accessible_resources": ["script.js"],

If not, the following error will appear in the console:

Denying load of chrome-extension://[EXTENSIONID]/script.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Method 2: Inject embedded code

This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).

var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

Note: template literals are only supported in Chrome 41 and above. If you want the extension to work in Chrome 40-, use:

var actualCode = ['/* Code here. Example: */' + 'alert(0);',
                  '// Beware! This array have to be joined',
                  '// using a newline. Otherwise, missing semicolons',
                  '// or single-line comments (//) will mess up your',
                  '// code ----->'].join('\n');

Method 2b: Using a function

For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:

var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // For example, the following does NOT overwrite the global `alert` method
    var alert = null;
    // To overwrite a global variable, prefix `window`:
    window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

This method works, because the + operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:

function injectScript(func) {
    var actualCode = '(' + func + ')();'
    ...
}
injectScript(function() {
   alert("Injected script");
});

Note: Since the function is serialized, the original scope, and all bound properties are lost!

var scriptToInject = function() {
    console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output:  "undefined"

Method 3: Using an inline event

Sometimes, you want to run some code immediately, e.g. to run some code before the <head> element is created. This can be done by inserting a <script> tag with textContent (see method 2/2b).

An alternative, but not recommended is to use inline events. It is not recommended because if the page defines a Content Security policy that forbids inline scripts, then inline event listeners are blocked. Inline scripts injected by the extension, on the other hand, still run. If you still want to use inline events, this is how:

var actualCode = '// Some code example \n' + 
                 'console.log(document.documentElement.outerHTML);';

document.documentElement.setAttribute('onreset', actualCode);
document.documentElement.dispatchEvent(new CustomEvent('reset'));
document.documentElement.removeAttribute('onreset');

Note: This method assumes that there are no other global event listeners that handle the reset event. If there is, you can also pick one of the other global events. Just open the JavaScript console (F12), type document.documentElement.on, and pick on of the available events.

Dynamic values in the injected code

Occasionally, you need to pass an arbitrary variable to the injected function. For example:

var GREETING = "Hi, I'm ";
var NAME = "Rob";
var scriptToInject = function() {
    alert(GREETING + NAME);
};

To inject this code, you need to pass the variables as arguments to the anonymous function. Be sure to implement it correctly! The following will not work:

var scriptToInject = function (GREETING, NAME) { ... };
var actualCode = '(' + scriptToInject + ')(' + GREETING + ',' + NAME + ')';
// The previous will work for numbers and booleans, but not strings.
// To see why, have a look at the resulting string:
var actualCode = "(function(GREETING, NAME) {...})(Hi, I'm ,Rob)";
//                                                 ^^^^^^^^ ^^^ No string literals!

The solution is to use JSON.stringify before passing the argument. Example:

var actualCode = '(' + function(greeting, name) { ...
} + ')(' + JSON.stringify(GREETING) + ',' + JSON.stringify(NAME) + ')';

If you have many variables, it's worthwhile to use JSON.stringify once, to improve readability, as follows:

...
} + ')(' + JSON.stringify([arg1, arg2, arg3, arg4]) + ')';

Singleton design pattern vs Singleton beans in Spring container

Singleton beans in Spring and classes based on Singleton design pattern are quite different.

Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader where as the scope of a Spring singleton bean is described as 'per container per bean'. Singleton scope in Spring means that this bean will be instantiated only once by Spring. Spring container merely returns the same instance again and again for subsequent calls to get the bean.

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I had the same problem. To solve the error: Close it on the emulator and then run it using Android Studio.

The error happens when you try to re-run the app when the app is already running on the emulator.

Basically the error says - "I don't have the existing channel anymore and disposing the already established connection" as you have run the app from Android Studio again.

How does a Breadth-First Search work when looking for Shortest Path?

The following solution works for all the test cases.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

   public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);

            int testCases = sc.nextInt();

            for (int i = 0; i < testCases; i++)
            {
                int totalNodes = sc.nextInt();
                int totalEdges = sc.nextInt();

                Map<Integer, List<Integer>> adjacencyList = new HashMap<Integer, List<Integer>>();

                for (int j = 0; j < totalEdges; j++)
                {
                    int src = sc.nextInt();
                    int dest = sc.nextInt();

                    if (adjacencyList.get(src) == null)
                    {
                        List<Integer> neighbours = new ArrayList<Integer>();
                        neighbours.add(dest);
                        adjacencyList.put(src, neighbours);
                    } else
                    {
                        List<Integer> neighbours = adjacencyList.get(src);
                        neighbours.add(dest);
                        adjacencyList.put(src, neighbours);
                    }


                    if (adjacencyList.get(dest) == null)
                    {
                        List<Integer> neighbours = new ArrayList<Integer>();
                        neighbours.add(src);
                        adjacencyList.put(dest, neighbours);
                    } else
                    {
                        List<Integer> neighbours = adjacencyList.get(dest);
                        neighbours.add(src);
                        adjacencyList.put(dest, neighbours);
                    }
                }

                int start = sc.nextInt();

                Queue<Integer> queue = new LinkedList<>();

                queue.add(start);

                int[] costs = new int[totalNodes + 1];

                Arrays.fill(costs, 0);

                costs[start] = 0;

                Map<String, Integer> visited = new HashMap<String, Integer>();

                while (!queue.isEmpty())
                {
                    int node = queue.remove();

                    if(visited.get(node +"") != null)
                    {
                        continue;
                    }

                    visited.put(node + "", 1);

                    int nodeCost = costs[node];

                    List<Integer> children = adjacencyList.get(node);

                    if (children != null)
                    {
                        for (Integer child : children)
                        {
                            int total = nodeCost + 6;
                            String key = child + "";

                            if (visited.get(key) == null)
                            {
                                queue.add(child);

                                if (costs[child] == 0)
                                {
                                    costs[child] = total;
                                } else if (costs[child] > total)
                                {
                                    costs[child] = total;
                                }
                            }
                        }
                    }
                }

                for (int k = 1; k <= totalNodes; k++)
                {
                    if (k == start)
                    {
                        continue;
                    }

                    System.out.print(costs[k] == 0 ? -1 : costs[k]);
                    System.out.print(" ");
                }
                System.out.println();
            }
        }
}

Sorting A ListView By Column

Since this is still a top viewed thread, I thought I might note that I came up with a dynamic solution to sort the listview by column. Here's the code just in case someone else wants to use it as well. It pretty much just involves sending the listview items to a datatable, sorting the default view of the datatable by the column name (using the index of the clicked column), and then overwriting that table with the defaultview.totable() method. Then pretty much just add them back to the listview. And wa la, its a sorted listview by column.

public void SortListView(int Index)
    {
        DataTable TempTable = new DataTable();
        //Add column names to datatable from listview
        foreach (ColumnHeader iCol in MyListView.Columns)
        {
            TempTable.Columns.Add(iCol.Text);
        }
        //Create a datarow from each listviewitem and add it to the table
        foreach (ListViewItem Item in MyListView.Items)
        {
             DataRow iRow = TempTable.NewRow();
             // the for loop dynamically copies the data one by one instead of doing irow[i] = MyListView.Subitems[1]... so on
            for (int i = 0; i < MyListView.Columns.Count; i++)
            {
                if (i == 0)
                {
                    iRow[i] = Item.Text;
                }
                else
                {
                    iRow[i] = Item.SubItems[i].Text;
                }
            }
            TempTable.Rows.Add(iRow);
        }
        string SortType = string.Empty;
        //LastCol is a public int variable on the form, and LastSort is public string variable
        if (LastCol == Index)
        {
            if (LastSort == "ASC" || LastSort == string.Empty || LastSort == null)
            {
                SortType = "DESC";
                LastSort = "DESC";
            }
            else
            {
                SortType = "ASC";
                LastSort = "ASC";
            }
        }
        else
        {
            SortType = "DESC";
            LastSort = "DESC";
        }
        LastCol = Index;
        MyListView.Items.Clear();
        //Sort it based on the column text clicked and the sort type (asc or desc)
        TempTable.DefaultView.Sort = MyListView.Columns[Index].Text + " " + SortType;
        TempTable = TempTable.DefaultView.ToTable();
        //Create a listview item from the data in each row
        foreach (DataRow iRow in TempTable.Rows)
        {
            ListViewItem Item = new ListViewItem();
            List<string> SubItems = new List<string>();
            for (int i = 0; i < TempTable.Columns.Count; i++)
            {
                if (i == 0)
                {
                    Item.Text = iRow[i].ToString();
                }
                else
                {
                    SubItems.Add(iRow[i].ToString());
                }
            }
            Item.SubItems.AddRange(SubItems.ToArray());
            MyListView.Items.Add(Item);
        }
    }

This method is dynamic as it uses the existing column name and doesn't require you to know the index or name of each column or even how many columns are in the listview/datatable. You can call it by doing creating an event for the listview.columnclick and then SortListView(e.column).

How to Get a Sublist in C#

Reverse the items in a sub-list

int[] l = {0, 1, 2, 3, 4, 5, 6};
var res = new List<int>();
res.AddRange(l.Where((n, i) => i < 2));
res.AddRange(l.Where((n, i) => i >= 2 && i <= 4).Reverse());
res.AddRange(l.Where((n, i) => i > 4));

Gives 0,1,4,3,2,5,6

How to have git log show filenames like svn log -v

git diff --stat HEAD^! shows changed files and added/removed line counts for the last commit (HEAD).

It seems to me that there is no single command to get concise output consisting only of filenames and added and removed line counts for several commits at once, so I created my own bash script for that:

#!/bin/bash
for ((i=0; i<=$1; i++))
do
    sha1=`git log -1 --skip=$i --pretty=format:%H`
    echo "HEAD~$i $sha1"
    git diff --stat HEAD~$(($i+1)) HEAD~$i 
done

To be called eg. ./changed_files 99 to get the changes in a concise form from HEAD to HEAD~99. Can be piped eg. to less.

Use CASE statement to check if column exists in table - SQL Server

You can check in the system 'table column mapping' table

SELECT count(*)
  FROM Sys.Columns c
  JOIN Sys.Tables t ON c.Object_Id = t.Object_Id
 WHERE upper(t.Name) = 'TAGS'
   AND upper(c.NAME) = 'MODIFIEDBYUSER'

performSelector may cause a leak because its selector is unknown

Here is an updated macro based on the answer given above. This one should allow you to wrap your code even with a return statement.

#define SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(code)                        \
    _Pragma("clang diagnostic push")                                        \
    _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")     \
    code;                                                                   \
    _Pragma("clang diagnostic pop")                                         \


SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(
    return [_target performSelector:_action withObject:self]
);

PHP __get and __set magic methods

Drop the public $bar; declaration and it should work as expected.

What is the use of ObservableCollection in .net?

class FooObservableCollection : ObservableCollection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        base.Add(index, Foo);

        if (this.CollectionChanged != null)
            this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
    }
}

var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;

collection.Add(new Foo());

void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
    Foo newItem = e.NewItems.OfType<Foo>().First();
}

link_to image tag. how to add class to a tag

Just adding that you can pass the link_to method a block:

<%= link_to href: 'http://www.example.com/' do %>
    <%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>

results in:

<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
    <img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>

This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

SQL Query - Concatenating Results into One String

from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row

The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select

Modify XML existing content in C#

The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

Just update the node you have selected and .Save() that XmlDocument.

jQuery DataTables: control table width

I have had numerous issues with the column widths of datatables. The magic fix for me was including the line

table-layout: fixed;

this css goes with the overall css of the table. For example, if you have declared the datatables like the following:

LoadTable = $('#LoadTable').dataTable.....

then the magic css line would go in the class Loadtable

#Loadtable {
margin: 0 auto;
clear: both;
width: 100%;
table-layout: fixed;

}

How can I read large text files in Python, line by line, without loading it into memory?

Please try this:

with open('filename','r',buffering=100000) as f:
    for line in f:
        print line

What is char ** in C?

Technically, the char* is not an array, but a pointer to a char.

Similarly, char** is a pointer to a char*. Making it a pointer to a pointer to a char.

C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of chars, or an array of strings.

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if (target.value === "[email protected]") {
            target.value= "";
        }
    }
    </script>
<input type="text" name="email" value="[email protected]" size="30" onfocus="clearThis(this)">

Try it out here: http://jsfiddle.net/2K3Vp/

How to POST raw whole JSON in the body of a Retrofit request?

This is what works me for the current version of retrofit 2.6.2,

First of all, we need to add a Scalars Converter to the list of our Gradle dependencies, which would take care of converting java.lang.String objects to text/plain request bodies,

implementation'com.squareup.retrofit2:converter-scalars:2.6.2'

Then, we need to pass a converter factory to our Retrofit builder. It will later tell Retrofit how to convert the @Body parameter passed to the service.

private val retrofitBuilder: Retrofit.Builder by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
}

Note: In my retrofit builder i have two converters Gson and Scalars you can use both of them but to send Json body we need to focus Scalars so if you don't need Gson remove it

Then Retrofit service with a String body parameter.

@Headers("Content-Type: application/json")
@POST("users")
fun saveUser(@Body   user: String): Response<MyResponse>

Then create the JSON body

val user = JsonObject()
 user.addProperty("id", 001)
 user.addProperty("name", "Name")

Call your service

RetrofitService.myApi.saveUser(user.toString())

SQL Server Management Studio – tips for improving the TSQL coding process

F5 to run the current query is an easy win, after that, the generic MS editor commands of CTRL + K + C to comment out the selected text and then CTRL + K + U to uncomment.

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

How to add empty spaces into MD markdown readme on GitHub?

You can use <pre> to display all spaces & blanks you have typed. E.g.:

<pre>
hello, this is
   just an     example
....
</pre>

View content of H2 or HSQLDB in-memory database

For HSQLDB, The following worked for me:

DatabaseManager.threadedDBM();

And this brought up the GUI with my tables and data once I pointed it to the right named in-mem database.

It is basically the equivalent of newing up a DatabaseManager (the non Swing variety), which prompts for connection details, and is set to --noexit)

I also tried the Swing version, but it only had a main, and I was unsure of the arguments to pass. If anyone knows, please post here.

Just because I searched for hours for the right database name: The name of the database is the name of your datasource. So try with URL jdbc:hsqldb:mem:dataSource if you have a data source bean with id=dataSource. If this does not work, try testdb which is the default.

How to access data/data folder in Android device?

may be to access this folder you need administrative rights.

so you have two options:-

  1. root your device and than try to access this folder
  2. use emulator

p.s. : if you are using any of above two options you can access this folder by following these steps

open DDMS perspective -> your device ->(Select File Explorer from right window options) select package -> data -> data -> package name ->files

and from there you can pull up your file

Why is "using namespace std;" considered bad practice?

Do not use it globally

It is considered "bad" only when used globally. Because:

  • You clutter the namespace you are programming in.
  • Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz.
  • Whatever is true for other readers of your source code is even more true for the most frequent reader of it: yourself. Come back in a year or two and take a look...
  • If you only talk about using namespace std you might not be aware of all the stuff you grab -- and when you add another #include or move to a new C++ revision you might get name conflicts you were not aware of.

You may use it locally

Go ahead and use it locally (almost) freely. This, of course, prevents you from repetition of std:: -- and repetition is also bad.

An idiom for using it locally

In C++03 there was an idiom -- boilerplate code -- for implementing a swap function for your classes. It was suggested that you actually use a local using namespace std -- or at least using std::swap:

class Thing {
    int    value_;
    Child  child_;
public:
    // ...
    friend void swap(Thing &a, Thing &b);
};
void swap(Thing &a, Thing &b) {
    using namespace std;      // make `std::swap` available
    // swap all members
    swap(a.value_, b.value_); // `std::stwap(int, int)`
    swap(a.child_, b.child_); // `swap(Child&,Child&)` or `std::swap(...)`
}

This does the following magic:

  • The compiler will choose the std::swap for value_, i.e. void std::swap(int, int).
  • If you have an overload void swap(Child&, Child&) implemented the compiler will choose it.
  • If you do not have that overload the compiler will use void std::swap(Child&,Child&) and try its best swapping these.

With C++11 there is no reason to use this pattern any more. The implementation of std::swap was changed to find a potential overload and choose it.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

Why won't my PHP app send a 404 error?

I came up to this problem.. I think that redirecting to a non existing link on your server might do the trick ! Because the server would return his 404:
header('Redirect abbb.404.nonexist'); < that doesnt exist for sure

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Just some thoughts on my case.

If you have changed the dbPath and logPath dirs to your custom values (say /data/mongodb/data, /data/mongodb/log), you must chown them to mongodb user, otherwise, the non-existent /data/db/ dir will be used.

sudo chown -R mongodb:mongodb /data/mongodb/

sudo service mongod restart

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Android Google Maps v2 - set zoom level for myLocation

You can also use:

mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );    

To just change the zoom value to any desired value between minimum value=2.0 and maximum value=21.0.

The API warns that not all locations have tiles at values at or near maximum zoom.

See this for more information about zoom methods available in the CameraUpdateFactory.

"document.getElementByClass is not a function"

Before jumping into any further error checking please first check whether its

document.getElementsByClassName() itself.

double check its getElements and not getElement

Add button to navigationbar programmatically

self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];

-(void)saveAction:(UIBarButtonItem *)sender{

//perform your action

}

HTML Entity Decode

Original author answer here.

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Example: http://jsfiddle.net/k65s3/

Input:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

How to implement infinity in Java?

double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

prints

Infinity
NaN
-Infinity

note: Infinity - Infinity is Not A Number.

Replace multiple whitespaces with single whitespace in JavaScript string

I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:

  • I want to replace multiple occurences of whitespace inside the string with a single space
  • ...and... I do not want whitespaces in the beginnin or end of the string (trim)

For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):

s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');

The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Making the Android emulator run faster

I think it is because clr virtual machine uses cpu directly without code opcode translation. It may be optimization for clr application or may be windows mobile/window phone 7 started on INTEL proccessor. Android platform based on linux and theoretically you can start android on virtual machine in i686 environment. In this case virtual machines such as vmware could execute some opcodes direcly. But this option will be allowed only if you write on the Java. Because the Java interpret their byte-code or precompile it before execution. see: http://www.taranfx.com/how-to-run-google-android-in-virtualbox-vmware-on-netbooks

psql: FATAL: role "postgres" does not exist

createuser postgres --interactive

or make a superuser postgresl just with

createuser postgres -s

How to import js-modules into TypeScript file?

You can import the whole module as follows:

import * as FriendCard from './../pages/FriendCard';

For more details please refer the modules section of Typescript official docs.

How to check if Thread finished execution

If you don't want to block the current thread by waiting/checking for the other running thread completion, you can implement callback method like this.

Action onCompleted = () => 
{  
    //On complete action
};

var thread = new Thread(
  () =>
  {
    try
    {
      // Do your work
    }
    finally
    {
      onCompleted();
    }
  });
thread.Start();

If you are dealing with controls that doesn't support cross-thread operation, then you have to invoke the callback method

this.Invoke(onCompleted);

Credentials for the SQL Server Agent service are invalid

  1. Under the "Account Name" Drop Box choose Browse. Type the user name that you used to log in to windows on the "Enter the object name to select" and then click "Check Names". Click "Ok".

  2. Under "Password" just type the password that you used for windows login.

Converting milliseconds to a date (jQuery/JavaScript)

Try using this code:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

Enjoy it!

How do I display images from Google Drive on a website?

<img src="https://drive.google.com/uc?export=view&id=Your_Image_ID" alt="">

I use on my wordpress site as storing image files on local host takes up to much space and slows down my site

I use textmate as it is easy to edit multiple URLs at same time using the 'alt/option' button

How to run a Python script in the background even after I logout SSH?

Here is a simple solution inside python using a decorator:

import os, time

def daemon(func):
    def wrapper(*args, **kwargs):
        if os.fork(): return
        func(*args, **kwargs)
        os._exit(os.EX_OK)
    return wrapper

@daemon
def my_func(count=10):    
  for i in range(0,count):
     print('parent pid: %d' % os.getppid())
     time.sleep(1)


my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own

You can of course replace the content of your bgservice.py file in place of my_func.

Before and After Suite execution hook in jUnit 4.x

As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.

T-SQL: Looping through an array of known values

use a static cursor variable and a split function:

declare @comma_delimited_list varchar(4000)
set @comma_delimited_list = '4,7,12,22,19'

declare @cursor cursor
set @cursor = cursor static for 
  select convert(int, Value) as Id from dbo.Split(@comma_delimited_list) a

declare @id int
open @cursor
while 1=1 begin
  fetch next from @cursor into @id
  if @@fetch_status <> 0 break
  ....do something....
end
-- not strictly necessary w/ cursor variables since they will go out of scope like a normal var
close @cursor
deallocate @cursor

Cursors have a bad rep since the default options when declared against user tables can generate a lot of overhead.

But in this case the overhead is quite minimal, less than any other methods here. STATIC tells SQL Server to materialize the results in tempdb and then iterate over that. For small lists like this, it's the optimal solution.

Unix epoch time to Java Date object

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

How to hide column of DataGridView when using custom DataSource?

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

$(this).attr("id") not working

Change

var ID = $(this).attr("id");

to

var ID = $(obj).attr("id");

Also you can change it to use jQuery event handler:

$('#race').change(function() {
    var select = $(this);
    var id = select.attr('id');
    if(select.val() == 'other') {
        select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
    } else {
        select.hide();
    }
});

What happens when a duplicate key is put into a HashMap?

BTW, if you want some semantics such as only put if this key is not exist. you can use concurrentHashMap with putIfAbsent() function. Check this out:

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#put(K,%20V)

concurrentHashMap is thread safe with high performance since it uses "lock striping" mechanism to improve the throughput.

How do I read a resource file from a Java jar file?

If you use resources extensively, you might consider using Commons VFS.

Also supports: * Local Files * FTP, SFTP * HTTP and HTTPS * Temporary Files "normal FS backed) * Zip, Jar and Tar (uncompressed, tgz or tbz2) * gzip and bzip2 * resources * ram - "ramdrive" * mime

There's also JBoss VFS - but it's not much documented.

Updating a date in Oracle SQL table

If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.

In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..

How to use ternary operator in razor (specifically on HTML attributes)?

Addendum:

The important concept is that you are evaluating an expression in your Razor code. The best way to do this (if, for example, you are in a foreach loop) is using a generic method.

The syntax for calling a generic method in Razor is:

@(expression)

In this case, the expression is:

User.Identity.IsAuthenticated ? "auth" : "anon"

Therefore, the solution is:

@(User.Identity.IsAuthenticated ? "auth" : "anon")

This code can be used anywhere in Razor, not just for an html attribute.

See @Kyralessa 's comment for C# Razor Syntax Quick Reference (Phil Haack's blog).

gpg: no valid OpenPGP data found

i got this problem "gpg-no-valid-openpgp-data-found" and solve it with the following first i open browser and paste https://pkg.jenkins.io/debian/jenkins-ci.org.key then i download the key in Downloads folder then cd /Downloads/ then sudo apt-key add jenkins-ci.org.key if Appear "OK" then you success to add the key :)

Get generic type of java.util.List

If those are actually fields of a certain class, then you can get them with a little help of reflection:

package test;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class Test {

    List<String> stringList = new ArrayList<String>();
    List<Integer> integerList = new ArrayList<Integer>();

    public static void main(String... args) throws Exception {
        Field stringListField = Test.class.getDeclaredField("stringList");
        ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
        Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
        System.out.println(stringListClass); // class java.lang.String.

        Field integerListField = Test.class.getDeclaredField("integerList");
        ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
        Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0];
        System.out.println(integerListClass); // class java.lang.Integer.
    }
}

You can also do that for parameter types and return type of methods.

But if they're inside the same scope of the class/method where you need to know about them, then there's no point of knowing them, because you already have declared them yourself.

Setting focus to a textbox control

Quite simple :

For the tab control, you need to handle the _SelectedIndexChanged event:

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
  Handles TabControl1.SelectedIndexChanged

If TabControl1.SelectedTab.Name = "TabPage1" Then
    TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
    TextBox4.Focus()
End If

add allow_url_fopen to my php.ini using .htaccess

allow_url_fopen is generally set to On. If it is not On, then you can try two things.

  1. Create an .htaccess file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.

    php_value allow_url_fopen On
    
  2. Create a php.ini file (for update server php5.ini) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:

    allow_url_fopen = On;
    

I have personally tested the above solutions; they worked for me.

sudo: docker-compose: command not found

I have same issue , i solved issue :

step-1 : download docker-compose using following command.

     1.  sudo su

     2. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

Step-2 : Run command

    chmod +x /usr/local/bin/docker-compose

Step-3 : Check docker-compose version

     docker-compose --version

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

If your application needs to react on request of type post, use this:

if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') { // if form submitted with post method
    // validate request, 
    // manage post request differently, 
    // log or don't log request,
    // redirect to avoid resubmition on F5 etc
}

If your application needs to react on any data received through post request, use this:

if(!empty($_POST)) {  // if received any post data
   // process $_POST values, 
   // save data to DB,
   // ... 
}

if(!empty($_FILES)) { // if received any "post" files
   // validate uploaded FILES
   // move to uploaded dir
   // ...
}

It is implementation specific, but you a going to use both, + $_FILES superglobal.

What's the default password of mariadb on fedora?

From https://mariadb.com/kb/en/mysql_secure_installation/ :

In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and you haven't set the root password yet, the password will be blank, so you should just press enter here.

the password will be blank

I think that's your answer.

npm not working - "read ECONNRESET"

This can be caused by installing anything with npm using sudo -- this causes the files in the cache to be owned by root, resulting in this problem. You can fix it by running:

sudo rm -rf ~/.npm

to remove the cache. Then try whatever you were doing again, making sure you never use sudo along with npm (or the problem may come back).

Lots more information: npm throws error without sudo

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Deserializing using JsonConvert.DeserializeObject() function

public class ApiValues
    {
        [JsonProperty("Address")]
        public string Address { get; set; }

        [JsonProperty("BaseUrl")]
        public string BaseUrl{ get; set; }
    }

var json = 
{ 
    "Address":"some-address",
    "BaseUrl":"some-url-value"
}


var values = JsonConvert.DeserializeObject<ApiValues>(json);

Entity Framework. Delete all rows in table

This works Properly in EF 5:

YourEntityModel myEntities = new YourEntityModel();

var objCtx = ((IObjectContextAdapter)myEntities).ObjectContext;
objCtx.ExecuteStoreCommand("TRUNCATE TABLE [TableName]");

numpy max vs amax vs maximum

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

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

I. For single array order statistics

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

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

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

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

II. For element-wise comparison of two arrays

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

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

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

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

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

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

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

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Image style height and width not taken in outlook mails

make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.

in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).

example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.

Retrieve only the queried element in an object array in MongoDB collection

Likewise you can find for the multiple

db.getCollection('localData').aggregate([
    // Get just the docs that contain a shapes element where color is 'red'
  {$match: {'shapes.color': {$in : ['red','yellow'] } }},
  {$project: {
     shapes: {$filter: {
        input: '$shapes',
        as: 'shape',
        cond: {$in: ['$$shape.color', ['red', 'yellow']]}
     }}
  }}
])

Jquery resizing image

So much code here, but I think this is the best answer

function resize() {
            var input = $("#picture");
            var maxWidth = 300;
            var maxHeight = 300;
            var width = input.width();
            var height = input.height();
            var ratioX = (maxWidth / width);
            var ratioY = (maxHeight / height);
            var ratio = Math.min(ratioX, ratioY);

            var newWidth  = (width * ratio);
            var newHeight = (height * ratio);
            input.css("width", newWidth);
            input.css("height", newHeight);
};

laravel Unable to prepare route ... for serialization. Uses Closure

This is definitely a bug.Laravel offers predefined code in routes/api.php

Route::middleware('auth:api')->get('/user', function (Request $request) { 
     return $request->user(); 
});

which is unabled to be processed by:

php artisan route:cache

This definitely should be fixed by Laravel team.(check the link),

simply if you want to fix it you should replace routes\api.php code with some thing like :

Route::middleware('auth:api')->get('/user', 'UserController@AuthRouteAPI');

and in UserController put this method:

 public function AuthRouteAPI(Request $request){
    return $request->user();
 }

vba error handling in loop

As a general way to handle error in a loop like your sample code, I would rather use:

on error resume next
for each...
    'do something that might raise an error, then
    if err.number <> 0 then
         ...
    end if
 next ....

Jquery get form field value

if you know the id of the inputs you only need to use this:

var value = $("#inputID").val();

Streaming via RTSP or RTP in HTML5

This is an old qustion, but I had to do it myself recently and I achieved something working so (besides response like mine would save me some time): Basically use ffmpeg to change the container to HLS, most of the IPCams stream h264 and some basic type of PCM, so use something like that:

ffmpeg -v info -i rtsp://ip:port/h264.sdp -c:v copy -c:a copy -bufsize 1835k -pix_fmt yuv420p -flags -global_header -hls_time 10 -hls_list_size 6 -hls_wrap 10 -start_number 1 /var/www/html/test.m3u8

Then use video.js with HLS plugin This will play Live stream nicely There is also a jsfiddle example under second link).

Note: although this is not a native support it doesn't require anything extra on user frontend.

Bind service to activity in Android

This is a biased answer, but I wrote a library that may simplify the usage of Android Services, if they run locally in the same process as the app: https://github.com/germnix/acacia

Basically you define an interface annotated with @Service and its implementing class, and the library creates and binds the service, handles the connection and the background worker thread:

@Service(ServiceImpl.class)
public interface MyService {
    void doProcessing(Foo aComplexParam);
}

public class ServiceImpl implements MyService {
    // your implementation
}

MyService service = Acacia.createService(context, MyService.class);
service.doProcessing(foo);

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    ...
    <service android:name="com.gmr.acacia.AcaciaService"/>
    ...
</application>

You can get an instance of the associated android.app.Service to hide/show persistent notifications, use your own android.app.Service and manually handle threading if you wish.

Convert string with commas to array

Regexp

As more powerful alternative to split, you can use match

"0,1".match(/\d+/g)

_x000D_
_x000D_
let a = "0,1".match(/\d+/g)

console.log(a);
_x000D_
_x000D_
_x000D_

How to use pagination on HTML tables?

It is a very simple and effective utility build in jquery to implement pagination on html table http://tablesorter.com/docs/example-pager.html

Download the plugin from http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js

After adding this plugin add following code in head script

$(document).ready(function() { 
    $("table") 
    .tablesorter({widthFixed: true, widgets: ['zebra']}) 
    .tablesorterPager({container: $("#pager")}); 
}); 

Java Array Sort descending?

There is a way that might be a little bit longer, but it works fine. This is a method to sort an int array descendingly.

Hope that this will help someone ,,, some day:

public static int[] sortArray (int[] array) {
    int [] sortedArray = new int[array.length];
    for (int i = 0; i < sortedArray.length; i++) {
        sortedArray[i] = array[i];
    }
    
    boolean flag = true;
    int temp;
    while (flag) {
        flag = false;
        for (int i = 0; i < sortedArray.length - 1; i++) {
            if(sortedArray[i] < sortedArray[i+1]) {
                temp = sortedArray[i];
                sortedArray[i] = sortedArray[i+1];
                sortedArray[i+1] = temp;
                flag = true;
            }
        }
    }
    
    return sortedArray;
    
}

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

Can we add div inside table above every <tr>?

You can't put a div directly inside a table but you can put div inside td or th element.

For that you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:

HTML:-

<tr>
  <td>
    <div>
      <p>I'm text in a div.</p>
    </div>
  </td>
</tr>

For more information :-

http://css-tricks.com/using-divs-inside-tables/

How to check if IsNumeric

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

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

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

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

How to get the groups of a user in Active Directory? (c#, asp.net)

GetAuthorizationGroups() does not find nested groups. To really get all groups a given user is a member of (including nested groups), try this:

using System.Security.Principal

private List<string> GetGroups(string userName)
{
    List<string> result = new List<string>();
    WindowsIdentity wi = new WindowsIdentity(userName);

    foreach (IdentityReference group in wi.Groups)
    {
        try
        {
            result.Add(group.Translate(typeof(NTAccount)).ToString());
        }
        catch (Exception ex) { }
    }
    result.Sort();
    return result;
}

I use try/catch because I had some exceptions with 2 out of 200 groups in a very large AD because some SIDs were no longer available. (The Translate() call does a SID -> Name conversion.)

Datetime current year and month in Python

You can always use a sub-string method:

import datetime;

today = str(datetime.date.today());
curr_year = int(today[:4]);
curr_month = int(today[5:7]);

This will get you the current month and year in integer format. If you want them to be strings you simply have to remove the " int " precedence while assigning values to the variables curr_year and curr_month.

Variable might not have been initialized error

You declared them, but not initialized.

int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization

How to set cursor position in EditText?

I believe the most simple way to do this is just use padding.

Say in your xml's edittext section, add android:paddingLeft="100dp" This will move your start position of cursor 100dp right from left end.

Same way, you can use android:paddingRight="100dp" This will move your end position of cursor 100dp left from right end.

For more detail, check this article on my blog: Android: Setting Cursor Starting and Ending Position in EditText Widget

JavaScript: how to change form action attribute value based on selection?

$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

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

If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars or hosts_vars.

For instance, with your example above, you can move your vars for group tests in the file group_vars/tests :

Inventory file :

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

group_vars/tests file :

data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

recyclerview No adapter attached; skipping layout

Just put code inside onCreate() method

/* Like This*/

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    layoutManager = new LinearLayoutManager(YourActivity.this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    mAdapter = new YourAdapter(YourModelClassObject);
    recyclerView.setAdapter(mAdapter);
}

builder for HashMap

Since Java 9 Map interface contains:

  • Map.of(k1,v1, k2,v2, ..)
  • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

Limitations of those factory methods are that they:

  • can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)
  • produce immutable maps

If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );

Reference an Element in a List of Tuples

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

i used hasAnyRole('ROLE_ADMIN','ROLE_USER') but i was getting bean creation below error

Error creating bean with name     'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] while setting bean property 'securityMetadataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Expected a single expression attribute for [/user/*]

then i tried

access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" and it's working fine for me.

as one of my user is admin as well as user.

for this you need to add use-expressions="true" auto-config="true" followed by http tag

<http use-expressions="true" auto-config="true" >.....</http>

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Create an empty data.frame

I keep this function handy for whenever I need it, and change the column names and classes to suit the use case:

make_df <- function() { data.frame(name=character(),
                     profile=character(),
                     sector=character(),
                     type=character(),
                     year_range=character(),
                     link=character(),
                     stringsAsFactors = F)
}

make_df()
[1] name       profile    sector     type       year_range link      
<0 rows> (or 0-length row.names)

How can I customize the tab-to-space conversion factor?

You want to make sure your editorconfig is not conflicting with your user or workspace settings configuration, as I just had a bit of annoyance thinking the settings files settings were not being applied when it was my editor configuration undoing those changes.

.attr('checked','checked') does not work

I don't think you can call

$.attr('checked',true);

because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces... please use LTRIM/RTRIM

 LTRIM(String)
 RTRIM(String)

The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.

SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers

Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi

How to do constructor chaining in C#

I hope following example shed some light on constructor chaining.
my use case here for example, you are expecting user to pass a directory to your constructor, user doesn't know what directory to pass and decides to let you assign default directory. you step up and assign a default directory that you think will work.

BTW, I used LINQPad for this example in case you are wondering what *.Dump() is.
cheers

void Main()
{

    CtorChaining ctorNoparam = new CtorChaining();
    ctorNoparam.Dump();
    //Result --> BaseDir C:\Program Files (x86)\Default\ 

    CtorChaining ctorOneparam = new CtorChaining("c:\\customDir");
    ctorOneparam.Dump();    
    //Result --> BaseDir c:\customDir 
}

public class CtorChaining
{
    public string BaseDir;
    public static string DefaultDir = @"C:\Program Files (x86)\Default\";


    public CtorChaining(): this(null) {}

    public CtorChaining(string baseDir): this(baseDir, DefaultDir){}

    public CtorChaining(string baseDir, string defaultDir)
    {
        //if baseDir == null, this.BaseDir = @"C:\Program Files (x86)\Default\"
        this.BaseDir = baseDir ?? defaultDir;
    }
}

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Apply function to each column in a data frame observing each columns existing data type

The reason that max works with apply is that apply is coercing your data frame to a matrix first, and a matrix can only hold one data type. So you end up with a matrix of characters. sapply is just a wrapper for lapply, so it is not surprising that both yield the same error.

The default behavior when you create a data frame is for categorical columns to be stored as factors. Unless you specify that it is an ordered factor, operations like max and min will be undefined, since R is assuming that you've created an unordered factor.

You can change this behavior by specifying options(stringsAsFactors = FALSE), which will change the default for the entire session, or you can pass stringsAsFactors = FALSE in the data.frame() construction call itself. Note that this just means that min and max will assume "alphabetical" ordering by default.

Or you can manually specify an ordering for each factor, although I doubt that's what you want to do.

Regardless, sapply will generally yield an atomic vector, which will entail converting everything to characters in many cases. One way around this is as follows:

#Some test data
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

d[4,] <- NA

#Similar function to DWin's answer          
fun <- function(x){
    if(is.numeric(x)){max(x,na.rm = 1)}
    else{max(as.character(x),na.rm=1)}
}   

#Use colwise from plyr package
colwise(fun)(d)
         v1 v2       v3 v4
1 0.8478983  j 1.999435  J

Merge two dataframes by index

Use merge, which is inner join by default:

pd.merge(df1, df2, left_index=True, right_index=True)

Or join, which is left join by default:

df1.join(df2)

Or concat, which is outer join by default:

pd.concat([df1, df2], axis=1)

Samples:

df1 = pd.DataFrame({'a':range(6),
                    'b':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df1)
   a  b
a  0  5
b  1  3
c  2  6
d  3  9
e  4  2
f  5  4

df2 = pd.DataFrame({'c':range(4),
                    'd':[10,20,30, 40]}, index=list('abhi'))

print (df2)
   c   d
a  0  10
b  1  20
h  2  30
i  3  40

#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

#default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:

find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'

Note that you can easily make it handle more file types (such as .jar) by adding them using -o, e.g.:

find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

How to limit google autocomplete results to City and Country only

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var options = {_x000D_
        types: ['geocode'] //this should work !_x000D_
      };_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

Get Character value from KeyCode in JavaScript... then trim

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode(). For values of keyCode <= 96 it seems to map using the function:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:

chrCode = keyCode

If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    let keyCode = e.keyCode;_x000D_
    let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
    let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
    console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_
_x000D_
_x000D_

Android appcompat v7:23

Ran into a similar issue using React Native

> Could not find com.android.support:appcompat-v7:23.0.1.

the Support Libraries are Local Maven repository for Support Libraries

enter image description here

ssh script returns 255 error

This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.

ssh returns 255 when an error occurred or 255 is returned by the remote script:

 EXIT STATUS

     ssh exits with the exit status of the remote command or
     with 255 if an error occurred.

Usually you would an error message something similar to:

ssh: connect to host host.domain.com port 22: No route to host

Or

ssh: connect to host HOSTNAME port 22: Connection refused

Check-list:

  • What happens if you run the ssh command directly from the command line?

  • Are you able to ping that machine?

  • Does the remote has ssh installed?

  • If installed, then is the ssh service running?

Assigning more than one class for one event

    $('[class*="tag"]').live('click', function() {
      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here
      }
   });

Convert Long into Integer

long visitors =1000;

int convVisitors =(int)visitors;

How to kill a while loop with a keystroke?

I modified the answer from rayzinnz to end the script with a specific key, in this case the escape key

import threading as th
import time
import keyboard

keep_going = True
def key_capture_thread():
    global keep_going
    a = keyboard.read_key()
    if a== "esc":
        keep_going = False


def do_stuff():
    th.Thread(target=key_capture_thread, args=(), name='key_capture_thread', daemon=True).start()
    i=0
    while keep_going:
        print('still going...')
        time.sleep(1)
        i=i+1
        print (i)
    print ("Schleife beendet")


do_stuff()

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

How do I conditionally apply CSS styles in AngularJS?

Another option when you need a simple css style of one or two properties:

View:

<tr ng-repeat="element in collection">
    [...amazing code...] 
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
        {{ element.myvar }}
    </td>
    [...more amazing code...]
</tr>

Controller:

$scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
        case 0: return 'red';
        case 1: return 'green';
        default: return 'yellow';
    }
};

Importing class/java files in Eclipse

create a new java project in Eclipse and copy .java files to its src directory, if you don't know where those source files should be placed, right click on the root of the project and choose new->class to create a test class and see where its .java file is placed, then put other files with it, in the same directory, you may have to adjust the package in those source files according to the new project directory structure.

if you use external libraries in your code, you have two options: either copy / download jar files or use maven if you use maven you'll have to create the project at maven project in the first place, creating java projects as maven projects are the way to go anyway but that's for another post...

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

Passing Variable through JavaScript from one html page to another page

Your best option here, is to use the Query String to 'send' the value.

how to get query string value using javascript

  • So page 1 redirects to page2.html?someValue=ABC
  • Page 2 can then read the query string and specifically the key 'someValue'

If this is anything more than a learning exercise you may want to consider the security implications of this though.

Global variables wont help you here as once the page is re-loaded they are destroyed.

How to Find the Default Charset/Encoding in Java?

Is this a bug or feature?

Looks like undefined behaviour. I know that, in practice, you can change the default encoding using a command-line property, but I don't think what happens when you do this is defined.

Bug ID: 4153515 on problems setting this property:

This is not a bug. The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

The preferred way to change the default encoding used by the VM and the runtime system is to change the locale of the underlying platform before starting your Java program.

I cringe when I see people setting the encoding on the command line - you don't know what code that is going to affect.

If you do not want to use the default encoding, set the encoding you do want explicitly via the appropriate method/constructor.

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

How to view the assembly behind the code using Visual C++?

For MSVC you can use the linker.

link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll

foo.pdb needs to be available to get symbols

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

In general I would recommend against calling the event handlers 'manually'.

  • It's unclear what gets executed because of multiple registered listeners
  • Danger to get into a recursive and infinite event-loop (click A triggering Click B, triggering click A, etc.)
  • Redundant updates to the DOM
  • Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).

Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.

Character reading from file in Python

Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:

text = text.replace (u"\u2018", "'")

In addition, what are you using to write the file? f1.read() should return a string that looks like this:

'I don\xe2\x80\x98t like this'

If it's returning this string, the file is being written incorrectly:

'I don\u2018t like this'

Rename multiple files in a directory in Python

Here is a more general solution:

This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character.

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

Try setting "Integrated Security=False" in the connection string.

<add name="YourContext" connectionString="Data Source=<IPAddressOfDBServer>;Initial Catalog=<DBName>;USER ID=<youruserid>;Password=<yourpassword>;Integrated Security=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

Simple Pivot Table to Count Unique Values

If you have the data sorted.. i suggest using the following formula

=IF(OR(A2<>A3,B2<>B3),1,0)

This is faster as it uses less cells to calculate.

TS1086: An accessor cannot be declared in ambient context

Setting "skipLibCheck": true in tsconfig.json solved my problem

"compilerOptions": {
    "skipLibCheck": true
}

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

This is an edge case, but you can also get this error if you are building an MFC application with CMake.

In that case, you need to add the following definitions:

ADD_DEFINITIONS(-D_AFXDLL) SET(CMAKE_MFC_FLAG 2) # or 1 if you are looking for the static library

If you are compiling with unicode, the following properties also need to be added:

set_target_properties(MyApp PROPERTIES COMPILE_DEFINITIONS _AFXDLL,_UNICODE,UNICODE,_BIND_TO_CURRENT_CRT_VERSION,_BIND_TO_CURRENT_MFC_VERSION LINK_FLAGS "/ENTRY:\"wWinMainCRTStartup\"" )

Soure: FAQ: How to use MFC with CMake

How to force composer to reinstall a library?

Reinstall the dependencies. Remove the vendor folder (manually) or via rm command (if you are in the project folder, sure) on Linux before:

rm -rf vendor/

composer update -v

https://www.dev-metal.com/composer-problems-try-full-reset/

How to find the date of a day of the week from a date using PHP?

I think this is what you want.

$dayofweek = date('w', strtotime($date));
$result    = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));

How to close a Java Swing application from the code

Try:

System.exit(0);

Crude, but effective.

Turn off iPhone/Safari input element rounding

input -webkit-appearance: none; alone does not work.

Try adding -webkit-border-radius:0px; in addition.

Google Maps API 3 - Custom marker color for default (dot) marker

As others have mentioned, vokimon's answer is great but unfortunately Google Maps is a bit slow when there are many SymbolPath/SVG-based markers at once.

It looks like using a Data URI is much faster, approximately on par with PNGs.

Also, since it's a full SVG document, it's possible to use a proper filled circle for the dot. The path is modified so it is no longer offset to the top-left, so the anchor needs to be defined.

Here's a modified version that generates these markers:

var coloredMarkerDef = {
    svg: [
        '<svg viewBox="0 0 22 41" width="22px" height="41px" xmlns="http://www.w3.org/2000/svg">',
            '<path d="M 11,41 c -2,-20 -10,-22 -10,-30 a 10,10 0 1 1 20,0 c 0,8 -8,10 -10,30 z" fill="{fillColor}" stroke="#ffffff" stroke-width="1.5"/>',
            '<circle cx="11" cy="11" r="3"/>',
        '</svg>'
    ].join(''),
    anchor: {x: 11, y: 41},
    size: {width: 22, height: 41}
};

var getColoredMarkerSvg = function(color) {
    return coloredMarkerDef.svg.replace('{fillColor}', color);
};

var getColoredMarkerUri = function(color) {
    return 'data:image/svg+xml,' + encodeURIComponent(getColoredMarkerSvg(color));
};

var getColoredMarkerIcon = function(color) {
    return {
        url: getColoredMarkerUri(color),
        anchor: coloredMarkerDef.anchor,
        size: coloredMarkerDef.size,
        scaledSize: coloredMarkerDef.size
    }
};

Usage:

var marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(latitude, longitude),
    icon: getColoredMarkerIcon("#FFF")
});

The downside, much like a PNG image, is the whole rectangle is clickable. In theory it's not too difficult to trace the SVG path and generate a MarkerShape polygon.

How to print a groupby object

If you're simply looking for a way to display it, you could use describe():

grp = df.groupby['colName']
grp.describe()

This gives you a neat table.

Generate a random double in a range

This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:

double random = ThreadLocalRandom.current().nextDouble(min, max);

nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int, and can be double.

How to compare two Carbon Timestamps?

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

In SQL Server, how to create while loop in select

You Could do something like this .....
Your Table

CREATE TABLE TestTable 
(
ID INT,
Data NVARCHAR(50)
)
GO

INSERT INTO TestTable
VALUES (1,'AABBCC'),
       (2,'FFDD'),
       (3,'TTHHJJKKLL')
GO

SELECT * FROM TestTable

My Suggestion

CREATE TABLE #DestinationTable
(
ID INT,
Data NVARCHAR(50)
)
GO  
    SELECT * INTO #Temp FROM TestTable

    DECLARE @String NVARCHAR(2)
    DECLARE @Data NVARCHAR(50)
    DECLARE @ID INT

    WHILE EXISTS (SELECT * FROM #Temp)
     BEGIN 
        SELECT TOP 1 @Data =  DATA, @ID = ID FROM  #Temp

          WHILE LEN(@Data) > 0
            BEGIN
                SET @String = LEFT(@Data, 2)

                INSERT INTO #DestinationTable (ID, Data)
                VALUES (@ID, @String)

                SET @Data = RIGHT(@Data, LEN(@Data) -2)
            END
        DELETE FROM #Temp WHERE ID = @ID
     END


SELECT * FROM #DestinationTable

Result Set

ID  Data
1   AA
1   BB
1   CC
2   FF
2   DD
3   TT
3   HH
3   JJ
3   KK
3   LL

DROP Temp Tables

DROP TABLE #Temp
DROP TABLE #DestinationTable

What's the difference between process.cwd() vs __dirname?

$ find proj

proj
proj/src
proj/src/index.js

$ cat proj/src/index.js

console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);

$ cd proj; node src/index.js

process.cwd() = /tmp/proj
__dirname = /tmp/proj/src

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs.110).aspx

How to count instances of character in SQL Column

Try this:

SELECT COUNT(DECODE(SUBSTR(UPPER(:main_string),rownum,LENGTH(:search_char)),UPPER(:search_char),1)) search_char_count
FROM DUAL
connect by rownum <= length(:main_string);

It determines the number of single character occurrences as well as the sub-string occurrences in main string.

How do you log content of a JSON object in Node.js?

function prettyJSON(obj) {
    console.log(JSON.stringify(obj, null, 2));
}

// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level

JSON.stringify on MDN

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

How to Create a real one-to-one relationship in SQL Server

There is one way I know how to achieve a strictly* one-to-one relationship without using triggers, computed columns, additional tables, or other 'exotic' tricks (only foreign keys and unique constraints), with one small caveat.

I will borrow the chicken-and-the-egg concept from the accepted answer to help me explain the caveat.

It is a fact that either a chicken or an egg must come first (in current DBs anyway). Luckily this solution does not get political and does not prescribe which has to come first - it leaves it up to the implementer.

The caveat is that the table which allows a record to 'come first' technically can have a record created without the corresponding record in the other table; however, in this solution, only one such record is allowed. When only one record is created (only chicken or egg), no more records can be added to any of the two tables until either the 'lonely' record is deleted or a matching record is created in the other table.

Solution:

Add foreign keys to each table, referencing the other, add unique constraints to each foreign key, and make one foreign key nullable, the other not nullable and also a primary key. For this to work, the unique constrain on the nullable column must only allow one null (this is the case in SQL Server, not sure about other databases).

CREATE TABLE dbo.Egg (
    ID int identity(1,1) not null,
    Chicken int null,
    CONSTRAINT [PK_Egg] PRIMARY KEY CLUSTERED ([ID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE dbo.Chicken (
    Egg int not null,
    CONSTRAINT [PK_Chicken] PRIMARY KEY CLUSTERED ([Egg] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE dbo.Egg  WITH NOCHECK ADD  CONSTRAINT [FK_Egg_Chicken] FOREIGN KEY([Chicken]) REFERENCES [dbo].[Chicken] ([Egg])
GO
ALTER TABLE dbo.Chicken  WITH NOCHECK ADD  CONSTRAINT [FK_Chicken_Egg] FOREIGN KEY([Egg]) REFERENCES [dbo].[Egg] ([ID])
GO
ALTER TABLE dbo.Egg WITH NOCHECK ADD CONSTRAINT [UQ_Egg_Chicken] UNIQUE([Chicken])
GO
ALTER TABLE dbo.Chicken WITH NOCHECK ADD CONSTRAINT [UQ_Chicken_Egg] UNIQUE([Egg])
GO

To insert, first an egg must be inserted (with null for Chicken). Now, only a chicken can be inserted and it must reference the 'unclaimed' egg. Finally, the added egg can be updated and it must reference the 'unclaimed' chicken. At no point can two chickens be made to reference the same egg or vice-versa.

To delete, the same logic can be followed: update egg's Chicken to null, delete the newly 'unclaimed' chicken, delete the egg.

This solution also allows swapping easily. Interestingly, swapping might be the strongest argument for using such a solution, because it has a potential practical use. Normally, in most cases, a one-to-one relationship of two tables is better implemented by simply refactoring the two tables into one; however, in a potential scenario, the two tables may represent truly distinct entities, which require a strict one-to-one relationship, but need to frequently swap 'partners' or be re-arranged in general, while still maintaining the one-to-one relationship after re-arrangement. If the more common solution were used, all data columns of one of the entities would have to be updated/overwritten for all pairs being re-arranged, as opposed to this solution, where only one column of foreign keys need to be re-arranged (the nullable foreign key column).

Well, this is the best I could do using standard constraints (don't judge :) Maybe someone will find it useful.

Are lists thread-safe?

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

Open application after clicking on Notification

Use below code for create notification for open activity. It works for me. For full code

 Intent myIntent = new Intent(context, DoSomething.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(
        context, 
        0, 
        myIntent, 
        Intent.FLAG_ACTIVITY_NEW_TASK);

 myNotification = new NotificationCompat.Builder(context)
   .setContentTitle("Exercise of Notification!")
   .setContentText("Do Something...")
   .setTicker("Notification!")
   .setWhen(System.currentTimeMillis())
   .setContentIntent(pendingIntent)
   .setDefaults(Notification.DEFAULT_SOUND)
   .setAutoCancel(true)
   .setSmallIcon(R.drawable.ic_launcher)
   .build();

 notificationManager = 
   (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
 notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

Add all files to a commit except a single file?

I use git add --patch quite a bit and wanted something like this to avoid having to hit d all the time through the same files. I whipped up a very hacky couple of git aliases to get the job done:

[alias]
    HELPER-CHANGED-FILTERED = "!f() { git status --porcelain | cut -c4- | ( [[ \"$1\" ]] && egrep -v \"$1\" || cat ); }; f"
    ap                      = "!git add --patch -- $(git HELPER-CHANGED-FILTERED 'min.(js|css)$' || echo 'THIS_FILE_PROBABLY_DOESNT_EXIST' )"

In my case I just wanted to ignore certain minified files all the time, but you could make it use an environment variable like $GIT_EXCLUDE_PATTERN for a more general use case.

How to initialize a vector with fixed length in R

?vector

X <- vector(mode="character", length=10)

This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

Converting RGB to grayscale/intensity

These values vary from person to person, especially for people who are colorblind.

XAMPP Object not found error

Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php

passing 2 $index values within nested ng-repeat

Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!

Right way

  <table>
    <tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
        <td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">

          <b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
          <small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>

        </td>
    </tr>
  </table>

Check: plnkr.co/52oIhLfeXXI9ZAynTuAJ

Read line by line in bash script

What you have is piping the text "cat test" into the loop.

You just want:

cat test | \
while read CMD; do
    echo $CMD
done

How to properly add include directories with CMake

Two things must be done.

First add the directory to be included:

target_include_directories(test PRIVATE ${YOUR_DIRECTORY})

In case you are stuck with a very old CMake version (2.8.10 or older) without support for target_include_directories, you can also use the legacy include_directories instead:

include_directories(${YOUR_DIRECTORY})

Then you also must add the header files to the list of your source files for the current target, for instance:

set(SOURCES file.cpp file2.cpp ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_executable(test ${SOURCES})

This way, the header files will appear as dependencies in the Makefile, and also for example in the generated Visual Studio project, if you generate one.

How to use those header files for several targets:

set(HEADER_FILES ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)

add_library(mylib libsrc.cpp ${HEADER_FILES})
target_include_directories(mylib PRIVATE ${YOUR_DIRECTORY})
add_executable(myexec execfile.cpp ${HEADER_FILES})
target_include_directories(myexec PRIVATE ${YOUR_DIRECTORY})

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

Angular 8 HttpClient Service example with Error Handling and Custom Header

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Student } from '../model/student';
    import { Observable, throwError } from 'rxjs';
    import { retry, catchError } from 'rxjs/operators';

    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {

      // API path
      base_path = 'http://localhost:3000/students';

      constructor(private http: HttpClient) { }

      // Http Options
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }

      // Handle API errors
      handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(
            `Backend returned code ${error.status}, ` +
            `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError(
          'Something bad happened; please try again later.');
      };


      // Create a new item
      createItem(item): Observable<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

      ....
      ....

enter image description here

Check complete example tutorial here

Adding multiple class using ng-class

Yes you can have multiple expression to add multiple class in ng-class.

For example:

<div ng-class="{class1:Result.length==2,class2:Result.length==3}"> Dummy Data </div>

Sqlite convert string to date

This is for fecha(TEXT) format date YYYY-MM-dd HH:mm:ss for instance I want all the records of Ene-05-2014 (2014-01-05):

SELECT 
 fecha 
FROM 
 Mytable 
WHERE 
 DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN 
 DATE(20140105) 
AND 
 DATE(20140105);

Open new popup window without address bars in firefox & IE

Workaround - Open a modal popup window and embed the external URL as an iframe.

Remove tracking branches no longer on remote

I am not sure for how long, but I do use git-up now, which takes care of that.

I do git up and it starts to track new branches and deletes the old ones.

Just to make it clear, it is not out-of-box git command — https://github.com/aanand/git-up

BTW it also stashes dirty tree and makes rebases still with just git up.

Hope it'll be useful for someone

Custom Listview Adapter with filter Android

You can use the Filterable interface on your Adapter, have a look at the example below:

public class SearchableAdapter extends BaseAdapter implements Filterable {
    
    private List<String>originalData = null;
    private List<String>filteredData = null;
    private LayoutInflater mInflater;
    private ItemFilter mFilter = new ItemFilter();
    
    public SearchableAdapter(Context context, List<String> data) {
        this.filteredData = data ;
        this.originalData = data ;
        mInflater = LayoutInflater.from(context);
    }
 
    public int getCount() {
        return filteredData.size();
    }
 
    public Object getItem(int position) {
        return filteredData.get(position);
    }
 
    public long getItemId(int position) {
        return position;
    }
 
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unnecessary calls
        // to findViewById() on each row.
        ViewHolder holder;
 
        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
 
            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.list_view);
 
            // Bind the data efficiently with the holder.
 
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
 
        // If weren't re-ordering this you could rely on what you set last time
        holder.text.setText(filteredData.get(position));
 
        return convertView;
    }
    
    static class ViewHolder {
        TextView text;
    }
 
    public Filter getFilter() {
        return mFilter;
    }
 
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            
            String filterString = constraint.toString().toLowerCase();
            
            FilterResults results = new FilterResults();
            
            final List<String> list = originalData;
 
            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);
 
            String filterableString ;
            
            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }
            
            results.values = nlist;
            results.count = nlist.size();
 
            return results;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }
 
    }
}

In your Activity or Fragment where of Adapter is instantiated :

editTxt.addTextChangedListener(new TextWatcher() {
  
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        System.out.println("Text ["+s+"]");
        
        mSearchableAdapter.getFilter().filter(s.toString());                           
    }
     
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
         
    }
     
    @Override
    public void afterTextChanged(Editable s) {
    }
});

Here are the links for the original source and another example

Convert Unix timestamp to a date string

date -d @1278999698 +'%Y-%m-%d %H:%M:%S' Where the number behind @ is the number in seconds

Why does the Google Play store say my Android app is incompatible with my own device?

I also had the same problem. I published an App in Test mode created with React Native 59. it wasn't compatible for certain tester. The message wasn't clear about why the app is not compatible , after i figured out that i restricted the app to be available only for certain country . that was the problem, but as i said the message wasn't clear. in Play Store WebApp the message is: "this app is not compatible with your device". in the mobile app the message "This app is not available in your country"

When should I use nil and NULL in Objective-C?

Basically: nil: null pointer on an object and null: is for other type pointer

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

How to convert a String to JsonObject using gson library

JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");

Creating temporary files in bash

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)

In Java, what is the best way to determine the size of an object?

You should use jol, a tool developed as part of the OpenJDK project.

JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc.

To get the sizes of primitives, references and array elements, use VMSupport.vmDetails(). On Oracle JDK 1.8.0_40 running on 64-bit Windows (used for all following examples), this method returns

Running 64-bit HotSpot VM.
Using compressed oop with 0-bit shift.
Using compressed klass with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

You can get the shallow size of an object instance using ClassLayout.parseClass(Foo.class).toPrintable() (optionally passing an instance to toPrintable). This is only the space consumed by a single instance of that class; it does not include any other objects referenced by that class. It does include VM overhead for the object header, field alignment and padding. For java.util.regex.Pattern:

java.util.regex.Pattern object internals:
 OFFSET  SIZE        TYPE DESCRIPTION                    VALUE
      0     4             (object header)                01 00 00 00 (0000 0001 0000 0000 0000 0000 0000 0000)
      4     4             (object header)                00 00 00 00 (0000 0000 0000 0000 0000 0000 0000 0000)
      8     4             (object header)                cb cf 00 20 (1100 1011 1100 1111 0000 0000 0010 0000)
     12     4         int Pattern.flags                  0
     16     4         int Pattern.capturingGroupCount    1
     20     4         int Pattern.localCount             0
     24     4         int Pattern.cursor                 48
     28     4         int Pattern.patternLength          0
     32     1     boolean Pattern.compiled               true
     33     1     boolean Pattern.hasSupplementary       false
     34     2             (alignment/padding gap)        N/A
     36     4      String Pattern.pattern                (object)
     40     4      String Pattern.normalizedPattern      (object)
     44     4        Node Pattern.root                   (object)
     48     4        Node Pattern.matchRoot              (object)
     52     4       int[] Pattern.buffer                 null
     56     4         Map Pattern.namedGroups            null
     60     4 GroupHead[] Pattern.groupNodes             null
     64     4       int[] Pattern.temp                   null
     68     4             (loss due to the next object alignment)
Instance size: 72 bytes (reported by Instrumentation API)
Space losses: 2 bytes internal + 4 bytes external = 6 bytes total

You can get a summary view of the deep size of an object instance using GraphLayout.parseInstance(obj).toFootprint(). Of course, some objects in the footprint might be shared (also referenced from other objects), so it is an overapproximation of the space that could be reclaimed when that object is garbage collected. For the result of Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$") (taken from this answer), jol reports a total footprint of 1840 bytes, of which only 72 are the Pattern instance itself.

java.util.regex.Pattern instance footprint:
     COUNT       AVG       SUM   DESCRIPTION
         1       112       112   [C
         3       272       816   [Z
         1        24        24   java.lang.String
         1        72        72   java.util.regex.Pattern
         9        24       216   java.util.regex.Pattern$1
        13        24       312   java.util.regex.Pattern$5
         1        16        16   java.util.regex.Pattern$Begin
         3        24        72   java.util.regex.Pattern$BitClass
         3        32        96   java.util.regex.Pattern$Curly
         1        24        24   java.util.regex.Pattern$Dollar
         1        16        16   java.util.regex.Pattern$LastNode
         1        16        16   java.util.regex.Pattern$Node
         2        24        48   java.util.regex.Pattern$Single
        40                1840   (total)

If you instead use GraphLayout.parseInstance(obj).toPrintable(), jol will tell you the address, size, type, value and path of field dereferences to each referenced object, though that's usually too much detail to be useful. For the ongoing pattern example, you might get the following. (Addresses will likely change between runs.)

java.util.regex.Pattern object externals:
          ADDRESS       SIZE TYPE                             PATH                           VALUE
         d5e5f290         16 java.util.regex.Pattern$Node     .root.next.atom.next           (object)
         d5e5f2a0        120 (something else)                 (somewhere else)               (something else)
         d5e5f318         16 java.util.regex.Pattern$LastNode .root.next.next.next.next.next.next.next (object)
         d5e5f328      21664 (something else)                 (somewhere else)               (something else)
         d5e647c8         24 java.lang.String                 .pattern                       (object)
         d5e647e0        112 [C                               .pattern.value                 [^, [, a, -, z, A, -, Z, 0, -, 9, _, ., +, -, ], +, @, [, a, -, z, A, -, Z, 0, -, 9, -, ], +, \, ., [, a, -, z, A, -, Z, 0, -, 9, -, ., ], +, $]
         d5e64850        448 (something else)                 (somewhere else)               (something else)
         d5e64a10         72 java.util.regex.Pattern                                         (object)
         d5e64a58        416 (something else)                 (somewhere else)               (something else)
         d5e64bf8         16 java.util.regex.Pattern$Begin    .root                          (object)
         d5e64c08         24 java.util.regex.Pattern$BitClass .root.next.atom.val$rhs        (object)
         d5e64c20        272 [Z                               .root.next.atom.val$rhs.bits   [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
         d5e64d30         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)
         d5e64d48         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)
         d5e64d60         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)
         d5e64d78         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)
         d5e64d90         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)
         d5e64da8         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs (object)
         d5e64dc0         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs (object)
         d5e64dd8         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs        (object)
         d5e64df0         24 java.util.regex.Pattern$5        .root.next.atom                (object)
         d5e64e08         32 java.util.regex.Pattern$Curly    .root.next                     (object)
         d5e64e28         24 java.util.regex.Pattern$Single   .root.next.next                (object)
         d5e64e40         24 java.util.regex.Pattern$BitClass .root.next.next.next.atom.val$rhs (object)
         d5e64e58        272 [Z                               .root.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
         d5e64f68         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)
         d5e64f80         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)
         d5e64f98         24 java.util.regex.Pattern$5        .root.next.next.next.atom.val$lhs.val$lhs (object)
         d5e64fb0         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$rhs (object)
         d5e64fc8         24 java.util.regex.Pattern$5        .root.next.next.next.atom.val$lhs (object)
         d5e64fe0         24 java.util.regex.Pattern$5        .root.next.next.next.atom      (object)
         d5e64ff8         32 java.util.regex.Pattern$Curly    .root.next.next.next           (object)
         d5e65018         24 java.util.regex.Pattern$Single   .root.next.next.next.next      (object)
         d5e65030         24 java.util.regex.Pattern$BitClass .root.next.next.next.next.next.atom.val$rhs (object)
         d5e65048        272 [Z                               .root.next.next.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
         d5e65158         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)
         d5e65170         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$rhs (object)
         d5e65188         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)
         d5e651a0         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)
         d5e651b8         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs.val$lhs (object)
         d5e651d0         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs (object)
         d5e651e8         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom (object)
         d5e65200         32 java.util.regex.Pattern$Curly    .root.next.next.next.next.next (object)
         d5e65220        120 (something else)                 (somewhere else)               (something else)
         d5e65298         24 java.util.regex.Pattern$Dollar   .root.next.next.next.next.next.next (object)

The "(something else)" entries describe other objects in the heap that are not part of this object graph.

The best jol documentation is the jol samples in the jol repository. The samples demonstrate common jol operations and show how you can use jol to analyze VM and garbage collector internals.

How to Programmatically Add Views to Views

for anyone yet interested:

the best way I found is to use the inflate static method of View.

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

where yourViewXML is something like R.layout.myView

please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

Extract Month and Year From Date in R

Use substring?

d = "2004-02-06"
substr(d,0,7)
>"2004-02"

What is the difference between square brackets and parentheses in a regex?

Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.

/^(7|8|9)\d{9}$/

What this does:

  • ^ and $ denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
  • () denotes a capturing group.
  • 7|8|9 denotes matching either of 7, 8, or 9. It does this with alternations, which is what the pipe operator | does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat

alternations

Pattern: [rf]at
Match string: carat

class

  • \d{9} matches nine digits. \d is a shorthanded metacharacter, which matches any digits.
/^[7|8|9][\d]{9}$/

Look at what it does:

  • ^ and $ denotes anchored matches as well.
  • [7|8|9] is a character class. Any characters from the list 7, |, 8, |, or 9 can be matched, thus the | was added in incorrectly. This matches without backtracking.
  • [\d] is a character class that inhabits the metacharacter \d. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
  • {9} indicates the previous single construct is repeated nine times in total.

The optimal regex is /^[789]\d{9}$/, because /^(7|8|9)\d{9}$/ captures unnecessarily which imposes a performance decrease on most regex implementations ( happens to be one, considering the question uses keyword var in code, this probably is JavaScript). The use of which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes [] instead of alternations | gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.

Darken background image on hover

How about this, using an overlay?

.image:hover > .overlay {
    width:100%;
    height:100%;
    position:absolute;
    background-color:#000;
    opacity:0.5;
    border-radius:30px;
}

Demo

Remove object from a list of objects in python

You can remove a string from an array like this:

array = ["Bob", "Same"]
array.remove("Bob")

pip cannot install anything

pip has mirror support

pip --use-mirrors install yolk

As of version 1.5, this option will be removed:

1.5 (unreleased)

BACKWARD INCOMPATIBLE pip no longer supports the --use-mirrors, -M, and --mirrors flags. The mirroring support has been removed. In order to use a mirror specify it as the primary index with -i or --index-url, or as an additional index with --extra-index-url. (Pull #1098, CVE-2013-5123)

BACKWARD INCOMPATIBLE pip no longer will scrape insecure external urls by default nor will it install externally hosted files by default. Users may opt into installing externally hosted or insecure files or urls using --allow-external PROJECT and --allow-insecure PROJECT. (Pull #1055)

Added colors to the logging output in order to draw attention to important warnings and errors. (Pull #1109)

Added warnings when using an insecure index, find-link, or dependency link. (Pull #1121)

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

WCF Service Returning "Method Not Allowed"

The basic intrinsic types (e.g. byte, int, string, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.

So, a silly question (but I have to ask it...): is UploadedFile marked as a [DataContract]? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].

Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)

A tremendous resource for WCF development is what we know in our shop as "the fish book": Programming WCF Services by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.

Looping from 1 to infinity in Python

Using itertools.count:

import itertools
for i in itertools.count(start=1):
    if there_is_a_reason_to_break(i):
        break

In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
    if there_is_a_reason_to_break(i):
        break

So it's probably best to use count().

Linux command line howto accept pairing for bluetooth device without pin

~ $ hciconfig noauth

It worked for me in "Linux mx 4.19"

The exact steps are:

1) open a terminal - run: "hciconfig noauth"
2) use the blueman-manager gui to pair the device (in my case it was a keyboard)
3) from the blueman-manager choose "connect to HID"

step(3) is normally asking for a password - the "hciconfig noauth" makes step(3) passwordless