Programs & Examples On #Language lawyer

For questions about the intricacies of formal or authoritative specifications of programming languages and environments.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

Is null reference possible?

The answer depends on your view point:


If you judge by the C++ standard, you cannot get a null reference because you get undefined behavior first. After that first incidence of undefined behavior, the standard allows anything to happen. So, if you write *(int*)0, you already have undefined behavior as you are, from a language standard point of view, dereferencing a null pointer. The rest of the program is irrelevant, once this expression is executed, you are out of the game.


However, in practice, null references can easily be created from null pointers, and you won't notice until you actually try to access the value behind the null reference. Your example may be a bit too simple, as any good optimizing compiler will see the undefined behavior, and simply optimize away anything that depends on it (the null reference won't even be created, it will be optimized away).

Yet, that optimizing away depends on the compiler to prove the undefined behavior, which may not be possible to do. Consider this simple function inside a file converter.cpp:

int& toReference(int* pointer) {
    return *pointer;
}

When the compiler sees this function, it does not know whether the pointer is a null pointer or not. So it just generates code that turns any pointer into the corresponding reference. (Btw: This is a noop since pointers and references are the exact same beast in assembler.) Now, if you have another file user.cpp with the code

#include "converter.h"

void foo() {
    int& nullRef = toReference(nullptr);
    cout << nullRef;    //crash happens here
}

the compiler does not know that toReference() will dereference the passed pointer, and assume that it returns a valid reference, which will happen to be a null reference in practice. The call succeeds, but when you try to use the reference, the program crashes. Hopefully. The standard allows for anything to happen, including the appearance of pink elephants.

You may ask why this is relevant, after all, the undefined behavior was already triggered inside toReference(). The answer is debugging: Null references may propagate and proliferate just as null pointers do. If you are not aware that null references can exist, and learn to avoid creating them, you may spend quite some time trying to figure out why your member function seems to crash when it's just trying to read a plain old int member (answer: the instance in the call of the member was a null reference, so this is a null pointer, and your member is computed to be located as address 8).


So how about checking for null references? You gave the line

if( & nullReference == 0 ) // null reference

in your question. Well, that won't work: According to the standard, you have undefined behavior if you dereference a null pointer, and you cannot create a null reference without dereferencing a null pointer, so null references exist only inside the realm of undefined behavior. Since your compiler may assume that you are not triggering undefined behavior, it can assume that there is no such thing as a null reference (even though it will readily emit code that generates null references!). As such, it sees the if() condition, concludes that it cannot be true, and just throw away the entire if() statement. With the introduction of link time optimizations, it has become plain impossible to check for null references in a robust way.


TL;DR:

Null references are somewhat of a ghastly existence:

Their existence seems impossible (= by the standard),
but they exist (= by the generated machine code),
but you cannot see them if they exist (= your attempts will be optimized away),
but they may kill you unaware anyway (= your program crashes at weird points, or worse).
Your only hope is that they don't exist (= write your program to not create them).

I do hope that will not come to haunt you!

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Methods for Aligning Flex Items along the Main Axis

As stated in the question:

To align flex items along the main axis there is one property: justify-content

To align flex items along the cross axis there are three properties: align-content, align-items and align-self.

The question then asks:

Why are there no justify-items and justify-self properties?

One answer may be: Because they're not necessary.

The flexbox specification provides two methods for aligning flex items along the main axis:

  1. The justify-content keyword property, and
  2. auto margins

justify-content

The justify-content property aligns flex items along the main axis of the flex container.

It is applied to the flex container but only affects flex items.

There are five alignment options:

  • flex-start ~ Flex items are packed toward the start of the line.

    enter image description here

  • flex-end ~ Flex items are packed toward the end of the line.

    enter image description here

  • center ~ Flex items are packed toward the center of the line.

    enter image description here

  • space-between ~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction and writing mode (ltr or rtl).

    enter image description here

  • space-around ~ Same as space-between except with half-size spaces on both ends.

    enter image description here


Auto Margins

With auto margins, flex items can be centered, spaced away or packed into sub-groups.

Unlike justify-content, which is applied to the flex container, auto margins go on flex items.

They work by consuming all free space in the specified direction.


Align group of flex items to the right, but first item to the left

Scenario from the question:

  • making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)

    Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.

enter image description here

enter image description here


Other useful scenarios:

enter image description here

enter image description here

enter image description here


Place a flex item in the corner

Scenario from the question:

  • placing a flex item in a corner .box { align-self: flex-end; justify-self: flex-end; }

enter image description here


Center a flex item vertically and horizontally

enter image description here

margin: auto is an alternative to justify-content: center and align-items: center.

Instead of this code on the flex container:

.container {
    justify-content: center;
    align-items: center;
}

You can use this on the flex item:

.box56 {
    margin: auto;
}

This alternative is useful when centering a flex item that overflows the container.


Center a flex item, and center a second flex item between the first and the edge

A flex container aligns flex items by distributing free space.

Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.

In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).

enter image description here

enter image description here

Of course, this method is nothing great in terms of semantics.

Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items

NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.


Center a flex item when adjacent items vary in size

Scenario from the question:

  • in a row of three flex items, affix the middle item to the center of the container (justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).

    Note that values space-around and space-between on justify-content property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).

As noted, unless all flex items are of equal width or height (depending on flex-direction), the middle item cannot be truly centered. This problem makes a strong case for a justify-self property (designed to handle the task, of course).

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
  height: 50px;_x000D_
  width: 75px;_x000D_
  background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
  width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
  width: 200px;_x000D_
}_x000D_
#center {_x000D_
  text-align: center;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
  background-color: aqua;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
  <span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
  <div class="box box1"></div>_x000D_
  <div class="box box2"></div>_x000D_
  <div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
_x000D_
_x000D_

Here are two methods for solving this problem:

Solution #1: Absolute Positioning

The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.

Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.

In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center and absolutely position the outer items.

enter image description here

Solution #2: Nested Flex Containers (no absolute positioning)

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.box {_x000D_
  flex: 1;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto;  }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
  align-items: center;_x000D_
  border: 1px solid #ccc;_x000D_
  background-color: lightgreen;_x000D_
  height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box box71"><span>71 short</span></div>_x000D_
  <div class="box box72"><span>72 centered</span></div>_x000D_
  <div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's how it works:

  • The top-level div (.container) is a flex container.
  • Each child div (.box) is now a flex item.
  • Each .box item is given flex: 1 in order to distribute container space equally.
  • Now the items are consuming all space in the row and are equal width.
  • Make each item a (nested) flex container and add justify-content: center.
  • Now each span element is a centered flex item.
  • Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.


justify-content: space-same (concept)

Going back to justify-content for a minute, here's an idea for one more option.

  • space-same ~ A hybrid of space-between and space-around. Flex items are evenly spaced (like space-between), except instead of half-size spaces on both ends (like space-around), there are full-size spaces on both ends.

This layout can be achieved with ::before and ::after pseudo-elements on the flex container.

enter image description here

(credit: @oriol for the code, and @crl for the label)

UPDATE: Browsers have begun implementing space-evenly, which accomplishes the above. See this post for details: Equal space between flex items


PLAYGROUND (includes code for all examples above)

Move branch pointer to different commit without checkout

Honestly, I'm surprised how nobody thought about the git push command:

git push -f . <destination>:<branch>

The dot ( . ) refers the local repository, and you may need the -f option because the destination could be "behind its remote counterpart".

Although this command is used to save your changes in your server, the result is exactly the same as if moving the remote branch (<branch>) to the same commit as the local branch (<destination>)

Vector of Vectors to create matrix

Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link

After initialization there will be no errors, see this link

Calculating distance between two geographic locations

http://developer.android.com/reference/android/location/Location.html

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);

or

private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
   
    return 6366000 * tt;
}

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

Python script to copy text to clipboard

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

What is the most efficient/elegant way to parse a flat table into a tree?

This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.

It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)

This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.

public class Node {

    private Node parent = null;

    private List<Node> children;

    private String name;

    private int id = -1;

    public Node(Node parent, int id, String name) {
        this.parent = parent;
        this.children = new ArrayList<Node>();
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public List<Node> getChildren() {
        return children;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", parent=" + parent;
    }
}

public class NodeBuilder {

    public static Node build(List<Map<String, String>> input) {

        // maps id of a node to it's Node object
        Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();

        // maps id of a node to the id of it's parent
        Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();

        // create special 'root' Node with id=0
        Node root = new Node(null, 0, "root");
        nodeMap.put(root.getId(), root);

        // iterate thru the input
        for (Map<String, String> map : input) {

            // expect each Map to have keys for "id", "name", "parent" ... a
            // real implementation would read from a SQL object or resultset
            int id = Integer.parseInt(map.get("id"));
            String name = map.get("name");
            int parent = Integer.parseInt(map.get("parent"));

            Node node = new Node(null, id, name);
            nodeMap.put(id, node);

            childParentMap.put(id, parent);
        }

        // now that each Node is created, setup the child-parent relationships
        for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
            int nodeId = entry.getKey();
            int parentId = entry.getValue();

            Node child = nodeMap.get(nodeId);
            Node parent = nodeMap.get(parentId);
            parent.addChild(child);
        }

        return root;
    }
}

public class NodePrinter {

    static void printRootNode(Node root) {
        printNodes(root, 0);
    }

    static void printNodes(Node node, int indentLevel) {

        printNode(node, indentLevel);
        // recurse
        for (Node child : node.getChildren()) {
            printNodes(child, indentLevel + 1);
        }
    }

    static void printNode(Node node, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("\t");
        }
        sb.append(node);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        // setup dummy data
        List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
        resultSet.add(newMap("1", "Node 1", "0"));
        resultSet.add(newMap("2", "Node 1.1", "1"));
        resultSet.add(newMap("3", "Node 2", "0"));
        resultSet.add(newMap("4", "Node 1.1.1", "2"));
        resultSet.add(newMap("5", "Node 2.1", "3"));
        resultSet.add(newMap("6", "Node 1.2", "1"));

        Node root = NodeBuilder.build(resultSet);
        printRootNode(root);

    }

    //convenience method for creating our dummy data
    private static Map<String, String> newMap(String id, String name, String parentId) {
        Map<String, String> row = new HashMap<String, String>();
        row.put("id", id);
        row.put("name", name);
        row.put("parent", parentId);
        return row;
    }
}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Had the same issue recently, solved by adding traditional: true,

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

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

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Understanding events and event handlers in C#

My understanding of the events is;

Delegate:

A variable to hold reference to method / methods to be executed. This makes it possible to pass around methods like a variable.

Steps for creating and calling the event:

  1. The event is an instance of a delegate

  2. Since an event is an instance of a delegate, then we have to first define the delegate.

  3. Assign the method / methods to be executed when the event is fired (Calling the delegate)

  4. Fire the event (Call the delegate)

Example:

using System;

namespace test{
    class MyTestApp{
        //The Event Handler declaration
        public delegate void EventHandler();

        //The Event declaration
        public event EventHandler MyHandler;

        //The method to call
        public void Hello(){
            Console.WriteLine("Hello World of events!");
        }

        public static void Main(){
            MyTestApp TestApp = new MyTestApp();

            //Assign the method to be called when the event is fired
            TestApp.MyHandler = new EventHandler(TestApp.Hello);

            //Firing the event
            if (TestApp.MyHandler != null){
                TestApp.MyHandler();
            }
        }

    }   

}

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

Try this way,hope this will help you to solve your problem.

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

MyActivity.java

public class MyActivity extends Activity {

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.webView);
        webView.loadData("<a href=\"tel:+1800229933\">Call us free!</a>", "text/html", "utf-8");
    }

}

Please add this permission in AndroidManifest.xml

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

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had the same error today, after deploying our service calling an external service to the staging environment in azure. Local the service called the external service without errors, but after deployment it didn't.

In the end it turned out to be that the external service has a IP validation. The new environment in Azure has another IP and it was rejected.

So if you ever get this error calling external services

It might be an IP restriction.

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

Datanode process not running in Hadoop

Delete the files under $hadoop_User/dfsdata and $hadoop_User/tmpdata then run:

hdfs namenode -format

finally run:

start-all.sh

Then your problem gets solved.

Select current element in jQuery

To select the sibling, you'd need something like:

$(this).next();

So, Shog9's comment is not correct. First of all, you'd need to name the variable "clicked" outside of the div click function, otherwise, it is lost after the click occurs.

var clicked;

$("div a").click(function(){
   clicked = $(this).next();
   // Do what you need to do to the newly defined click here
});

// But you can also access the "clicked" element here

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

How to fix HTTP 404 on Github Pages?

If you haven't already, choose a Jekyll theme in your GitHub Pages settings tab. Apparently this is required even if you're not using Jekyll for your Pages site.

GitHub settings screenshot

How to reload/refresh jQuery dataTable?

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

HTML

<table id="HelpdeskOverview">
  <thead>
    <tr>
      <th>Ärende</th>
      <th>Rapporterad</th>
      <th>Syst/Utr/Appl</th>
      <th>Prio</th>
      <th>Rubrik</th>
      <th>Status</th>
      <th>Ägare</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Javascript

function InitOverviewDataTable()
{
  oOverviewTable =$('#HelpdeskOverview').dataTable(
  {
    "bPaginate": true,
    "bJQueryUI": true,  // ThemeRoller-stöd
    "bLengthChange": false,
    "bFilter": false,
    "bSort": false,
    "bInfo": true,
    "bAutoWidth": true,
    "bProcessing": true,
    "iDisplayLength": 10,
    "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
  });
}

function RefreshTable(tableId, urlData)
{
  $.getJSON(urlData, null, function( json )
  {
    table = $(tableId).dataTable();
    oSettings = table.fnSettings();

    table.fnClearTable(this);

    for (var i=0; i<json.aaData.length; i++)
    {
      table.oApi._fnAddData(oSettings, json.aaData[i]);
    }

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
  });
}

function AutoReload()
{
  RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

  setTimeout(function(){AutoReload();}, 30000);
}

$(document).ready(function () {
  InitOverviewDataTable();
  setTimeout(function(){AutoReload();}, 30000);
});

Source

Add default value of datetime field in SQL Server to a timestamp

This works for me...

ALTER TABLE [accounts] 
 ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;

How to convert integer to char in C?

A char in C is already a number (the character's ASCII code), no conversion required.

If you want to convert a digit to the corresponding character, you can simply add '0':

c = i +'0';

The '0' is a character in the ASCll table.

When to use pthread_exit() and when to use pthread_join() in Linux?

The pthread_exit() API

as has been already remarked, is used for the calling thread termination. After a call to that function a complicating clean up mechanism is started. When it completes the thread is terminated. The pthread_exit() API is also called implicitly when a call to the return() routine occurs in a thread created by pthread_create(). Actually, a call to return() and a call to pthread_exit() have the same impact, being called from a thread created by pthread_create().

It is very important to distinguish the initial thread, implicitly created when the main() function starts, and threads created by pthread_create(). A call to the return() routine from the main() function implicitly invokes the exit() system call and the entire process terminates. No thread clean up mechanism is started. A call to the pthread_exit() from the main() function causes the clean up mechanism to start and when it finishes its work the initial thread terminates.

What happens to the entire process (and to other threads) when pthread_exit() is called from the main() function depends on the PTHREAD implementation. For example, on IBM OS/400 implementation the entire process is terminated, including other threads, when pthread_exit() is called from the main() function. Other systems may behave differently. On most modern Linux machines a call to pthread_exit() from the initial thread does not terminate the entire process until all threads termination. Be careful using pthread_exit() from main(), if you want to write a portable application.

The pthread_join() API

is a convenient way to wait for a thread termination. You may write your own function that waits for a thread termination, perhaps more suitable to your application, instead of using pthread_join(). For example, it can be a function based on waiting on conditional variables.

I would recommend for reading a book of David R. Butenhof “Programming with POSIX Threads”. It explains the discussed topics (and more complicated things) very well (although some implementation details, such as pthread_exit usage in the main function, not always reflected in the book).

Why do people write #!/usr/bin/env python on the first line of a Python script?

It probably makes sense to emphasize one thing that the most have missed, which may prevent immediate understanding. When you type python in terminal you don't normally provide a full path. Instead, the executable is up looked in PATH environment variable. In turn, when you want to execute a Python program directly, /path/to/app.py, one must tell the shell what interpreter to use (via the hashbang, what the other contributors are explaining above).

Hashbang expects full path to an interpreter. Thus to run your Python program directly you have to provide full path to Python binary which varies significantly, especially considering a use of virtualenv. To address portability the trick with /usr/bin/env is used. The latter is originally intended to alter environment in-place and run a command in it. When no alteration is provided it runs the command in current environment, which effectively results in the same PATH lookup which does the trick.

Source from unix stackexchange

WebView and HTML5 <video>

mdelolmo's answer was incredibly helpful, but like he said, the video only plays once and then you can't open it again.

I looked into this a bit and here is what I found, in case any weary WebView travelers like myself stumble on this post in the future.

First off, I looked at the VideoView and MediaPlayer's documentation and got a better sense of how those work. I strongly recommend those.

Then, I looked at the source code to see how the Android Browser does it. Do a page find and go look at how they handle onShowCustomView(). They keep a reference to the CustomViewCallbackand to the custom view.

With all of that, and with mdelolmo's answer in mind, when you are done with the video, all you need to do is two things. First, on the VideoView that you saved a reference to, call stopPlayback() that will release the MediaPlayer to be used later elsewhere. You can see it in the VideoView source code. Second, on the CustomViewCallback you saved a reference to call CustomViewCallback.onCustomViewHidden().

After doing those two things, you can click on the same video or any other video and it will open like before. No need to restart the entire WebView.

Hope that helps.

Collections.sort with multiple fields

I'd make a comparator using Guava's ComparisonChain:

public class ReportComparator implements Comparator<Report> {
  public int compare(Report r1, Report r2) {
    return ComparisonChain.start()
        .compare(r1.getReportKey(), r2.getReportKey())
        .compare(r1.getStudentNumber(), r2.getStudentNumber())
        .compare(r1.getSchool(), r2.getSchool())
        .result();
  }
}

How to sort a Collection<T>?

You can't if T is all you get. It must be injected by the provider:

Collection<T extends Comparable>

or pass in the Comparator

Collections.sort(...)

Auto Scale TextView Text to Fit within Bounds

I needed a specific solution. I have got an edittext and textview in my layout. The textview is fixed height and width. When the user starts to type in the edittext, the text should immediately appear in the textview. The text in the textfield should auto - resize to fit the textview. So I updated Chase's solution to work for me. So when the text changes in the textview, resizing starts. The difference between mine and Chase's soluton: resizing is done even if the user DELETE some chars. I hope it can help someone.

public class TextFitTextView extends TextView {

// Minimum text size for this text view
public static final float MIN_TEXT_SIZE = 10;

// Maximum text size for this text view - if it is 0, then the text acts
// like match_parent
public static final float MAX_TEXT_SIZE = 0;

// Our ellipse string
private static final String mEllipsis = "...";

// Text size that is set from code. This acts as a starting point for
// resizing
private float mTextSize;

// Lower bounds for text size
private float mMinTextSize = MIN_TEXT_SIZE;

// Max bounds for text size
private float mMaxTextSize = MAX_TEXT_SIZE;

// Text view line spacing multiplier
private float mSpacingMult = 1.0f;

// Text view additional line spacing
private float mSpacingAdd = 0.0f;

// Add ellipsis to text that overflows at the smallest text size
private boolean mAddEllipsis = true;

// Add ellipsis to text that overflows at the smallest text size
private int heightLimit;
private int widthLimit;

// Default constructor override
public TextFitTextView(Context context) {
    this(context, null);
}

// Default constructor when inflating from XML file
public TextFitTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

// Default constructor override
public TextFitTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mTextSize = getTextSize();
}

/**
 * When text changes resize the text size.
 */
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
    // if we are adding new chars to text
    if (before <= after && after != 1) {
        resizeText(true);
        // now we are deleting chars
    } else {
        resizeText(false);
    }
}

/**
 * Override the set text size to update our internal reference values
 */
@Override
public void setTextSize(float size) {
    super.setTextSize(size);
    mTextSize = getTextSize();
}

/**
 * Override the set text size to update our internal reference values
 */
@Override
public void setTextSize(int unit, float size) {
    super.setTextSize(unit, size);
    mTextSize = getTextSize();
}

/**
 * Override the set line spacing to update our internal reference values
 */
@Override
public void setLineSpacing(float add, float mult) {
    super.setLineSpacing(add, mult);
    mSpacingMult = mult;
    mSpacingAdd = add;
}

/**
 * Set the lower text size limit and invalidate the view
 * 
 * @param minTextSize
 */
public void setMinTextSize(float minTextSize) {
    mMinTextSize = minTextSize;
    requestLayout();
    invalidate();
}

/**
 * Return lower text size limit
 * 
 * @return
 */
public float getMinTextSize() {
    return mMinTextSize;
}

/**
 * Set flag to add ellipsis to text that overflows at the smallest text size
 * 
 * @param addEllipsis
 */
public void setAddEllipsis(boolean addEllipsis) {
    mAddEllipsis = addEllipsis;
}

/**
 * Return flag to add ellipsis to text that overflows at the smallest text
 * size
 * 
 * @return
 */
public boolean getAddEllipsis() {
    return mAddEllipsis;
}

/**
 * Get width and height limits
 */
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    if (widthLimit == 0 && heightLimit == 0) {
        widthLimit = (right - left) - getCompoundPaddingLeft() - getCompoundPaddingRight();
        heightLimit = (bottom - top) - getCompoundPaddingBottom() - getCompoundPaddingTop();
    }
    super.onLayout(changed, left, top, right, bottom);
}

/**
 * Resize the text size with specified width and height
 * 
 * @param width
 * @param height
 */
public void resizeText(boolean increase) {
    CharSequence text = getText();
    // Do not resize if the view does not have dimensions or there is no
    // text
    if (text == null || text.length() == 0 || heightLimit <= 0 || widthLimit <= 0 || mTextSize == 0) {
        return;
    }

    // Get the text view's paint object
    TextPaint textPaint = getPaint();

    // Get the required text height
    int textHeight = getTextHeight(text, textPaint, widthLimit, mTextSize);


    // If the text length is increased 
    // Until we either fit within our text view or we had reached our min
    // text size, incrementally try smaller sizes
    if (increase) {
        while (textHeight > heightLimit && mTextSize > mMinTextSize) {
            mTextSize = Math.max(mTextSize - 2, mMinTextSize);
            textHeight = getTextHeight(text, textPaint, widthLimit, mTextSize);
        }
    } 
//      text length has been decreased
    else {
//          if max test size is set then add it to while condition
        if (mMaxTextSize != 0) {
            while (textHeight < heightLimit && mTextSize <= mMaxTextSize) {
                mTextSize = mTextSize + 2;
                textHeight = getTextHeight(text, textPaint, widthLimit, mTextSize);
            }
        } else {
            while (textHeight < heightLimit) {
                mTextSize = mTextSize + 2;
                textHeight = getTextHeight(text, textPaint, widthLimit, mTextSize);
            }
        }
        mTextSize = textHeight > heightLimit ? mTextSize - 2 : mTextSize;
    }

    // If we had reached our minimum text size and still don't fit, append
    // an ellipsis
    if (mAddEllipsis && mTextSize == mMinTextSize && textHeight > heightLimit) {
        // Draw using a static layout
        TextPaint paint = new TextPaint(textPaint);
        StaticLayout layout = new StaticLayout(text, paint, widthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
                mSpacingAdd, false);
        // Check that we have a least one line of rendered text
        if (layout.getLineCount() > 0) {
            // Since the line at the specific vertical position would be cut
            // off,
            // we must trim up to the previous line
            int lastLine = layout.getLineForVertical(heightLimit) - 1;
            // If the text would not even fit on a single line, clear it
            if (lastLine < 0) {
                setText("");
            }
            // Otherwise, trim to the previous line and add an ellipsis
            else {
                int start = layout.getLineStart(lastLine);
                int end = layout.getLineEnd(lastLine);
                float lineWidth = layout.getLineWidth(lastLine);
                float ellipseWidth = paint.measureText(mEllipsis);

                // Trim characters off until we have enough room to draw the
                // ellipsis
                while (widthLimit < lineWidth + ellipseWidth) {
                    lineWidth = paint.measureText(text.subSequence(start, --end + 1).toString());
                }
                setText(text.subSequence(0, end) + mEllipsis);
            }
        }
    }

    // Some devices try to auto adjust line spacing, so force default line
    // spacing
    // and invalidate the layout as a side effect
    setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

}

// Set the text size of the text paint object and use a static layout to
// render text off screen before measuring
private int getTextHeight(CharSequence source, TextPaint originalPaint, int width, float textSize) {
    // Update the text paint object
    TextPaint paint = new TextPaint(originalPaint);
    paint.setTextSize(textSize);
    // Measure using a static layout
    StaticLayout layout = new StaticLayout(source, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd,
            true);
    return layout.getHeight();
}

}

How to get selected value of a html select with asp.net

If you would use asp:dropdownlist you could select it easier by testSelect.Text.

Now you'd have to do a Request.Form["testSelect"] to get the value after pressed btnTes.

Hope it helps.

EDIT: You need to specify a name of the select (not only ID) to be able to Request.Form["testSelect"]

How do you create a read-only user in PostgreSQL?

I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

Had this issue with spring-boot 2.4.1 when running the tests in bulk from [Intellij Idea] version 2020.3. The issue doesn't appear when running only one test at a time from IntelliJ or when running the tests from command line.

Maybe Intellij caching problem?

Follow up:

The problem appears when running tests using the maven-surefire-plugin reuseForks true. Using reuseForks false would provide a quick fix, but the tests running time will increase dramatically. Because we are reusing forks, the database context might become dirty due to other tests that are run - without cleaning the database context afterwards. The obvious solution would be to clean the database context before running a test, but the best one should be to clean up the database context after each test (solving the root cause of the original problem). Using the @Transactional annotation on your test methods will guarantee that your database changes are rolled back at the end of the test methods. See the Spring documentation on transactions: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testcontext-tx.

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.

winpty docker exec -it <container-id> //bin//sh

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

print variable and a string in python

Something that (surprisingly) hasn't been mentioned here is simple concatenation.

Example:

foo = "seven"

print("She lives with " + foo + " small men")

Result:

She lives with seven small men

Additionally, as of Python 3, the % method is deprecated. Don't use that.

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

How to include Javascript file in Asp.Net page

If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:

<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>' 
type="text/javascript"></script>

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

Another solution is to mix valueChangeListener, ajax and process:

<p:selectManyCheckbox id="employees" value="#{employees}" columns="1" layout="grid" valueChangeListener="#{mybean.fireSelection}"   >
    <f:selectItems var="employee" value="#{employeesSI}" />
    <p:ajax event="valueChange" immediate="true" process="@this"/>
</p:selectManyCheckbox>

Method in mybean is just :

public void fireSelection(ValueChangeEvent event) {
    log.debug("New: "+event.getNewValue()+", Old: "+event.getOldValue());
}

Like this, valueChangeEvent is very light !

PS: Works fine with PrimeFaces 5.0

Getting started with Haskell

I'd suggest joining the #haskell irc channel and asking questions there. That's how I learned Haskell. If you go through Real World Haskell as suggested above, real time answers to your questions will help greatly. Lots of smart people on #haskell write Haskell for fun and for profit, so you'll get lots of good input. Try it!

How do I get the time difference between two DateTime objects using C#?

 var startDate = new DateTime(2007, 3, 24);

 var endDate = new DateTime(2009, 6, 26);

 var dateDiff = endDate.Subtract(startDate);

 var date = string.Format("{0} years {1} months {2} days", (int)dateDiff.TotalDays / 365, 
 (int)(dateDiff.TotalDays % 365) / 30, (int)(dateDiff.TotalDays % 365) / 30);

 Console.WriteLine(date);

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse


def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
        print(sock.recv(10240))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.1' '224.1.1.2' '224.1.1.3' --bind-group '224.1.1.2'

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.4'

Multicast sender:

import socket
import argparse


def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='224.1.1.1')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 multicast_send.py --mcast-group '224.1.1.2'

python3 multicast_send.py --mcast-group '224.1.1.4'

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Android Studio: Application Installation Failed

I solved the issue by simply deleting my whole /build folder and rebuilding (menu Build > rebuild project).

java build path problems

From the Package Explorer in Eclipse, you can right click the project, choose Build Path, Configure Build Path to get the build path dialog. From there you can remove the JRE reference for the 1.5 JRE and 'Add Library' to add a reference to your installed JRE.

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

How to disable an input type=text?

document.getElementById('foo').disabled = true;

or

document.getElementById('foo').readOnly = true;

Note that readOnly should be in camelCase to work correctly in Firefox (magic).

Demo: https://jsfiddle.net/L96svw3c/ -- somewhat explains the difference between disabled and readOnly.

How to create a template function within a class? (C++)

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

SQL query to find third highest salary in company

select min (salary) from Employee where Salary in (Select Top 3 Salary from Employee order by Salary desc)

How to count duplicate value in an array in javascript

Duplicates in an array containing alphabets:

_x000D_
_x000D_
var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],_x000D_
  sortedArr = [],_x000D_
  count = 1;_x000D_
_x000D_
sortedArr = arr.sort();_x000D_
_x000D_
for (var i = 0; i < sortedArr.length; i = i + count) {_x000D_
  count = 1;_x000D_
  for (var j = i + 1; j < sortedArr.length; j++) {_x000D_
    if (sortedArr[i] === sortedArr[j])_x000D_
      count++;_x000D_
  }_x000D_
  document.write(sortedArr[i] + " = " + count + "<br>");_x000D_
}
_x000D_
_x000D_
_x000D_

Duplicates in an array containing numbers:

_x000D_
_x000D_
var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],_x000D_
  sortedArr = [],_x000D_
  count = 1;_x000D_
sortedArr = arr.sort(function(a, b) {_x000D_
  return a - b_x000D_
});_x000D_
for (var i = 0; i < sortedArr.length; i = i + count) {_x000D_
  count = 1;_x000D_
  for (var j = i + 1; j < sortedArr.length; j++) {_x000D_
    if (sortedArr[i] === sortedArr[j])_x000D_
      count++;_x000D_
  }_x000D_
  document.write(sortedArr[i] + " = " + count + "<br>");_x000D_
}
_x000D_
_x000D_
_x000D_

Install msi with msiexec in a Specific Directory

I tried TARGETDIR, INSTALLLOCATION and INSTALLDIR args and still it installed in the default directory. So I viewed the log and there is this arg where it sets the Application Directory and it is being set to default.

MSI (s) (50:94) [09:03:13:374]: Running product '{BDAFD18D-0395-4E72-B295-1EA66A7B80CF}' with elevated privileges: Product is assigned.
MSI (s) (50:94) [09:03:13:374]: PROPERTY CHANGE: Adding APPDIR property. Its value is 'E:\RMP2'.
MSI (s) (50:94) [09:03:13:374]: PROPERTY CHANGE: Adding CURRENTDIRECTORY property. Its value is 'C:\Users\Administrator'.

So I changed the command to have APPDIR instead of the args mentioned above. It worked like a charm.

msiexec /i "path_to_msi" APPDIR="path_to_installation_dir" /q

Add /lv if you want to copy the installation progress to a logfile.

Parsing a comma-delimited std::string

Something less verbose, std and takes anything separated by a comma.

stringstream ss( "1,1,1,1, or something else ,1,1,1,0" );
vector<string> result;

while( ss.good() )
{
    string substr;
    getline( ss, substr, ',' );
    result.push_back( substr );
}

Error Code: 1406. Data too long for column - MySQL

I got the same error while using the imagefield in Django. post_picture = models.ImageField(upload_to='home2/khamulat/mydomain.com/static/assets/images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)

I just removed the excess code as shown above to post_picture = models.ImageField(upload_to='images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None) and the error was gone

Does Index of Array Exist

You can rather use a List, so you can check the existence.

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}

React prevent event bubbling in nested components on click

You can avoid event bubbling by checking target of event.
For example if you have input nested to the div element where you have handler for click event, and you don't want to handle it, when input is clicked, you can just pass event.target into your handler and check is handler should be executed based on properties of target.
For example you can check if (target.localName === "input") { return}.
So, it's a way to "avoid" handler execution

Best practice for Django project working directory structure

My answer is inspired on my own working experience, and mostly in the book Two Scoops of Django which I highly recommend, and where you can find a more detailed explanation of everything. I just will answer some of the points, and any improvement or correction will be welcomed. But there also can be more correct manners to achieve the same purpose.

Projects
I have a main folder in my personal directory where I maintain all the projects where I am working on.

Source Files
I personally use the django project root as repository root of my projects. But in the book is recommended to separate both things. I think that this is a better approach, so I hope to start making the change progressively on my projects.

project_repository_folder/
    .gitignore
    Makefile
    LICENSE.rst
    docs/
    README.rst
    requirements.txt
    project_folder/
        manage.py
        media/
        app-1/
        app-2/
        ...
        app-n/
        static/
        templates/
        project/
            __init__.py
            settings/
                __init__.py
                base.py
                dev.py
                local.py
                test.py
                production.py
            ulrs.py
            wsgi.py

Repository
Git or Mercurial seem to be the most popular version control systems among Django developers. And the most popular hosting services for backups GitHub and Bitbucket.

Virtual Environment
I use virtualenv and virtualenvwrapper. After installing the second one, you need to set up your working directory. Mine is on my /home/envs directory, as it is recommended on virtualenvwrapper installation guide. But I don't think the most important thing is where is it placed. The most important thing when working with virtual environments is keeping requirements.txt file up to date.

pip freeze -l > requirements.txt 

Static Root
Project folder

Media Root
Project folder

README
Repository root

LICENSE
Repository root

Documents
Repository root. This python packages can help you making easier mantaining your documentation:

Sketches

Examples

Database

How to set cache: false in jQuery.get call

Note that callback syntax is deprecated:

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Here a modernized solution using the promise interface

$.ajax({url: "...", cache: false}).done(function( data ) {
    // data contains result
}).fail(function(err){
    // error
});

DTO pattern: Best way to copy properties between two objects

You can use Apache Commmons Beanutils. The API is

org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(Object dest, Object orig).

It copies property values from the "origin" bean to the "destination" bean for all cases where the property names are the same.

Now I am going to off topic. Using DTO is mostly considered an anti-pattern in EJB3. If your DTO and your domain objects are very alike, there is really no need to duplicate codes. DTO still has merits, especially for saving network bandwidth when remote access is involved. I do not have details about your application architecture, but if the layers you talked about are logical layers and does not cross network, I do not see the need for DTO.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

Although I didn't use this exact function I got this same error.

In my case I just had to remove the protocol.

Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";

Use $uri = "api.hostip.info/?ip=$ip&position=true";

And it worked fine afterwards

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

IntelliJ: Never use wildcard imports

  1. File\Settings... (Ctrl+Alt+S)
  2. Project Settings > Editor > Code Style > Java > Imports tab
  3. Set Class count to use import with '*' to 999
  4. Set Names count to use static import with '*' to 999

After this, your configuration should look like: enter image description here

(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)

jQuery loop over JSON result from AJAX Success?

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

Counting repeated characters in a string in Python

My first idea was to do this:

chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"

for char in chars:
  count = check_string.count(char)
  if count > 1:
    print char, count

This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:

count = {}
for s in check_string:
  if s in count:
    count[s] += 1
  else:
    count[s] = 1

for key in count:
  if count[key] > 1:
    print key, count[key]

This ensures that you only go through the string once, instead of 26 times.

Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.

What is the difference between DSA and RSA?

And in addition to the above nice answers.

  • DSA uses Discrete logarithm.
  • RSA uses Integer Factorization.

RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

How to find out which processes are using swap space in Linux?

Here's a version that outputs the same as the script by @loolotux, but is much faster(while less readable). That loop takes about 10 secs on my machine, my version takes 0.019 s, which mattered to me because I wanted to make it into a cgi page.

    join -t / -1 3 -2 3 \
    <(grep VmSwap /proc/*/status  |egrep -v '/proc/self|thread-self' | sort -k3,3 --field-separator=/ ) \
    <(grep -H  '' --binary-files=text /proc/*/cmdline |tr '\0' ' '|cut -c 1-200|egrep -v '/proc/self|/thread-self'|sort -k3,3 --field-separator=/ ) \
    | cut -d/ -f1,4,7- \
    | sed 's/status//; s/cmdline//' \
    | sort -h -k3,3 --field-separator=:\
    | tee >(awk -F: '{s+=$3} END {printf "\nTotal Swap Usage = %.0f kB\n",s}') /dev/null

Disable Enable Trigger SQL server for a table

if you want to execute ENABLE TRIGGER Directly From Source :

we can't write like this:

Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"

instead, we can write :

Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"

Upgrading React version and it's dependencies by reading package.json

if you want to update your react and react-dom version in your existing react step then run this command I hope You get the latest version of react and react-dom.

Thanks

npm install react@latest react-dom@latest

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

Callback after all asynchronous forEach callbacks are completed

Array.forEach does not provide this nicety (oh if it would) but there are several ways to accomplish what you want:

Using a simple counter

function callback () { console.log('all done'); }

var itemsProcessed = 0;

[1, 2, 3].forEach((item, index, array) => {
  asyncFunction(item, () => {
    itemsProcessed++;
    if(itemsProcessed === array.length) {
      callback();
    }
  });
});

(thanks to @vanuan and others) This approach guarantees that all items are processed before invoking the "done" callback. You need to use a counter that gets updated in the callback. Depending on the value of the index parameter does not provide the same guarantee, because the order of return of the asynchronous operations is not guaranteed.

Using ES6 Promises

(a promise library can be used for older browsers):

  1. Process all requests guaranteeing synchronous execution (e.g. 1 then 2 then 3)

    function asyncFunction (item, cb) {
      setTimeout(() => {
        console.log('done with', item);
        cb();
      }, 100);
    }
    
    let requests = [1, 2, 3].reduce((promiseChain, item) => {
        return promiseChain.then(() => new Promise((resolve) => {
          asyncFunction(item, resolve);
        }));
    }, Promise.resolve());
    
    requests.then(() => console.log('done'))
    
  2. Process all async requests without "synchronous" execution (2 may finish faster than 1)

    let requests = [1,2,3].map((item) => {
        return new Promise((resolve) => {
          asyncFunction(item, resolve);
        });
    })
    
    Promise.all(requests).then(() => console.log('done'));
    

Using an async library

There are other asynchronous libraries, async being the most popular, that provide mechanisms to express what you want.

Edit

The body of the question has been edited to remove the previously synchronous example code, so i've updated my answer to clarify. The original example used synchronous like code to model asynchronous behaviour, so the following applied:

array.forEach is synchronous and so is res.write, so you can simply put your callback after your call to foreach:

  posts.foreach(function(v, i) {
    res.write(v + ". index " + i);
  });

  res.end();

Create an ISO date object in javascript

In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)) So, simply convert it to a js Date by: new Date(ISOString);

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

Override browser form-filling and input highlighting with HTML/CSS

The REAL problem here is that Webkit (Safari, Chrome, ...) has a bug. When there's more than one [form] on the page, each with an [input type="text" name="foo" ...] (i.e. with the same value for the attribute 'name'), then when the user returns to the page the autofill will be done in the input field of the FIRST [form] on the page, not in the [form] that was sent. The second time, the NEXT [form] will be autofilled, and so on. Only [form] with an input text field with the SAME name will be affected.

This should be reported to the Webkit developers.

Opera autofills the right [form].

Firefox and IE doesn't autofill.

So, I say again: this is a bug in Webkit.

How do you add Boost libraries in CMakeLists.txt?

You can use find_package to search for available boost libraries. It defers searching for Boost to FindBoost.cmake, which is default installed with CMake.

Upon finding Boost, the find_package() call will have filled many variables (check the reference for FindBoost.cmake). Among these are BOOST_INCLUDE_DIRS, Boost_LIBRARIES and Boost_XXX_LIBRARY variabels, with XXX replaced with specific Boost libraries. You can use these to specify include_directories and target_link_libraries.

For example, suppose you would need boost::program_options and boost::regex, you would do something like:

find_package( Boost REQUIRED COMPONENTS program_options regex )
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable( run main.cpp ) # Example application based on main.cpp

# Alternatively you could use ${Boost_LIBRARIES} here.
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )

Some general tips:

  • When searching, FindBoost checks the environment variable $ENV{BOOST_ROOT}. You can set this variable before calling find_package if necessary.
  • When you have multiple build-versions of boost (multi-threaded, static, shared, etc.) you can specify you desired configuration before calling find_package. Do this by setting some of the following variables to On: Boost_USE_STATIC_LIBS, Boost_USE_MULTITHREADED, Boost_USE_STATIC_RUNTIME
  • When searching for Boost on Windows, take care with the auto-linking. Read the "NOTE for Visual Studio Users" in the reference.
    • My advice is to disable auto-linking and use cmake's dependency handling: add_definitions( -DBOOST_ALL_NO_LIB )
    • In some cases, you may need to explicitly specify that a dynamic Boost is used: add_definitions( -DBOOST_ALL_DYN_LINK )

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Just just using Transformers It did not work for me I was getting type cast exception.

sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class)) did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.

It worked for me when I make following changes When I have added sqlQuery.addScalar(-) each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");

And I have join MYEngityName with NextEnity we cant just select * in the Query it will give array of Object in the return list.

Below code sample :

session = ht.getSessionFactory().openSession();
                String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM  MYEngityName nft INNER JOIN NextEntity m on nft.mId  =  m.id where nft.txnId < ").append(lastTxnId)
                       .append(StringUtils.isNotBlank(regionalCountryOfService)? " And  m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
                       .append(" order by nft.txnId desc").toString();
                SQLQuery sqlQuery = session.createSQLQuery(sql);
                sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
                sqlQuery.addScalar("txnId",Hibernate.LONG)
                        .addScalar("merchantId",Hibernate.INTEGER)
                        .addScalar("count",Hibernate.BYTE)
                        .addScalar("retryReason")
                        .addScalar("langCode");
                sqlQuery.setMaxResults(maxLimit);
                return sqlQuery.list();

It might help some one. in this way work for me.

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

How to make JQuery-AJAX request synchronous

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

return, return None, and no return at all?

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      

<DIV> inside link (<a href="">) tag

I think you should do it the other way round. Define your Divs and have your a href within each Div, pointing to different links

Copying files into the application folder at compile time

You could do this with a post build event. Set the files to no action on compile, then in the macro copy the files to the directory you want.

Here's a post build Macro that I think will work by copying all files in a directory called Configuration to the root build folder:

copy $(ProjectDir)Configuration\* $(ProjectDir)$(OutDir)

Why does JavaScript only work after opening developer tools in IE once?

If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.

Simple service for logging. Default implementation safely writes the message into the browser's console (if present).

https://docs.angularjs.org/api/ng/service/$log

So if you have something similar to

angular.module('logExample', [])
  .controller('LogController', ['$scope', function($scope) {
    console.log('Hello World!');
 }]);

you can replace it with

angular.module('logExample', [])
  .controller('LogController', ['$scope', '$log', function($scope, $log) {
    $log.log('Hello World!');
 }]);

Angular 2+ does not have any built-in log service.

How to exclude 0 from MIN formula Excel

Solutions listed did not exactly work for me. The closest was Chief Wiggum - I wanted to add a comment on his answer but lack the reputation to do so. So I post as separate answer:

=MIN(IF(A1:E1>0;A1:E1))

Then instead of pressing ENTER, press CTRL+SHIFT+ENTER and watch Excel add { and } to respectively the beginning and the end of the formula (to activate the formula on array).

The comma "," and "If" statement as proposed by Chief Wiggum did not work on Excel Home and Student 2013. Need a semicolon ";" as well as full cap "IF" did the trick. Small syntax difference but took me 1.5 hour to figure out why I was getting an error and #VALUE.

How to solve a pair of nonlinear equations using Python?

You can use openopt package and its NLP method. It has many dynamic programming algorithms to solve nonlinear algebraic equations consisting:
goldenSection, scipy_fminbound, scipy_bfgs, scipy_cg, scipy_ncg, amsg2p, scipy_lbfgsb, scipy_tnc, bobyqa, ralg, ipopt, scipy_slsqp, scipy_cobyla, lincher, algencan, which you can choose from.
Some of the latter algorithms can solve constrained nonlinear programming problem. So, you can introduce your system of equations to openopt.NLP() with a function like this:

lambda x: x[0] + x[1]**2 - 4, np.exp(x[0]) + x[0]*x[1]

Limiting Python input strings to certain characters and lengths

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

print "Your input was:", input_str

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

How to read/process command line arguments?

Just going around evangelizing for argparse which is better for these reasons.. essentially:

(copied from the link)

  • argparse module can handle positional and optional arguments, while optparse can handle only optional arguments

  • argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality

  • argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.

  • argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance

  • argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually

And my personal favorite:

  • argparse allows the type and action parameters to add_argument() to be specified with simple callables, while optparse requires hacking class attributes like STORE_ACTIONS or CHECK_METHODS to get proper argument checking

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

When to use static classes in C#

I've started using static classes when I wish to use functions, rather than classes, as my unit of reuse. Previously, I was all about the evil of static classes. However, learning F# has made me see them in a new light.

What do I mean by this? Well, say when working up some super DRY code, I end up with a bunch of one-method classes. I may just pull these methods into a static class and then inject them into dependencies using a delegate. This also plays nicely with my dependency injection (DI) container of choice Autofac.

Of course taking a direct dependency on a static method is still usually evil (there are some non-evil uses).

Is jQuery $.browser Deprecated?

Updated! 3/24/2015 (scroll below hr)

lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser object, as well as some other little features.


New Extended Version!

Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).

One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent string.

JS Minified

/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */

jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

Does JSON syntax allow duplicate keys in an object?

Asking for purpose, there are different answers:

Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.

However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:

To use duplicate keys to comment our JSON samples. Example:

{ "property1" : "value1", "REMARK" : "... prop1 controls ...", "property2" : "value2", "REMARK" : "... value2 raises an exception ...", }

The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.

So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.

PHP $_POST not working?

Have you check your php.ini ?
I broken my post method once that I set post_max_size the same with upload_max_filesize.

I think that post_max_size must less than upload_max_filesize.
Tested with PHP 5.3.3 in RHEL 6.0

FYI:
$_POST in php 5.3.5 does not work
PHP POST not working

What is the difference between const int*, const int * const, and int const *?

It's simple but tricky. Please note that we can swap the const qualifier with any data type (int, char, float, etc.).

Let's see the below examples.


const int *p ==> *p is read-only [p is a pointer to a constant integer]

int const *p ==> *p is read-only [p is a pointer to a constant integer]


int *p const ==> Wrong Statement. Compiler throws a syntax error.

int *const p ==> p is read-only [p is a constant pointer to an integer]. As pointer p here is read-only, the declaration and definition should be in same place.


const int *p const ==> Wrong Statement. Compiler throws a syntax error.

const int const *p ==> *p is read-only

const int *const p1 ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.


int const *p const ==> Wrong Statement. Compiler throws a syntax error.

int const int *p ==> Wrong Statement. Compiler throws a syntax error.

int const const *p ==> *p is read-only and is equivalent to int const *p

int const *const p ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

Conditional Replace Pandas

Try

df.loc[df.my_channel > 20000, 'my_channel'] = 0

Note: Since v0.20.0, ix has been deprecated in favour of loc / iloc.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

Sometime finish() not working

I have solved that issue with

finishAffinity()

How do I export (and then import) a Subversion repository?

You can also use the svnadmin hotcopy command:

svnadmin hotcopy OLD_REPOS_PATH NEW_REPOS_PATH

It takes a full backup from repository, including all hooks, configuration files, etc.

More at SVN Book

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If one or both of the files you wish to compare isn't in an Eclipse project:

  1. Open the Quick Access search box

    • Linux/Windows: Ctrl+3
    • Mac: ?+3
  2. Type compare and select Compare With Other Resource

  3. Select the files to compare ? OK

You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys

How to run a maven created jar file using just the command line

I am not sure in your case. But as I know to run any jar file from cmd we can use following command:

Go up to the directory where your jar file is saved:

java -jar <jarfilename>.jar

But you can check following links. I hope it'll help you:

Run Netbeans maven project from command-line?

http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html

How to add parameters to a HTTP GET request in Android?

If you have constant URL I recommend use simplified http-request built on apache http.

You can build your client as following:

private filan static HttpRequest<YourResponseType> httpRequest = 
                   HttpRequestBuilder.createGet(yourUri,YourResponseType)
                   .build();

public void send(){
    ResponseHendler<YourResponseType> rh = 
         httpRequest.execute(param1, value1, param2, value2);

    handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
     rh.ifHasContent(content -> // your code);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
   LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText());
}

Note: There are many useful methods to manipulate your response.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

How to get the input from the Tkinter Text Widget?

Lets say that you have a Text widget called my_text_widget.

To get input from the my_text_widget you can use the get function.

Let's assume that you have imported tkinter. Lets define my_text_widget first, lets make it just a simple text widget.

my_text_widget = Text(self)

To get input from a text widget you need to use the get function, both, text and entry widgets have this.

input = my_text_widget.get()

The reason we save it to a variable is to use it in the further process, for example, testing for what's the input.

Accessing a class' member variables in Python?

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

Default SecurityProtocol in .NET 4.5

I'm running under .NET 4.5.2, and I wasn't happy with any of these answers. As I'm talking to a system which supports TLS 1.2, and seeing as SSL3, TLS 1.0, and TLS 1.1 are all broken and unsafe for use, I don't want to enable these protocols. Under .NET 4.5.2, the SSL3 and TLS 1.0 protocols are both enabled by default, which I can see in code by inspecting ServicePointManager.SecurityProtocol. Under .NET 4.7, there's the new SystemDefault protocol mode which explicitly hands over selection of the protocol to the OS, where I believe relying on registry or other system configuration settings would be appropriate. That doesn't seem to be supported under .NET 4.5.2 however. In the interests of writing forwards-compatible code, that will keep making the right decisions even when TLS 1.2 is inevitably broken in the future, or when I upgrade to .NET 4.7+ and hand over more responsibility for selecting an appropriate protocol to the OS, I adopted the following code:

SecurityProtocolType securityProtocols = ServicePointManager.SecurityProtocol;
if (securityProtocols.HasFlag(SecurityProtocolType.Ssl3) || securityProtocols.HasFlag(SecurityProtocolType.Tls) || securityProtocols.HasFlag(SecurityProtocolType.Tls11))
{
    securityProtocols &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
    if (securityProtocols == 0)
    {
        securityProtocols |= SecurityProtocolType.Tls12;
    }
    ServicePointManager.SecurityProtocol = securityProtocols;
}

This code will detect when a known insecure protocol is enabled, and in this case, we'll remove these insecure protocols. If no other explicit protocols remain, we'll then force enable TLS 1.2, as the only known secure protocol supported by .NET at this point in time. This code is forwards compatible, as it will take into consideration new protocol types it doesn't know about being added in the future, and it will also play nice with the new SystemDefault state in .NET 4.7, meaning I won't have to re-visit this code in the future. I'd strongly recommend adopting an approach like this, rather than hard-coding any particular security protocol states unconditionally, otherwise you'll have to recompile and replace your client with a new version in order to upgrade to a new security protocol when TLS 1.2 is inevitably broken, or more likely you'll have to leave the existing insecure protocols turned on for years on your server, making your organisation a target for attacks.

How to prevent SIGPIPEs (or handle them properly)

You generally want to ignore the SIGPIPE and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.

The most portable way to do this is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket or pipe write from causing a SIGPIPE signal.

To ignore the SIGPIPE signal, use the following code:

signal(SIGPIPE, SIG_IGN);

If you're using the send() call, another option is to use the MSG_NOSIGNAL option, which will turn the SIGPIPE behavior off on a per call basis. Note that not all operating systems support the MSG_NOSIGNAL flag.

Lastly, you may also want to consider the SO_SIGNOPIPE socket flag that can be set with setsockopt() on some operating systems. This will prevent SIGPIPE from being caused by writes just to the sockets it is set on.

Table 'mysql.user' doesn't exist:ERROR

My solution was to run

mysql_upgrade -u root

Scenario: I updated the MySQL version on my Mac with 'homebrew upgrade'. Afterwards, some stuff worked, but other commands raised the error described in the question.

Validating parameters to a Bash script

Use set -u which will cause any unset argument reference to immediately fail the script.

Please, see the article: Writing Robust Bash Shell Scripts - David Pashley.com.

convert a list of objects from one type to another using lambda expression

Try the following

var targetList = origList
  .Select(x => new TargetType() { SomeValue = x.SomeValue })
  .ToList();

This is using a combination of Lambdas and LINQ to achieve the solution. The Select function is a projection style method which will apply the passed in delegate (or lambda in this case) to every value in the original collection. The result will be returned in a new IEnumerable<TargetType>. The .ToList call is an extension method which will convert this IEnumerable<TargetType> into a List<TargetType>.

setup android on eclipse but don't know SDK directory

You can search your hard drive for one of the programs that's installed with the SDK. For instance, if you search for aapt.exe or adb.exe, they will be in the platform-tools directory underneath the installation directory (which is what you're after).

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Best way to make WPF ListView/GridView sort on column-header clicking?

I use MVVM, so I created some attached properties of my own, using Thomas's as a reference. It does sorting on one column at a time when you click on the header, toggling between Ascending and Descending. It sorts from the very beginning using the first column. And it shows Win7/8 style glyphs.

Normally, all you have to do is set the main property to true (but you have to explicitly declare the GridViewColumnHeaders):

<Window xmlns:local="clr-namespace:MyProjectNamespace">
  <Grid>
    <ListView local:App.EnableGridViewSort="True" ItemsSource="{Binding LVItems}">
      <ListView.View>
        <GridView>
          <GridViewColumn DisplayMemberBinding="{Binding Property1}">
            <GridViewColumnHeader Content="Prop 1" />
          </GridViewColumn>
          <GridViewColumn DisplayMemberBinding="{Binding Property2}">
            <GridViewColumnHeader Content="Prop 2" />
          </GridViewColumn>
        </GridView>
      </ListView.View>
    </ListView>
  </Grid>
<Window>

If you want to sort on a different property than the display, than you have to declare that:

<GridViewColumn DisplayMemberBinding="{Binding Property3}"
                local:App.GridViewSortPropertyName="Property4">
    <GridViewColumnHeader Content="Prop 3" />
</GridViewColumn>

Here's the code for the attached properties, I like to be lazy and put them in the provided App.xaml.cs:

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data.
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace MyProjectNamespace
{
  public partial class App : Application
  {
      #region GridViewSort
      public static DependencyProperty GridViewSortPropertyNameProperty =
          DependencyProperty.RegisterAttached(
              "GridViewSortPropertyName", 
              typeof(string), 
              typeof(App), 
              new UIPropertyMetadata(null)
          );

      public static string GetGridViewSortPropertyName(GridViewColumn gvc)
      {
          return (string)gvc.GetValue(GridViewSortPropertyNameProperty);
      }

      public static void SetGridViewSortPropertyName(GridViewColumn gvc, string n)
      {
          gvc.SetValue(GridViewSortPropertyNameProperty, n);
      }

      public static DependencyProperty CurrentSortColumnProperty =
          DependencyProperty.RegisterAttached(
              "CurrentSortColumn", 
              typeof(GridViewColumn), 
              typeof(App), 
              new UIPropertyMetadata(
                  null, 
                  new PropertyChangedCallback(CurrentSortColumnChanged)
              )
          );

      public static GridViewColumn GetCurrentSortColumn(GridView gv)
      {
          return (GridViewColumn)gv.GetValue(CurrentSortColumnProperty);
      }

      public static void SetCurrentSortColumn(GridView gv, GridViewColumn value)
      {
          gv.SetValue(CurrentSortColumnProperty, value);
      }

      public static void CurrentSortColumnChanged(
          object sender, DependencyPropertyChangedEventArgs e)
      {
          GridViewColumn gvcOld = e.OldValue as GridViewColumn;
          if (gvcOld != null)
          {
              CurrentSortColumnSetGlyph(gvcOld, null);
          }
      }

      public static void CurrentSortColumnSetGlyph(GridViewColumn gvc, ListView lv)
      {
          ListSortDirection lsd;
          Brush brush;
          if (lv == null)
          {
              lsd = ListSortDirection.Ascending;
              brush = Brushes.Transparent;
          }
          else
          {
              SortDescriptionCollection sdc = lv.Items.SortDescriptions;
              if (sdc == null || sdc.Count < 1) return;
              lsd = sdc[0].Direction;
              brush = Brushes.Gray;
          }

          FrameworkElementFactory fefGlyph = 
              new FrameworkElementFactory(typeof(Path));
          fefGlyph.Name = "arrow";
          fefGlyph.SetValue(Path.StrokeThicknessProperty, 1.0);
          fefGlyph.SetValue(Path.FillProperty, brush);
          fefGlyph.SetValue(StackPanel.HorizontalAlignmentProperty, 
              HorizontalAlignment.Center);

          int s = 4;
          if (lsd == ListSortDirection.Ascending)
          {
              PathFigure pf = new PathFigure();
              pf.IsClosed = true;
              pf.StartPoint = new Point(0, s);
              pf.Segments.Add(new LineSegment(new Point(s * 2, s), false));
              pf.Segments.Add(new LineSegment(new Point(s, 0), false));

              PathGeometry pg = new PathGeometry();
              pg.Figures.Add(pf);

              fefGlyph.SetValue(Path.DataProperty, pg);
          }
          else
          {
              PathFigure pf = new PathFigure();
              pf.IsClosed = true;
              pf.StartPoint = new Point(0, 0);
              pf.Segments.Add(new LineSegment(new Point(s, s), false));
              pf.Segments.Add(new LineSegment(new Point(s * 2, 0), false));

              PathGeometry pg = new PathGeometry();
              pg.Figures.Add(pf);

              fefGlyph.SetValue(Path.DataProperty, pg);
          }

          FrameworkElementFactory fefTextBlock = 
              new FrameworkElementFactory(typeof(TextBlock));
          fefTextBlock.SetValue(TextBlock.HorizontalAlignmentProperty,
              HorizontalAlignment.Center);
          fefTextBlock.SetValue(TextBlock.TextProperty, new Binding());

          FrameworkElementFactory fefDockPanel = 
              new FrameworkElementFactory(typeof(StackPanel));
          fefDockPanel.SetValue(StackPanel.OrientationProperty,
              Orientation.Vertical);
          fefDockPanel.AppendChild(fefGlyph);
          fefDockPanel.AppendChild(fefTextBlock);

          DataTemplate dt = new DataTemplate(typeof(GridViewColumn));
          dt.VisualTree = fefDockPanel;

          gvc.HeaderTemplate = dt;
      }

      public static DependencyProperty EnableGridViewSortProperty =
          DependencyProperty.RegisterAttached(
              "EnableGridViewSort", 
              typeof(bool), 
              typeof(App), 
              new UIPropertyMetadata(
                  false, 
                  new PropertyChangedCallback(EnableGridViewSortChanged)
              )
          );

      public static bool GetEnableGridViewSort(ListView lv)
      {
          return (bool)lv.GetValue(EnableGridViewSortProperty);
      }

      public static void SetEnableGridViewSort(ListView lv, bool value)
      {
          lv.SetValue(EnableGridViewSortProperty, value);
      }

      public static void EnableGridViewSortChanged(
          object sender, DependencyPropertyChangedEventArgs e)
      {
          ListView lv = sender as ListView;
          if (lv == null) return;

          if (!(e.NewValue is bool)) return;
          bool enableGridViewSort = (bool)e.NewValue;

          if (enableGridViewSort)
          {
              lv.AddHandler(
                  GridViewColumnHeader.ClickEvent,
                  new RoutedEventHandler(EnableGridViewSortGVHClicked)
              );
              if (lv.View == null)
              {
                  lv.Loaded += new RoutedEventHandler(EnableGridViewSortLVLoaded);
              }
              else
              {
                  EnableGridViewSortLVInitialize(lv);
              }
          }
          else
          {
              lv.RemoveHandler(
                  GridViewColumnHeader.ClickEvent,
                  new RoutedEventHandler(EnableGridViewSortGVHClicked)
              );
          }
      }

      public static void EnableGridViewSortLVLoaded(object sender, RoutedEventArgs e)
      {
          ListView lv = e.Source as ListView;
          EnableGridViewSortLVInitialize(lv);
          lv.Loaded -= new RoutedEventHandler(EnableGridViewSortLVLoaded);
      }

      public static void EnableGridViewSortLVInitialize(ListView lv)
      {
          GridView gv = lv.View as GridView;
          if (gv == null) return;

          bool first = true;
          foreach (GridViewColumn gvc in gv.Columns)
          {
              if (first)
              {
                  EnableGridViewSortApplySort(lv, gv, gvc);
                  first = false;
              }
              else
              {
                  CurrentSortColumnSetGlyph(gvc, null);
              }
          }
      }

      public static void EnableGridViewSortGVHClicked(
          object sender, RoutedEventArgs e)
      {
          GridViewColumnHeader gvch = e.OriginalSource as GridViewColumnHeader;
          if (gvch == null) return;
          GridViewColumn gvc = gvch.Column;
          if(gvc == null) return;            
          ListView lv = VisualUpwardSearch<ListView>(gvch);
          if (lv == null) return;
          GridView gv = lv.View as GridView;
          if (gv == null) return;

          EnableGridViewSortApplySort(lv, gv, gvc);
      }

      public static void EnableGridViewSortApplySort(
          ListView lv, GridView gv, GridViewColumn gvc)
      {
          bool isEnabled = GetEnableGridViewSort(lv);
          if (!isEnabled) return;

          string propertyName = GetGridViewSortPropertyName(gvc);
          if (string.IsNullOrEmpty(propertyName))
          {
              Binding b = gvc.DisplayMemberBinding as Binding;
              if (b != null && b.Path != null)
              {
                  propertyName = b.Path.Path;
              }

              if (string.IsNullOrEmpty(propertyName)) return;
          }

          ApplySort(lv.Items, propertyName);
          SetCurrentSortColumn(gv, gvc);
          CurrentSortColumnSetGlyph(gvc, lv);
      }

      public static void ApplySort(ICollectionView view, string propertyName)
      {
          if (string.IsNullOrEmpty(propertyName)) return;

          ListSortDirection lsd = ListSortDirection.Ascending;
          if (view.SortDescriptions.Count > 0)
          {
              SortDescription sd = view.SortDescriptions[0];
              if (sd.PropertyName.Equals(propertyName))
              {
                  if (sd.Direction == ListSortDirection.Ascending)
                  {
                      lsd = ListSortDirection.Descending;
                  }
                  else
                  {
                      lsd = ListSortDirection.Ascending;
                  }
              }
              view.SortDescriptions.Clear();
          }

          view.SortDescriptions.Add(new SortDescription(propertyName, lsd));
      }
      #endregion

      public static T VisualUpwardSearch<T>(DependencyObject source) 
          where T : DependencyObject
      {
          return VisualUpwardSearch(source, x => x is T) as T;
      }

      public static DependencyObject VisualUpwardSearch(
                          DependencyObject source, Predicate<DependencyObject> match)
      {
          DependencyObject returnVal = source;

          while (returnVal != null && !match(returnVal))
          {
              DependencyObject tempReturnVal = null;
              if (returnVal is Visual || returnVal is Visual3D)
              {
                  tempReturnVal = VisualTreeHelper.GetParent(returnVal);
              }
              if (tempReturnVal == null)
              {
                  returnVal = LogicalTreeHelper.GetParent(returnVal);
              }
              else
              {
                  returnVal = tempReturnVal;
              }
          }

          return returnVal;
      }
  }
}

Regular expression to match numbers with or without commas and decimals in text

Here is another construction which starts with the simplest number format and then, in a non-overlapping way, progressively adds more complex number formats:

Java regep:

(\d)|([1-9]\d+)|(\.\d+)|(\d\.\d*)|([1-9]\d+\.\d*)|([1-9]\d{0,2}(,\d{3})+(\.\d*)?)

As a Java String (note the extra \ needed to escape to \ and . since \ and . have special meaning in a regexp when on their own):

String myregexp="(\\d)|([1-9]\\d+)|(\\.\\d+)|(\\d\\.\\d*)|([1-9]\\d+\\.\\d*)|([1-9]\\d{0,2}(,\\d{3})+(\\.\\d*)?)";   

Explanation:

  1. This regexp has the form A|B|C|D|E|F where A,B,C,D,E,F are themselves regexps that do not overlap. Generally, I find it easier to start with the simplest possible matches, A. If A misses matches you want, then create a B that is a minor modification of A and includes a bit more of what you want. Then, based on B, create a C that catches more, etc. I also find it easier to create regexps that don't overlap; it is easier to understand a regexp with 20 simple non-overlapping regexps connected with ORs rather than a few regexps with more complex matching. But, each to their own!

  2. A is (\d) and matches exactly one of 0,1,2,3,4,5,6,7,8,9 which can't be simpler!

  3. B is ([1-9]\d+) and only matches numbers with 2 or more digits, the first excluding 0 . B matches exactly one of 10,11,12,... B does not overlap A but is a small modification of A.

  4. C is (.\d+) and only matches a decimal followed by one or more digits. C matches exactly one of .0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .00 .01 .02 ... . .23000 ... C allows trailing eros on the right which I prefer: if this is measurement data, the number of trailing zeros indicates the level of precision. If you don't want the trailing zeros on the right, change (.\d+) to (.\d*[1-9]) but this also excludes .0 which I think should be allowed. C is also a small modification of A.

  5. D is (\d.\d*) which is A plus decimals with trailing zeros on the right. D only matches a single digit, followed by a decimal, followed by zero or more digits. D matches 0. 0.0 0.1 0.2 ....0.01000...9. 9.0 9.1..0.0230000 .... 9.9999999999... If you want to exclude "0." then change D to (\d.\d+). If you want to exclude trailing zeros on the right, change D to (\d.\d*[1-9]) but this excludes 2.0 which I think should be included. D does not overlap A,B,or C.

  6. E is ([1-9]\d+.\d*) which is B plus decimals with trailing zeros on the right. If you want to exclude "13.", for example, then change E to ([1-9]\d+.\d+). E does not overlap A,B,C or D. E matches 10. 10.0 10.0100 .... 99.9999999999... Trailing zeros can be handled as in 4. and 5.

  7. F is ([1-9]\d{0,2}(,\d{3})+(.\d*)?) and only matches numbers with commas and possibly decimals allowing trailing zeros on the right. The first group ([1-9]\d{0,2}) matches a non-zero digit followed zero, one or two more digits. The second group (,\d{3})+ matches a 4 character group (a comma followed by exactly three digits) and this group can match one or more times (no matches means no commas!). Finally, (.\d*)? matches nothing, or matches . by itself, or matches a decimal . followed by any number of digits, possibly none. Again, to exclude things like "1,111.", change (.\d*) to (.\d+). Trailing zeros can be handled as in 4. or 5. F does not overlap A,B,C,D, or E. I couldn't think of an easier regexp for F.

Let me know if you are interested and I can edit above to handle the trailing zeros on the right as desired.

Here is what matches regexp and what does not:

0
1
02 <- invalid
20
22
003 <- invalid
030 <- invalid
300
033 <- invalid
303
330
333
0004 <- invalid
0040 <- invalid
0400 <- invalid
4000
0044 <- invalid
0404 <- invalid
0440 <- invalid
4004
4040
4400
0444 <- invalid
4044
4404
4440
4444
00005 <- invalid
00050 <- invalid
00500 <- invalid
05000 <- invalid
50000
00055 <- invalid
00505 <- invalid
00550 <- invalid
05050 <- invalid
05500 <- invalid
50500
55000
00555 <- invalid
05055 <- invalid
05505 <- invalid
05550 <- invalid
50550
55050
55500
. <- invalid
.. <- invalid
.0
0.
.1
1.
.00
0.0
00. <- invalid
.02
0.2
02. <- invalid
.20
2.0
20.
.22
2.2
22.
.000
0.00
00.0 <- invalid
000. <- invalid
.003
0.03
00.3 <- invalid
003. <- invalid
.030
0.30
03.0 <- invalid
030. <- invalid
.033
0.33
03.3 <- invalid
033. <- invalid
.303
3.03
30.3
303.
.333
3.33
33.3
333.
.0000
0.000
00.00 <- invalid
000.0 <- invalid
0000. <- invalid
.0004
0.0004
00.04 <- invalid
000.4 <- invalid
0004. <- invalid
.0044
0.044
00.44 <- invalid
004.4 <- invalid
0044. <- invalid
.0404
0.404
04.04 <- invalid
040.4 <- invalid
0404. <- invalid
.0444
0.444
04.44 <- invalid
044.4 <- invalid
0444. <- invalid
.4444
4.444
44.44
444.4
4444.
.00000
0.0000
00.000 <- invalid
000.00 <- invalid
0000.0 <- invalid
00000. <- invalid
.00005
0.0005
00.005 <- invalid
000.05 <- invalid
0000.5 <- invalid
00005. <- invalid
.00055
0.0055
00.055 <- invalid
000.55 <- invalid
0005.5 <- invalid
00055. <- invalid
.00505
0.0505
00.505 <- invalid
005.05 <- invalid
0050.5 <- invalid
00505. <- invalid
.00550
0.0550
00.550 <- invalid
005.50 <- invalid
0055.0 <- invalid
00550. <- invalid
.05050
0.5050
05.050 <- invalid
050.50 <- invalid
0505.0 <- invalid
05050. <- invalid
.05500
0.5500
05.500 <- invalid
055.00 <- invalid
0550.0 <- invalid
05500. <- invalid
.50500
5.0500
50.500
505.00
5050.0
50500.
.55000
5.5000
55.000
550.00
5500.0
55000.
.00555
0.0555
00.555 <- invalid
005.55 <- invalid
0055.5 <- invalid
00555. <- invalid
.05055
0.5055
05.055 <- invalid
050.55 <- invalid
0505.5 <- invalid
05055. <- invalid
.05505
0.5505
05.505 <- invalid
055.05 <- invalid
0550.5 <- invalid
05505. <- invalid
.05550
0.5550
05.550 <- invalid
055.50 <- invalid
0555.0 <- invalid
05550. <- invalid
.50550
5.0550
50.550
505.50
5055.0
50550.
.55050
5.5050
55.050
550.50
5505.0
55050.
.55500
5.5500
55.500
555.00
5550.0
55500.
.05555
0.5555
05.555 <- invalid
055.55 <- invalid
0555.5 <- invalid
05555. <- invalid
.50555
5.0555
50.555
505.55
5055.5
50555.
.55055
5.5055
55.055
550.55
5505.5
55055.
.55505
5.5505
55.505
555.05
5550.5
55505.
.55550
5.5550
55.550
555.50
5555.0
55550.
.55555
5.5555
55.555
555.55
5555.5
55555.
, <- invalid
,, <- invalid
1, <- invalid
,1 <- invalid
22, <- invalid
2,2 <- invalid
,22 <- invalid
2,2, <- invalid
2,2, <- invalid
,22, <- invalid
333, <- invalid
33,3 <- invalid
3,33 <- invalid
,333 <- invalid
3,33, <- invalid
3,3,3 <- invalid
3,,33 <- invalid
,,333 <- invalid
4444, <- invalid
444,4 <- invalid
44,44 <- invalid
4,444
,4444 <- invalid
55555, <- invalid
5555,5 <- invalid
555,55 <- invalid
55,555
5,5555 <- invalid
,55555 <- invalid
666666, <- invalid
66666,6 <- invalid
6666,66 <- invalid
666,666
66,6666 <- invalid
6,66666 <- invalid
66,66,66 <- invalid
6,66,666 <- invalid
,666,666 <- invalid
1,111.
1,111.11
1,111.110
01,111.110 <- invalid
0,111.100 <- invalid
11,11. <- invalid
1,111,.11 <- invalid
1111.1,10 <- invalid
01111.11,0 <- invalid
0111.100, <- invalid
1,111,111.
1,111,111.11
1,111,111.110
01,111,111.110 <- invalid
0,111,111.100 <- invalid
1,111,111.
1,1111,11.11 <- invalid
11,111,11.110 <- invalid
01,11,1111.110 <- invalid
0,111111.100 <- invalid
0002,22.2230 <- invalid
.,5.,., <- invalid
2.0,345,345 <- invalid
2.334.456 <- invalid

Dictionary returning a default value if the key does not exist

I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.

I wish this were just part of the base Dictionary class.

public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
  TValue _default;
  public TValue DefaultValue {
    get { return _default; }
    set { _default = value; }
  }
  public DictionaryWithDefault() : base() { }
  public DictionaryWithDefault(TValue defaultValue) : base() {
    _default = defaultValue;
  }
  public new TValue this[TKey key]
  {
    get { 
      TValue t;
      return base.TryGetValue(key, out t) ? t : _default;
    }
    set { base[key] = value; }
  }
}

Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Regex pattern inside SQL Replace function?

I think a simpler and faster approach is iterate by each character of the alphabet:

DECLARE @i int
SET @i = 0

WHILE(@i < 256)
BEGIN  

    IF char(@i) NOT IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')      

      UPDATE Table SET Column = replace(Column, char(@i), '')

    SET @i = @i + 1

END

Python Linked List

Sample of a doubly linked list (save as linkedlist.py):

class node:
    def __init__(self, before=None, cargo=None, next=None): 
        self._previous = before
        self._cargo = cargo 
        self._next  = next 

    def __str__(self):
        return str(self._cargo) or None 

class linkedList:
    def __init__(self): 
        self._head = None 
        self._length = 0

    def add(self, cargo):
        n = node(None, cargo, self._head)
        if self._head:
            self._head._previous = n
        self._head = n
        self._length += 1

    def search(self,cargo):
        node = self._head
        while (node and node._cargo != cargo):
            node = node._next
        return node

    def delete(self,cargo):
        node = self.search(cargo)
        if node:
            prev = node._previous
            nx = node._next
            if prev:
                prev._next = node._next
            else:
                self._head = nx
                nx._previous = None
            if nx:
                nx._previous = prev 
            else:
                prev._next = None
        self._length -= 1

    def __str__(self):
        print 'Size of linked list: ',self._length
        node = self._head
        while node:
            print node
            node = node._next

Testing (save as test.py):

from linkedlist import node, linkedList

def test():

    print 'Testing Linked List'

    l = linkedList()

    l.add(10)
    l.add(20)
    l.add(30)
    l.add(40)
    l.add(50)
    l.add(60)

    print 'Linked List after insert nodes:'
    l.__str__()

    print 'Search some value, 30:'
    node = l.search(30)
    print node

    print 'Delete some value, 30:'
    node = l.delete(30)
    l.__str__()

    print 'Delete first element, 60:'
    node = l.delete(60)
    l.__str__()

    print 'Delete last element, 10:'
    node = l.delete(10)
    l.__str__()


if __name__ == "__main__":
    test()

Output:

Testing Linked List
Linked List after insert nodes:
Size of linked list:  6
60
50
40
30
20
10
Search some value, 30:
30
Delete some value, 30:
Size of linked list:  5
60
50
40
20
10
Delete first element, 60:
Size of linked list:  4
50
40
20
10
Delete last element, 10:
Size of linked list:  3
50
40
20

Override valueof() and toString() in Java enum

The following is a nice generic alternative to valueOf()

public static RandomEnum getEnum(String value) {
  for (RandomEnum re : RandomEnum.values()) {
    if (re.description.compareTo(value) == 0) {
      return re;
    }
  }
  throw new IllegalArgumentException("Invalid RandomEnum value: " + value);
}

Fastest way to add an Item to an Array

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem

for more info Redim

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I was having a similar issue with a customer and none of the posted resolutions did the trick. I granted the "Log on as a batch job" permission via the Local Security Policy and that finally made the Central Administration web page come up properly.

How to deselect a selected UITableView cell?

Please check with the delegate method whether it is correct or not. For example;

-(void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

for

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Update Git branches from master

If you've been working on a branch on-and-off, or lots has happened in other branches while you've been working on something, it's best to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.

git checkout master
git pull
git checkout local_branch_name
git rebase master
git push --force # force required if you've already pushed

Notes:

  • Don't rebase branches that you've collaborated with others on.
  • You should rebase on the branch to which you will be merging which may not always be master.

There's a chapter on rebasing at http://git-scm.com/book/ch3-6.html, and loads of other resources out there on the web.

Cloning a private Github repo

Cloning Private Repository using HTTPS in Year 2020

If maintainer of repository has given Developer access to you on his private library ,you need to first login to https://gitlab.com/users/sign_in with user for which you have received invitation,you will be prompted to change your password,once you change your password then you can successfully clone repository ,pull and push changes to it.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

These instructions are for windows machine with a single user profile for AWS. Make sure your ~/.aws/credentials file looks like this

[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

I had to set the AWS_DEFAULT_PROFILEenvironment variable to profile_name found in your credentials.
Then my python was able to connect. eg from here

import boto3

# Let's use Amazon S3
s3 = boto3.resource('s3')

# Print out bucket names
for bucket in s3.buckets.all():
    print(bucket.name)

WinForms DataGridView font size

Go to designer.cs file of the form in which you have the grid view and comment the following line: - //this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;

if you are using vs 2008 or .net framework 3.5 as it will be by default applied to alternating rows.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

After changing https to http within gitbox app, it worked for me.

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

Get first word of string

const getFirstWord = string => {
    const firstWord = [];
    for (let i = 0; i < string.length; i += 1) {
        if (string[i] === ' ') break;
        firstWord.push(string[i]);
    }
    return firstWord.join('');
};
console.log(getFirstWord('Hello World'));

or simplify it:

const getFirstWord = string => {
    const words = string.split(' ');
    return words[0];
};
console.log(getFirstWord('Hello World'));

How do I add a newline to a TextView in Android?

I think this has something to do with your HTM.fromHtml(subTitle) call: a "\n" doesn't mean bupkis to HTML. Try <br/> instead of "\n".

LINQ Inner-Join vs Left-Join

Here's a good blog post that's just been posted by Fabrice (author of LINQ in Action) which covers the material in the question that I asked. I'm putting it here for reference as readers of the question will find this useful.

Converting LINQ queries from query syntax to method/operator syntax

Comparing two byte arrays in .NET

Span<T> offers an extremely competitive alternative without having to throw confusing and/or non-portable fluff into your own application's code base:

// byte[] is implicitly convertible to ReadOnlySpan<byte>
static bool ByteArrayCompare(ReadOnlySpan<byte> a1, ReadOnlySpan<byte> a2)
{
    return a1.SequenceEqual(a2);
}

The (guts of the) implementation as of .NET 5.0.0 can be found here.

I've revised @EliArbel's gist to add this method as SpansEqual, drop most of the less interesting performers in others' benchmarks, run it with different array sizes, output graphs, and mark SpansEqual as the baseline so that it reports how the different methods compare to SpansEqual.

The below numbers are from the results, lightly edited to remove "Error" column.

|        Method |  ByteCount |               Mean |            StdDev | Ratio | RatioSD |
|-------------- |----------- |-------------------:|------------------:|------:|--------:|
|    SpansEqual |         15 |           4.629 ns |         0.0289 ns |  1.00 |    0.00 |
|  LongPointers |         15 |           4.598 ns |         0.0416 ns |  0.99 |    0.01 |
|      Unrolled |         15 |          18.199 ns |         0.0291 ns |  3.93 |    0.02 |
| PInvokeMemcmp |         15 |           9.872 ns |         0.0441 ns |  2.13 |    0.02 |
|               |            |                    |                   |       |         |
|    SpansEqual |       1026 |          19.965 ns |         0.0880 ns |  1.00 |    0.00 |
|  LongPointers |       1026 |          63.005 ns |         0.5217 ns |  3.16 |    0.04 |
|      Unrolled |       1026 |          38.731 ns |         0.0166 ns |  1.94 |    0.01 |
| PInvokeMemcmp |       1026 |          40.355 ns |         0.0202 ns |  2.02 |    0.01 |
|               |            |                    |                   |       |         |
|    SpansEqual |    1048585 |      43,761.339 ns |        30.8744 ns |  1.00 |    0.00 |
|  LongPointers |    1048585 |      59,585.479 ns |        17.3907 ns |  1.36 |    0.00 |
|      Unrolled |    1048585 |      54,646.243 ns |        35.7638 ns |  1.25 |    0.00 |
| PInvokeMemcmp |    1048585 |      55,198.289 ns |        23.9732 ns |  1.26 |    0.00 |
|               |            |                    |                   |       |         |
|    SpansEqual | 2147483591 | 240,607,692.857 ns | 2,733,489.4894 ns |  1.00 |    0.00 |
|  LongPointers | 2147483591 | 238,223,478.571 ns | 2,033,769.5979 ns |  0.99 |    0.02 |
|      Unrolled | 2147483591 | 236,227,340.000 ns | 2,189,627.0164 ns |  0.98 |    0.00 |
| PInvokeMemcmp | 2147483591 | 238,724,660.000 ns | 3,726,140.4720 ns |  0.99 |    0.02 |

I was surprised to see SpansEqual not come out on top for the max-array-size methods, but the difference is so minor that I don't think it'll ever matter.

My system info:

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042
Intel Core i7-6850K CPU 3.60GHz (Skylake), 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.100
  [Host]     : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT
  DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT

Setting table column width

Try this instead.

<table style="width: 100%">
    <tr>
        <th style="width: 20%">
           column 1
        </th>
        <th style="width: 40%">
           column 2
        </th>
        <th style="width: 40%">
           column 3
        </th>
    </tr>
    <tr>
        <td style="width: 20%">
           value 1
        </td>
        <td style="width: 40%">
           value 2
        </td>
        <td style="width: 40%">
           value 3
        </td>
    </tr>
</table>

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

Difference between Spring MVC and Spring Boot

Think this way:

Spring MVC is a web based framework to implement the MVC architecture.

Spring Boot is a tool oriented to the programmer. Programmer must focus on programming and tool must focus on configurations. So we don't need to wast our time configuring a bunch of xml to make a simple 'Hello world'.

Comparing strings by their alphabetical order

String.compareTo might or might not be what you need.

Take a look at this link if you need localized ordering of strings.

How can I change the Y-axis figures into percentages in a barplot?

Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:

scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))

This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).

Looping through JSON with node.js

Not sure if it helps, but it looks like there might be a library for async iteration in node hosted here:

https://github.com/caolan/async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, forEach…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

Inserting a PDF file in LaTeX

There is an option without additional packages that works under pdflatex

Adapt this code

\begin{figure}[h]
    \centering
    \includegraphics[width=\ScaleIfNeeded]{figuras/diagrama-spearman.pdf}
    \caption{Schematical view of Spearman's theory.}
\end{figure}

"diagrama-spearman.pdf" is a plot generated with TikZ and this is the code (it is another .tex file different from the .tex file where I want to insert a pdf)

\documentclass[border=3mm]{standalone}
\usepackage[applemac]{inputenc}
\usepackage[protrusion=true,expansion=true]{microtype}
\usepackage[bb=lucida,bbscaled=1,cal=boondoxo]{mathalfa}
\usepackage[stdmathitalics=true,math-style=iso,lucidasmallscale=true,romanfamily=bright]{lucimatx}
\usepackage{tikz}
\usetikzlibrary{intersections}
\newcommand{\at}{\makeatletter @\makeatother}

\begin{document}

\begin{tikzpicture}
\tikzset{venn circle/.style={draw,circle,minimum width=5cm,fill=#1,opacity=1}}
\node [venn circle = none, name path=A] (A) at (45:2cm) { };
\node [venn circle = none, name path=B] (B) at (135:2cm) { };
\node [venn circle = none, name path=C] (C) at (225:2cm) { };
\node [venn circle = none, name path=D] (D) at (315:2cm) { };
\node[above right] at (barycentric cs:A=1) {logical}; 
\node[above left] at (barycentric cs:B=1) {mechanical}; 
\node[below left] at (barycentric cs:C=1) {spatial}; 
\node[below right] at (barycentric cs:D=1) {arithmetical}; 
\node at (0,0) {G};    
\end{tikzpicture}

\end{document} 

This is the diagram I included

enter image description here

How can I scroll a web page using selenium webdriver in python?

For my purpose, I wanted to scroll down more, keeping the windows position in mind. My solution was similar and used window.scrollY

driver.execute_script("window.scrollTo(0, window.scrollY + 200)")

which will go to the current y scroll position + 200

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Instead of below code:

$(this).attr("src").replace(urlRelative, urlAbsolute);

Use this:

$(this).attr("src",urlAbsolute);

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

Using <style> tags in the <body> with other HTML

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

Push Notifications in Android Platform

(cross-posting from an answer I gave to a similar question - Does Android support near real time push notification? )

I recently started playing with MQTT http://mqtt.org for Android as a way of doing this sort of thing (i.e. push notification that is not SMS but data driven, almost immediate message delivery, not polling, etc.)

I have a blog post with background information on this in case it's helpful

http://dalelane.co.uk/blog/?p=938

(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)

How to get first character of a string in SQL?

If you search the first char of string in Sql string

SELECT CHARINDEX('char', 'my char')

=> return 4

How to make div occupy remaining height?

You could use calc function to calculate remaining height for 2nd div.

_x000D_
_x000D_
*{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#div1{_x000D_
  height: 50px;_x000D_
  background: skyblue;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
  height: calc(100vh - 50px);_x000D_
  background: blue;_x000D_
}
_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>
_x000D_
_x000D_
_x000D_

jQuery ajax upload file in asp.net mvc

If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button

Convert a file path to Uri in Android

Normal answer for this question if you really want to get something like content//media/external/video/media/18576 (e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4:

MediaScannerConnection.scanFile(this,
          new String[] { file.getAbsolutePath() }, null,
          new MediaScannerConnection.OnScanCompletedListener() {
      public void onScanCompleted(String path, Uri uri) {
          Log.i("onScanCompleted", uri.getPath());
      }
 });

Accepted answer is wrong (cause it will not return content//media/external/video/media/*)

Uri.fromFile(file).toString() only returns something like file///storage/emulated/0/* which is a simple absolute path of a file on the sdcard but with file// prefix (scheme)

You can also get content uri using MediaStore database of Android

TEST (what returns Uri.fromFile and what returns MediaScannerConnection):

File videoFile = new File("/storage/emulated/0/video.mp4");

Log.i(TAG, Uri.fromFile(videoFile).toString());

MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
        (path, uri) -> Log.i(TAG, uri.toString()));

Output:

I/Test: file:///storage/emulated/0/video.mp4

I/Test: content://media/external/video/media/268927

jQuery click event on radio button doesn't get fired

A different way

$("#inline_content input[name='type']").change(function () {
    if ($(this).val() == "walk_in" && $(this).is(":checked")) {
        $('#select-table > .roomNumber').attr('enabled', false);
    }
});

Demo - http://jsfiddle.net/cB6xV/

Markdown and image alignment

You can embed HTML in Markdown, so you can do something like this:

<img style="float: right;" src="whatever.jpg">

Continue markdown text...

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Jquery Change Height based on Browser Size/Resize

I have the feeling that the check should be different

new: h < 768 || w < 1024

How can I change image tintColor in iOS and WatchKit

iOS
For an iOS app, in Swift 3, 4 or 5:

theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red

For Swift 2:

theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
theImageView.tintColor = UIColor.redColor()

Meanwhile, the modern Objective-C solution is:

theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];

Watchkit
In WatchKit for Apple Watch apps, you can set the tint color for a template image.

  1. You must add your image to an Asset Catalog in your WatchKit App, and set the image set to be rendered as a Template Image in the Attributes Inspector. Unlike for an iPhone app, you cannot set the template rendering in code in the WatchKit Extension at present.
  2. Set that image to be used in your WKInterfaceImage in interface builder for your app
  3. Create an IBOutlet in your WKInterfaceController for the WKInterfaceImage called 'theImage'...

To then set the tint color in Swift 3 or 4:

theImage.setTintColor(UIColor.red)

Swift 2:

theImage.setTintColor(UIColor.redColor())

To then set the tint color in Objective-C:

[self.theImage setTintColor:[UIColor redColor]];

If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied. If you have not set a Global Tint, theImage will be tinted light blue by default when used as a template image.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

Just try this line:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

after:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

CSS background-size: cover replacement for Mobile Safari

There are answers over the net that try to solve this, however none of them functioned correctly for me. Goal: put a background image on the body and have background-size: cover; work mobile, without media queries, overflows, or hacky z-index: -1; position: absolute; overlays.

Here is what I did to solve this. It works on Chrome on Android even when keyboard drawer is active. If someone wants to test iPhone that would be cool:

body {
    background: #FFFFFF url('../image/something.jpg') no-repeat fixed top center;
    background-size: cover;
    -webkit-background-size: cover; /* safari may need this */
}

Here is the magic. Treat html like a wrapper with a ratio enforced height relative to the actual viewport. You know the classic responsive tag <meta name="viewport" content="width=device-width, initial-scale=1">? This is why the vh is used. Also, on the surface it would seem like body should get these rules, and it may look ok...until a change of height like when the keyboard opens up.

html {
    height: 100vh; /* set viewport constraint */
    min-height: 100%; /* enforce height */
}

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

C++: Converting Hexadecimal to Decimal

Here is a solution using strings and converting it to decimal with ASCII tables:

#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
    unsigned long result = 0;
    for (int i=0; i<hex.length(); i++) {
        if (hex[i]>=48 && hex[i]<=57)
        {
            result += (hex[i]-48)*pow(16,hex.length()-i-1);
        } else if (hex[i]>=65 && hex[i]<=70) {
            result += (hex[i]-55)*pow(16,hex.length( )-i-1);
        } else if (hex[i]>=97 && hex[i]<=102) {
            result += (hex[i]-87)*pow(16,hex.length()-i-1);
        }
    }
    return result;
}

int main(int argc, const char * argv[]) {
    string hex_str;
    cin >> hex_str;
    cout << hex2dec(hex_str) << endl;
    return 0;
}

How to access POST form fields

Use express-fileupload package:

var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')

app.use(fileUpload());

app.post('/', function(req, res) {
  var email = req.body.email;
  res.send('<h1>Email :</h1> '+email);
});

http.listen(3000, function(){
  console.log('Running Port:3000');
});

Delete with Join in MySQL

Single Table Delete:

In order to delete entries from posts table:

DELETE ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from projects table:

DELETE pj 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from clients table:

DELETE C
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

Multiple Tables Delete:

In order to delete entries from multiple tables out of the joined results you need to specify the table names after DELETE as comma separated list:

Suppose you want to delete entries from all the three tables (posts,projects,clients) for a particular client :

DELETE C,pj,ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

How to catch a unique constraint error in a PL/SQL block?

EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         UPDATE

How Do I Uninstall Yarn

If you installed with brew, try brew uninstall yarn at terminal prompt. Also remember to remove yarn path info in your .bash_profile.

Check if an array contains duplicate values

function hasNoDuplicates(arr) { return arr.every(num => arr.indexOf(num) === arr.lastIndexOf(num)); }

hasNoDuplicates accepts an array and returns true if there are no duplicate values. If there are any duplicates, the function returns false.

PHP function to make slug (URL string)

Since gTLDs and IDNs are becoming more and more used I cannot see why URL shouldn't contain Andrés.

Just rawurlencode $URL you want instead. Most browsers show UTF-8 characters in URLs (not some ancient IE6 maybe) and bit.ly / goo.gl can be used to make it short in cases like Russian and Arabic if need may be for ad purposes or just write them in ads like user would write them on browser URL.

Only difference is spaces " " it might be good idea to replace them with "-" and "/" if you don't want to allow those.

<?php
function slugify($url)
{
    $url = trim($url);

    $url = str_replace(" ","-",$url);
    $url = str_replace("/","-slash-",$url);
    $url = rawurlencode($url);
}
?>

Url as encoded http://www.hurtta.com/RU/%D0%9F%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B/

Url as written http://www.hurtta.com/RU/????????/

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

Accessing private member variables from prototype-defined functions

There is a very simple way to do this

function SharedPrivate(){
  var private = "secret";
  this.constructor.prototype.getP = function(){return private}
  this.constructor.prototype.setP = function(v){ private = v;}
}

var o1 = new SharedPrivate();
var o2 = new SharedPrivate();

console.log(o1.getP()); // secret
console.log(o2.getP()); // secret
o1.setP("Pentax Full Frame K1 is on sale..!");
console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
o2.setP("And it's only for $1,795._");
console.log(o1.getP()); // And it's only for $1,795._

JavaScript prototypes are golden.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

first of all: as far as i know placing dialog inside a tabview is a bad practice... you better take it out...

and now to your question:

sorry, took me some time to get what exactly you wanted to implement,

did at my web app myself just now, and it works

as I sayed before place the p:dialog out side the `p:tabView ,

leave the p:dialog as you initially suggested :

<p:dialog modal="true" widgetVar="dlg">
    <h:panelGrid id="display">
        <h:outputText value="Name:" />
        <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
    </h:panelGrid>
</p:dialog>   

and the p:commandlink should look like this (all i did is to change the update attribute)

<p:commandLink update="display" oncomplete="dlg.show()">
    <f:setPropertyActionListener value="#{lndInstrument}" 
        target="#{instrumentBean.selectedInstrument}" />
    <h:outputText value="#{lndInstrument.name}" />
</p:commandLink>  

the same works in my web app, and if it does not work for you , then i guess there is something wrong in your java bean code...

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

This worked for me.

<table>
  <tr>
    <td *ngFor="#group of groups">
       <h1>{{group.name}}</h1>
   </td>
  </tr>
</table>

How to determine one year from now in Javascript

In very simple way. use this code.

// define function 
function nextYearDate(date1) {
    var date2 = new Date(date1);
    var date3 = date2.setDate(date2.getDate() - 1);
    var date = new Date(date3);
    var day = date.getDate();
    var month = date.getMonth()+1;
    var year = date.getFullYear()+1;
    var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
    $("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />

<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Confirm Password with jQuery Validate

Remove the required: true rule.

Demo: Fiddle

jQuery('.validatedForm').validate({
            rules : {
                password : {
                    minlength : 5
                },
                password_confirm : {
                    minlength : 5,
                    equalTo : "#password"
                }
            }

Bootstrap carousel multiple frames at once

I had the same problem and the solutions described here worked well. But I wanted to support window size (and layout) changes. The result is a small library that solves all the calculation. Check it out here: https://github.com/SocialbitGmbH/BootstrapCarouselPageMerger

To make the script work, you have to add a new <div> wrapper with the class .item-content directly into your .item <div>. Example:

<div class="carousel slide multiple" id="very-cool-carousel" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
        <div class="item active">
            <div class="item-content">
                First page
            </div>
        </div>
        <div class="item active">
            <div class="item-content">
                Second page
            </div>
        </div>
    </div>
</div>

Usage of this library:

socialbitBootstrapCarouselPageMerger.run('div.carousel');

To change the settings:

socialbitBootstrapCarouselPageMerger.settings.spaceCalculationFactor = 0.82;

Example:

As you can see, the carousel gets updated to show more controls when you resize the window. Check out the watchWindowSizeTimeout setting to control the timeout for reacting to window size changes.

How to get Chrome to allow mixed content?

In Windows open the Run window (Win + R):

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe  --allow-running-insecure-content

In OS-X Terminal.app run the following command +space:

open /Applications/Google\ Chrome.app --args --allow-running-insecure-content

Note: You seem to be able to add the argument --allow-running-insecure-content to bypass this for development. But its not a recommended solution.

What is the official name for a credit card's 3 digit code?

From Wikipedia,

The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.

The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.

There are actually several types of security codes:

* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.

The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)

The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.

How do I set up a private Git repository on GitHub? Is it even possible?

GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.

You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.

python selenium click on button

The following debugging process helped me solve a similar issue.

with open("output_init.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))


xpath1 = "the xpath of the link you want to click on"
destination_page_link = driver.find_element_by_xpath(xpath1)
destination_page_link.click()


with open("output_dest.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))

You should then have two textfiles with the initial page you were on ('output_init.txt') and the page you were forwarded to after clicking the button ('output_dest.txt'). If they're the same, then yup, your code did not work. If they aren't, then your code worked, but you have another issue. The issue for me seemed to be that the necessary javascript that transformed the content to produce my hook was not yet executed.

Your options as I see it:

  1. Have the driver execute the javascript and then call your find element code. Look for more detailed answers on this on stackoverflow, as I didn't follow this approach.
  2. Just find a comparable hook on the 'output_dest.txt' that will produce the same result, which is what I did.
  3. Try waiting a bit before clicking anything:

xpath2 = "your xpath that you are going to click on"

WebDriverWait(driver, timeout=5).until(lambda x: x.find_element_by_xpath(xpath2))

The xpath approach isn't necessarily better, I just prefer it, you can also use your selector approach.

How good is Java's UUID.randomUUID?

Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.

Do programmers routinely dismiss as "impossible" other events that can and do occur?

When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.

Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).

This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!

How to check if a registry value exists using C#?

  RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false);
        if (rkSubKey == null)
        {
           // It doesn't exist
        }
        else
        {
           // It exists and do something if you want to
         }

How to remove the left part of a string?

I guess this what you are exactly looking for

    def findPath(i_file) :
        lines = open( i_file ).readlines()
        for line in lines :
            if line.startswith( "Path=" ):
                output_line=line[(line.find("Path=")+len("Path=")):]
                return output_line

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

How to solve static declaration follows non-static declaration in GCC C code?

I have had this issue in a case where the static function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.

What does "to stub" mean in programming?

"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."

From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones

Choose File Dialog

You just need to override onCreateDialog in an Activity.

//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList() {
    try {
        mPath.mkdirs();
    }
    catch(SecurityException e) {
        Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(mPath.exists()) {
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                return filename.contains(FTYPE) || sel.isDirectory();
            }

        };
        mFileList = mPath.list(filter);
    }
    else {
        mFileList= new String[0];
    }
}

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    switch(id) {
        case DIALOG_LOAD_FILE:
            builder.setTitle("Choose your file");
            if(mFileList == null) {
                Log.e(TAG, "Showing file picker before loading the file list");
                dialog = builder.create();
                return dialog;
            }
            builder.setItems(mFileList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mChosenFile = mFileList[which];
                    //you can do stuff with the file here too
                }
            });
            break;
    }
    dialog = builder.show();
    return dialog;
}

How to align footer (div) to the bottom of the page?

This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.

<style type="text/css">
  #footer {
    position : absolute;
    bottom : 0;
    height : 40px;
    margin-top : 40px;
  }
</style>
<div id="footer">I am footer</div>

The height and margin-top should be the same so that the footer doesnt show over the content.

Chrome sendrequest error: TypeError: Converting circular structure to JSON

For my case I was getting that error when I was using async function on my server-side to fetch documents using mongoose. It turned out that the reason was I forgot to put await before calling find({}) method. Adding that part fixed my issue.

throw checked Exceptions from mocks with Mockito

A workaround is to use a willAnswer() method.

For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:

given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); });

The equivalent for plain Mockito would to use the doAnswer method

passing form data to another HTML page

You need the get the values from the query string (since you dont have a method set, your using GET by default)

use the following tutorial.

http://papermashup.com/read-url-get-variables-withjavascript/

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

"Invalid JSON primitive" in Ajax processing

Here dataTpe is "json" so, data/reqParam must be in the form of string while calling API, many as much as object as you want but at last inside $.ajax's data stringify the object.

             let person= {  name: 'john',
                age: 22
            };

           var personStr = JSON.stringify(person); 

            $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: JSON.stringify( { param1: personStr } ),
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");

        },
        error: function (error) {
            console.log("error found",error);
        }
    });

OR,

       $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: personStr,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");

        },
        error: function (error) {
            console.log("error found",error);
        }
    });