Programs & Examples On #Nidaqmx

nidaqmx is shorthand for National Instruments (NI) Data Acquisition. NI has developed several software products for using their hardware, e.g. LabVIEW. They also have released an extensive C header file and a dll to facilitate use of their hardware in other user software (Measurement Studio). Examples in several flavors of C, visualBasic, and Python can easily be found on the Web.

How to delete a stash created with git stash create?

git stash           // create stash,
git stash push -m "message" // create stash with msg,
git stash apply         // to apply stash,
git stash apply indexno // to apply  specific stash, 
git stash list          //list stash,
git stash drop indexno      //to delete stash,
git stash pop indexno,
git stash pop = stash drop + stash apply
git stash clear         //clear all your local stashed code

Laravel whereIn OR whereIn

You have a orWhereIn function in Laravel. It takes the same parameters as the whereIn function.

It's not in the documentation but you can find it in the laravel API. http://laravel.com/api/4.1/

That should give you this:

$query-> orWhereIn('products.value', $f);

How to check visibility of software keyboard in Android?

There's a hidden method can help for this, InputMethodManager.getInputMethodWindowVisibleHeight. But I don't know why it's hidden.

import android.content.Context
import android.os.Handler
import android.view.inputmethod.InputMethodManager

class SoftKeyboardStateWatcher(private val ctx: Context) {
  companion object {
    private const val DELAY = 10L
  }

  private val handler = Handler()
  private var isSoftKeyboardOpened: Boolean = false

  private val height: Int
    get() {
      val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      val method = imm.javaClass.getMethod("getInputMethodWindowVisibleHeight")
      method.isAccessible = true
      return method.invoke(imm) as Int
    }

  private val task: Runnable by lazy {
    Runnable {
      start()
      if (!isSoftKeyboardOpened && height > 0) {
        isSoftKeyboardOpened = true
        notifyOnSoftKeyboardOpened(height)
      } else if (isSoftKeyboardOpened && height == 0) {
        isSoftKeyboardOpened = false
        notifyOnSoftKeyboardClosed()
      }
    }
  }

  var listener: SoftKeyboardStateListener? = null

  interface SoftKeyboardStateListener {
    fun onSoftKeyboardOpened(keyboardHeightInPx: Int)
    fun onSoftKeyboardClosed()
  }

  fun start() {
    handler.postDelayed(task, DELAY)
  }

  fun stop() {
    handler.postDelayed({
      if (!isSoftKeyboardOpened) handler.removeCallbacks(task)
    }, DELAY * 10)
  }

  private fun notifyOnSoftKeyboardOpened(keyboardHeightInPx: Int) {
    listener?.onSoftKeyboardOpened(keyboardHeightInPx)
  }

  private fun notifyOnSoftKeyboardClosed() {
    listener?.onSoftKeyboardClosed()
  }
}

Python check if website exists

from urllib2 import Request, urlopen, HTTPError, URLError

user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
        page_open = urlopen(req)
except HTTPError, e:
        print e.code
except URLError, e:
        print e.reason
else:
        print 'ok'

To answer the comment of unutbu:

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source

z-index issue with twitter bootstrap dropdown menu

I had the same problem, in my case because i forgot this in my NavBar style: overflow: hidden;

Difference between Destroy and Delete

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

How can I find WPF controls by name or type?

You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}

Call it like this:

Window owner = UIHelper.FindVisualParent<Window>(myControl);

How to get height of entire document with JavaScript?

Document sizes are a browser compatibility nightmare because, although all browsers expose clientHeight and scrollHeight properties, they don't all agree how the values are calculated.

There used to be a complex best-practice formula around for how you tested for correct height/width. This involved using document.documentElement properties if available or falling back on document properties and so on.

The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one. This is basically what jQuery does:

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.

Note that testing the height of the document before the document is ready will always result in a 0. Also, if you load more stuff in, or the user resizes the window, you may need to re-test. Use onload or a document ready event if you need this at load time, otherwise just test whenever you need the number.

How can I check whether Google Maps is fully loaded?

In my case, Tile Image loaded from remote url and tilesloaded event was triggered before render the image.

I solved with following dirty way.

var tileCount = 0;
var options = {
    getTileUrl: function(coord, zoom) {
        tileCount++;
        return "http://posnic.com/tiles/?param"+coord;
    },
    tileSize: new google.maps.Size(256, 256),
    opacity: 0.5,
    isPng: true
};
var MT = new google.maps.ImageMapType(options);
map.overlayMapTypes.setAt(0, MT);
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    var checkExist = setInterval(function() {
        if ($('#map_canvas > div > div > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div > div').length === tileCount) {
            callyourmethod();
            clearInterval(checkExist);
        }
    }, 100); // check every 100ms
});

How do you log all events fired by an element in jQuery?

Here is a non-jquery way to monitor events in the console with your code and without the use of monitorEvents() because that only works in Chrome Developer Console. You can also choose to not monitor certain events by editing the no_watch array.

    function getEvents(obj) {
    window["events_list"] = [];
    var no_watch = ['mouse', 'pointer']; // Array of event types not to watch
    var no_watch_reg = new RegExp(no_watch.join("|"));

    for (var prop in obj) {
        if (prop.indexOf("on") === 0) {
            prop = prop.substring(2); // remove "on" from beginning
            if (!prop.match(no_watch_reg)) {
                window["events_list"].push(prop);
                window.addEventListener(prop, function() {
                    console.log(this.event); // Display fired event in console
                } , false);
            }
        }
    }
    window["events_list"].sort(); // Alphabetical order 

}

getEvents(document); // Put window, document or any html element here
console.log(events_list); // List every event on element

PHP preg replace only allow numbers

I think you're saying you want to remove all non-numeric characters. If so, \D means "anything that isn't a digit":

preg_replace('/\D/', '', $c)

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Swift: Display HTML data in a label or textView

Add this extension to convert your html code to a regular string:

    extension String {

        var html2AttributedString: NSAttributedString? {
            guard
                let data = dataUsingEncoding(NSUTF8StringEncoding)
            else { return nil }
            do {
                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
            } catch let error as NSError {
                print(error.localizedDescription)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
}

And then you show your String inside an UITextView Or UILabel

textView.text = yourString.html2String or

label.text = yourString.html2String

Difference between static class and singleton pattern?

What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.

Where are static variables stored in C and C++?

When a program is loaded into memory, it’s organized into different segments. One of the segment is DATA segment. The Data segment is further sub-divided into two parts:

Initialized data segment: All the global, static and constant data are stored here.
Uninitialized data segment(BSS): All the uninitialized data are stored in this segment.

Here is a diagram to explain this concept:

enter image description here


here is very good link explaining these concepts:

http://www.inf.udec.cl/~leo/teoX.pdf

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

I was having this same issue and I resolved it in the following way...

I have the NVIDIA "Tegra Android Development Pack" installed and it seems to also have a version of mysysgit.exe with it. TortoiseGit automatically found that installation location (instead of the standard git installation) and auto-populated it in the settings menu.

To correct this, go to: "Settings -> General" and there is a field for the path to mysysgit.exe. Make sure this is pointing to the correct installation.

C++ Pass A String

You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?

void print(std::string input)
{
    cout << input << endl;
} 
int main()
{
    print("yo");
}

It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input) then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

Getting the screen resolution using PHP

JS:

$.ajax({
    url: "ajax.php",
    type: "POST",
    data: "width=" + $("body").width(),
    success: function(msg) {

        return true;
    }
});

ajax.php

if(!empty($_POST['width']))
    $width = (int)$_POST['width'];

How to create a String with carriage returns?

The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")

ant build.xml file doesn't exist

You have invoked Ant with the verbose (-v) mode but the default buildfile build.xml does not exist. Nor have you specified any other buildfile for it to use.

I would say your Ant installation is fine.

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Remove duplicates from a list of objects based on property in Java 8

If order does not matter and when it's more performant to run in parallel, Collect to a Map and then get values:

employee.stream().collect(Collectors.toConcurrentMap(Employee::getId, Function.identity(), (p, q) -> p)).values()

Mime type for WOFF fonts?

IIS automatically defined .ttf as application/octet-stream which seems to work fine and fontshop recommends .woff to be defined as application/octet-stream

How to tackle daylight savings using TimeZone in Java

In java, DateFormatter by default uses DST,To avoid day Light saving (DST) you need to manually do a trick,
first you have to get the DST offset i.e. for how many millisecond DST applied, for ex somewhere DST is also for 45 minutes and for some places it is for 30 min
but in most cases DST is of 1 hour
you have to use Timezone object and check with the date whether it is falling under DST or not and then you have to manually add offset of DST into it. for eg:

 TimeZone tz = TimeZone.getTimeZone("EST");
 boolean isDST = tz.inDaylightTime(yourDateObj);
 if(isDST){
 int sec= tz.getDSTSavings()/1000;// for no. of seconds
 Calendar cal= Calendar.getInstance();
 cal.setTime(yourDateObj);
 cal.add(Calendar.Seconds,sec);
 System.out.println(cal.getTime());// your Date with DST neglected
  }

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

How to set Google Chrome in WebDriver

Mac OS: You have to install ChromeDriver first:

brew cask install chromedriver

It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.

Send multiple checkbox data to PHP via jQuery ajax()

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

How to start Activity in adapter?

If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.

btnInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                intent.setData(Uri.parse(link));
                context.startActivity(intent);
            }
        });

overlay two images in android to set an imageview

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

You're getting into looping most likely due to these rules:

RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

Just comment it out and try again in a new browser.

When should I use mmap for file access?

In addition to other nice answers, a quote from Linux system programming written by Google's expert Robert Love:

Advantages of mmap( )

Manipulating files via mmap( ) has a handful of advantages over the standard read( ) and write( ) system calls. Among them are:

  • Reading from and writing to a memory-mapped file avoids the extraneous copy that occurs when using the read( ) or write( ) system calls, where the data must be copied to and from a user-space buffer.

  • Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory.

  • When multiple processes map the same object into memory, the data is shared among all the processes. Read-only and shared writable mappings are shared in their entirety; private writable mappings have their not-yet-COW (copy-on-write) pages shared.

  • Seeking around the mapping involves trivial pointer manipulations. There is no need for the lseek( ) system call.

For these reasons, mmap( ) is a smart choice for many applications.

Disadvantages of mmap( )

There are a few points to keep in mind when using mmap( ):

  • Memory mappings are always an integer number of pages in size. Thus, the difference between the size of the backing file and an integer number of pages is "wasted" as slack space. For small files, a significant percentage of the mapping may be wasted. For example, with 4 KB pages, a 7 byte mapping wastes 4,089 bytes.

  • The memory mappings must fit into the process' address space. With a 32-bit address space, a very large number of various-sized mappings can result in fragmentation of the address space, making it hard to find large free contiguous regions. This problem, of course, is much less apparent with a 64-bit address space.

  • There is overhead in creating and maintaining the memory mappings and associated data structures inside the kernel. This overhead is generally obviated by the elimination of the double copy mentioned in the previous section, particularly for larger and frequently accessed files.

For these reasons, the benefits of mmap( ) are most greatly realized when the mapped file is large (and thus any wasted space is a small percentage of the total mapping), or when the total size of the mapped file is evenly divisible by the page size (and thus there is no wasted space).

Remove HTML Tags in Javascript with Regex

The way I do it is practically a one-liner.

The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.

Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.

I realize this question is old, I just thought my solution was unique and wanted to share. :)

function getTextFromString(htmlString) {
    return document
        .createRange()
        // Creates a fragment and turns the supplied string into HTML nodes
        .createContextualFragment(htmlString)
        // Gets the text from the fragment
        .textContent
        // Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
        .replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
        // Trims off any extra space on either end of the string
        .trim();
}

var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');

alert(cleanString);

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

The problem is with the string

"C:\Users\Eric\Desktop\beeline.txt"

Here, \U in "C:\Users... starts an eight-character Unicode escape, such as \U00014321. In your code, the escape is followed by the character 's', which is invalid.

You either need to duplicate all backslashes:

"C:\\Users\\Eric\\Desktop\\beeline.txt"

Or prefix the string with r (to produce a raw string):

r"C:\Users\Eric\Desktop\beeline.txt"

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

Adding an onclick event to a table row

selectRowToInput();
function selectRowToInput(){
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
    var currentRow = table.rows[i];
    currentRow.onclick = function() {

       rows=this.rowIndex;
        console.log(rows);  
    };
}

}

How to use a decimal range() step value?

Suprised no-one has yet mentioned the recommended solution in the Python 3 docs:

See also:

  • The linspace recipe shows how to implement a lazy version of range that suitable for floating point applications.

Once defined, the recipe is easy to use and does not require numpy or any other external libraries, but functions like numpy.linspace(). Note that rather than a step argument, the third num argument specifies the number of desired values, for example:

print(linspace(0, 10, 5))
# linspace(0, 10, 5)
print(list(linspace(0, 10, 5)))
# [0.0, 2.5, 5.0, 7.5, 10]

I quote a modified version of the full Python 3 recipe from Andrew Barnert below:

import collections.abc
import numbers

class linspace(collections.abc.Sequence):
    """linspace(start, stop, num) -> linspace object

    Return a virtual sequence of num numbers from start to stop (inclusive).

    If you need a half-open range, use linspace(start, stop, num+1)[:-1].
    """
    def __init__(self, start, stop, num):
        if not isinstance(num, numbers.Integral) or num <= 1:
            raise ValueError('num must be an integer > 1')
        self.start, self.stop, self.num = start, stop, num
        self.step = (stop-start)/(num-1)
    def __len__(self):
        return self.num
    def __getitem__(self, i):
        if isinstance(i, slice):
            return [self[x] for x in range(*i.indices(len(self)))]
        if i < 0:
            i = self.num + i
        if i >= self.num:
            raise IndexError('linspace object index out of range')
        if i == self.num-1:
            return self.stop
        return self.start + i*self.step
    def __repr__(self):
        return '{}({}, {}, {})'.format(type(self).__name__,
                                       self.start, self.stop, self.num)
    def __eq__(self, other):
        if not isinstance(other, linspace):
            return False
        return ((self.start, self.stop, self.num) ==
                (other.start, other.stop, other.num))
    def __ne__(self, other):
        return not self==other
    def __hash__(self):
        return hash((type(self), self.start, self.stop, self.num))

How to access Winform textbox control from another class?

If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:

otherClassInstance.textBox1.Text = "hello world";

Group a list of objects by an attribute

Implement SQL GROUP BY Feature in Java using Comparator, comparator will compare your column data, and sort it. Basically if you keep sorted data that looks as grouped data, for example if you have same repeated column data then sort mechanism sort them keeping same data one side and then look for other data which is dissimilar data. This indirectly viewed as GROUPING of same data.

public class GroupByFeatureInJava {

    public static void main(String[] args) {
        ProductBean p1 = new ProductBean("P1", 20, new Date());
        ProductBean p2 = new ProductBean("P1", 30, new Date());
        ProductBean p3 = new ProductBean("P2", 20, new Date());
        ProductBean p4 = new ProductBean("P1", 20, new Date());
        ProductBean p5 = new ProductBean("P3", 60, new Date());
        ProductBean p6 = new ProductBean("P1", 20, new Date());

        List<ProductBean> list = new ArrayList<ProductBean>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        list.add(p5);
        list.add(p6);

        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
        System.out.println("******** AFTER GROUP BY PRODUCT_ID ******");
        Collections.sort(list, new ProductBean().new CompareByProductID());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }

        System.out.println("******** AFTER GROUP BY PRICE ******");
        Collections.sort(list, new ProductBean().new CompareByProductPrice());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
    }
}

class ProductBean {
    String productId;
    int price;
    Date date;

    @Override
    public String toString() {
        return "ProductBean [" + productId + " " + price + " " + date + "]";
    }
    ProductBean() {
    }
    ProductBean(String productId, int price, Date date) {
        this.productId = productId;
        this.price = price;
        this.date = date;
    }
    class CompareByProductID implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.productId.compareTo(p2.productId) > 0) {
                return 1;
            }
            if (p1.productId.compareTo(p2.productId) < 0) {
                return -1;
            }
            // at this point all a.b,c,d are equal... so return "equal"
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByProductPrice implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            // this mean the first column is tied in thee two rows
            if (p1.price > p2.price) {
                return 1;
            }
            if (p1.price < p2.price) {
                return -1;
            }
            return 0;
        }
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByCreateDate implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.date.after(p2.date)) {
                return 1;
            }
            if (p1.date.before(p2.date)) {
                return -1;
            }
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }
}

Output is here for the above ProductBean list is done GROUP BY criteria, here if you see the input data that is given list of ProductBean to Collections.sort(list, object of Comparator for your required column) This will sort based on your comparator implementation and you will be able to see the GROUPED data in below output. Hope this helps...

    ******** BEFORE GROUPING INPUT DATA LOOKS THIS WAY ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ******** AFTER GROUP BY PRODUCT_ID ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

    ******** AFTER GROUP BY PRICE ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

Integer.valueOf() vs. Integer.parseInt()

parseInt() parses String to int while valueOf() additionally wraps this int into Integer. That's the only difference.

If you want to have full control over parsing integers, check out NumberFormat with various locales.

Equivalent of String.format in jQuery

I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.

Usage is similar to c# version:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

Also, added support for using names & object properties

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

PHP string concatenation

One step (IMHO) better

$result .= $personCount . ' people';

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Can I have onScrollListener for a ScrollView?

Every instance of View calls getViewTreeObserver(). Now when holding an instance of ViewTreeObserver, you can add an OnScrollChangedListener() to it using the method addOnScrollChangedListener().

You can see more information about this class here.

It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY() or getScrollX() from within the listener though.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        int scrollY = rootScrollView.getScrollY(); // For ScrollView
        int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
        // DO SOMETHING WITH THE SCROLL COORDINATES
    }
});

Error message "No exports were found that match the constraint contract name"

This happened to me with Visual Studio 2013 Web, after Windows installed several updates. Unfortunately none of the suggestions in this thread helped.

I had to re-run the installer and select the "Repair" option. After that (and a reboot) it was working once again.

In some cases you may have to repair more than one version of Visual Studio. One example is when a Script Task control in VS 2013 opens VS 2012 when you click Edit Script.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

The javascript library sugar.js (http://sugarjs.com/) has functions to format dates

Example:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

Using jQuery, Restricting File Size Before Uploading

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

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

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

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

in PATH system variable

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

inetmgr then come to Application pool->Advanced setting of your pool-> will have the option "Enable 32-Bit Applications" set to true; and restart IIS. check again.!

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

How do I initialize a dictionary of empty lists in Python?

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don't have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Adding the Tomcat server in the server runtime will do the job:

Right click your project and than;

Project properties ? Target Runtimes ? Select/Check "Apache Tomcat" ? Finish.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

Use of PUT vs PATCH methods in REST API real life scenarios

NOTE: When I first spent time reading about REST, idempotence was a confusing concept to try to get right. I still didn't get it quite right in my original answer, as further comments (and Jason Hoetger's answer) have shown. For a while, I have resisted updating this answer extensively, to avoid effectively plagiarizing Jason, but I'm editing it now because, well, I was asked to (in the comments).

After reading my answer, I suggest you also read Jason Hoetger's excellent answer to this question, and I will try to make my answer better without simply stealing from Jason.

Why is PUT idempotent?

As you noted in your RFC 2616 citation, PUT is considered idempotent. When you PUT a resource, these two assumptions are in play:

  1. You are referring to an entity, not to a collection.

  2. The entity you are supplying is complete (the entire entity).

Let's look at one of your examples.

{ "username": "skwee357", "email": "[email protected]" }

If you POST this document to /users, as you suggest, then you might get back an entity such as

## /users/1

{
    "username": "skwee357",
    "email": "[email protected]"
}

If you want to modify this entity later, you choose between PUT and PATCH. A PUT might look like this:

PUT /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // new email address
}

You can accomplish the same using PATCH. That might look like this:

PATCH /users/1
{
    "email": "[email protected]"       // new email address
}

You'll notice a difference right away between these two. The PUT included all of the parameters on this user, but PATCH only included the one that was being modified (email).

When using PUT, it is assumed that you are sending the complete entity, and that complete entity replaces any existing entity at that URI. In the above example, the PUT and PATCH accomplish the same goal: they both change this user's email address. But PUT handles it by replacing the entire entity, while PATCH only updates the fields that were supplied, leaving the others alone.

Since PUT requests include the entire entity, if you issue the same request repeatedly, it should always have the same outcome (the data you sent is now the entire data of the entity). Therefore PUT is idempotent.

Using PUT wrong

What happens if you use the above PATCH data in a PUT request?

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"
}
PUT /users/1
{
    "email": "[email protected]"       // new email address
}

GET /users/1
{
    "email": "[email protected]"      // new email address... and nothing else!
}

(I'm assuming for the purposes of this question that the server doesn't have any specific required fields, and would allow this to happen... that may not be the case in reality.)

Since we used PUT, but only supplied email, now that's the only thing in this entity. This has resulted in data loss.

This example is here for illustrative purposes -- don't ever actually do this. This PUT request is technically idempotent, but that doesn't mean it isn't a terrible, broken idea.

How can PATCH be idempotent?

In the above example, PATCH was idempotent. You made a change, but if you made the same change again and again, it would always give back the same result: you changed the email address to the new value.

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"
}
PATCH /users/1
{
    "email": "[email protected]"       // new email address
}

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // email address was changed
}
PATCH /users/1
{
    "email": "[email protected]"       // new email address... again
}

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // nothing changed since last GET
}

My original example, fixed for accuracy

I originally had examples that I thought were showing non-idempotency, but they were misleading / incorrect. I am going to keep the examples, but use them to illustrate a different thing: that multiple PATCH documents against the same entity, modifying different attributes, do not make the PATCHes non-idempotent.

Let's say that at some past time, a user was added. This is the state that you are starting from.

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "10001"
}

After a PATCH, you have a modified entity:

PATCH /users/1
{"email": "[email protected]"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",    // the email changed, yay!
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "10001"
}

If you then repeatedly apply your PATCH, you will continue to get the same result: the email was changed to the new value. A goes in, A comes out, therefore this is idempotent.

An hour later, after you have gone to make some coffee and take a break, someone else comes along with their own PATCH. It seems the Post Office has been making some changes.

PATCH /users/1
{"zip": "12345"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",  // still the new email you set
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "12345"                      // and this change as well
}

Since this PATCH from the post office doesn't concern itself with email, only zip code, if it is repeatedly applied, it will also get the same result: the zip code is set to the new value. A goes in, A comes out, therefore this is also idempotent.

The next day, you decide to send your PATCH again.

PATCH /users/1
{"email": "[email protected]"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "12345"
}

Your patch has the same effect it had yesterday: it set the email address. A went in, A came out, therefore this is idempotent as well.

What I got wrong in my original answer

I want to draw an important distinction (something I got wrong in my original answer). Many servers will respond to your REST requests by sending back the new entity state, with your modifications (if any). So, when you get this response back, it is different from the one you got back yesterday, because the zip code is not the one you received last time. However, your request was not concerned with the zip code, only with the email. So your PATCH document is still idempotent - the email you sent in PATCH is now the email address on the entity.

So when is PATCH not idempotent, then?

For a full treatment of this question, I again refer you to Jason Hoetger's answer. I'm just going to leave it at that, because I honestly don't think I can answer this part better than he already has.

String.Replace(char, char) method in C#

What about creating an Extension Method like this....

 public static string ReplaceTHAT(this string s)
 {
    return s.Replace("\n\r", "");
 }

And then when you want to replace that wherever you want you can do this.

s.ReplaceTHAT();

Best Regards!

Openssl is not recognized as an internal or external command

First navigate to your Java/jre/bin folder in cmd cd c:\Program Files (x86)\Java\jre7\bin

Then use : [change debug.keystore path to the correct location on your system] install openssl (for windows 32 or 64 as per your needs at c:\openssl )

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.exe" sha1 -binary | "c:\openssl\bin\openssl.exe" base64

So the whole command goes like this : [prompts to enter keystore password on execution ]

c:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.ex
e" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
Enter keystore password:

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

How to retry after exception?

Alternatives to retrying: tenacity and backoff (2020 update)

The retrying library was previously the way to go, but sadly it has some bugs and it hasn't got any updates since 2016. Other alternatives seem to be backoff and tenacity. During the time of writing this, the tenacity had more GItHub stars (2.3k vs 1.2k) and was updated more recently, hence I chose to use it. Here is an example:

from functools import partial
import random # producing random errors for this example

from tenacity import retry, stop_after_delay, wait_fixed, retry_if_exception_type

# Custom error type for this example
class CommunicationError(Exception):
    pass

# Define shorthand decorator for the used settings.
retry_on_communication_error = partial(
    retry,
    stop=stop_after_delay(10),  # max. 10 seconds wait.
    wait=wait_fixed(0.4),  # wait 400ms 
    retry=retry_if_exception_type(CommunicationError),
)()


@retry_on_communication_error
def do_something_unreliable(i):
    if random.randint(1, 5) == 3:
        print('Run#', i, 'Error occured. Retrying.')
        raise CommunicationError()

for i in range(100):
    do_something_unreliable(i)

The above code outputs something like:

Run# 3 Error occured. Retrying.
Run# 5 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 10 Error occured. Retrying.
.
.
.

More settings for the tenacity.retry are listed on the tenacity GitHub page.

Right way to split an std::string into a vector<string>

std::vector<std::string> split(std::string text, char delim) {
    std::string line;
    std::vector<std::string> vec;
    std::stringstream ss(text);
    while(std::getline(ss, line, delim)) {
        vec.push_back(line);
    }
    return vec;
}

split("String will be split", ' ') -> {"String", "will", "be", "split"}

split("Hello, how are you?", ',') -> {"Hello", "how are you?"}

EDIT: Here's a thing I made, this can use multi-char delimiters, albeit I'm not 100% sure if it always works:

std::vector<std::string> split(std::string text, std::string delim) {
    std::vector<std::string> vec;
    size_t pos = 0, prevPos = 0;
    while (1) {
        pos = text.find(delim, prevPos);
        if (pos == std::string::npos) {
            vec.push_back(text.substr(prevPos));
            return vec;
        }

        vec.push_back(text.substr(prevPos, pos - prevPos));
        prevPos = pos + delim.length();
    }
}

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

swift 3.0 Data to String?

This is much easier in Swift 3 and later using reduce:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.reduce("") { $0 + String(format: "%02x", $1) }

    DispatchQueue.global(qos: .background).async { 
        let url = URL(string: "https://example.com/myApp/apns.php")!

        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: [
            "token" : token, 
            "ios" : UIDevice.current.systemVersion,
            "languages" : Locale.preferredLanguages.joined(separator: ", ")
            ])

        URLSession.shared.dataTask(with: request).resume()
    }
}

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

How to delete all data from solr and hbase

If you need to clean out all data, it might be faster to recreate collection, e.g.

solrctl --zk localhost:2181/solr collection --delete <collectionName>
solrctl --zk localhost:2181/solr collection --create <collectionName> -s 1

Filling a List with all enum values in Java

This is a bit more readable:

Object[] allValues = all.getDeclaringClass().getEnumConstants();

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Just try adjusting ( decrease ) your allotted RAM for the virtual machine in Motherboard in settings. The amount of RAM free in your system at that time might be less than the amount you have allotted for the virtual machine. This worked for me.

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

What’s the difference between Response.Write() andResponse.Output.Write()?

See this:

The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.

In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);} 

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; } 

Which means you can do the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method aka String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);

But internally, of course, this is happening:

public virtual void Write(string format, params object[] arg)
{ 
this.Write(string.Format(format, arg)); 
}

How can building a heap be O(n) time complexity?

In case of building the heap, we start from height, logn -1 (where logn is the height of tree of n elements). For each element present at height 'h', we go at max upto (logn -h) height down.

    So total number of traversal would be:-
    T(n) = sigma((2^(logn-h))*h) where h varies from 1 to logn
    T(n) = n((1/2)+(2/4)+(3/8)+.....+(logn/(2^logn)))
    T(n) = n*(sigma(x/(2^x))) where x varies from 1 to logn
     and according to the [sources][1]
    function in the bracket approaches to 2 at infinity.
    Hence T(n) ~ O(n)

HTTP headers in Websockets client API

Updated 2x

Short answer: No, only the path and protocol field can be specified.

Longer answer:

There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:

var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);

The above results in the following headers:

Sec-WebSocket-Protocol: protocol

and

Sec-WebSocket-Protocol: protocol1, protocol2

A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security

Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified.

Basic Auth Info (Deprecated - No longer functional):

NOTE: the following information is no longer accurate in any modern browsers.

The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:

var ws = new WebSocket("ws://username:[email protected]")

The above results in the following header with the string "username:password" base64 encoded:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).

Thanks to Dmitry Frank's for the basic auth answer

What Process is using all of my disk IO

iotop with the -a flag:

-a, --accumulated     show accumulated I/O instead of bandwidth

How to convert signed to unsigned integer in python

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376
>>> i & 0xffffffff
4288082920

or if it is 64 bit:

>>> i & 0xffffffffffffffff
18446744073702667240

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.

This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.

Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):

>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:

>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376

Or for the 64 bit version:

>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.

Hash Map in Python

Here is the implementation of the Hash Map using python For the simplicity hash map is of a fixed size 16. This can be changed easily. Rehashing is out of scope of this code.

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None

class HashMap:
    def __init__(self):
        self.store = [None for _ in range(16)]
    def get(self, key):
        index = hash(key) & 15
        if self.store[index] is None:
            return None
        n = self.store[index]
        while True:
            if n.key == key:
                return n.value
            else:
                if n.next:
                    n = n.next
                else:
                    return None
    def put(self, key, value):
        nd = Node(key, value)
        index = hash(key) & 15
        n = self.store[index]
        if n is None:
            self.store[index] = nd
        else:
            if n.key == key:
                n.value = value
            else:
                while n.next:
                    if n.key == key:
                        n.value = value
                        return
                    else:
                        n = n.next
                n.next = nd

hm = HashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
hm.put("4", "srinath")
hm.put("5", "kumble")
hm.put("6", "dhoni")
hm.put("7", "kohli")
hm.put("8", "pandya")
hm.put("9", "rohit")
hm.put("10", "dhawan")
hm.put("11", "shastri")
hm.put("12", "manjarekar")
hm.put("13", "gupta")
hm.put("14", "agarkar")
hm.put("15", "nehra")
hm.put("16", "gawaskar")
hm.put("17", "vengsarkar")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))
print(hm.get("4"))
print(hm.get("5"))
print(hm.get("6"))
print(hm.get("7"))
print(hm.get("8"))
print(hm.get("9"))
print(hm.get("10"))
print(hm.get("11"))
print(hm.get("12"))
print(hm.get("13"))
print(hm.get("14"))
print(hm.get("15"))
print(hm.get("16"))
print(hm.get("17"))

Output:

sachin
sehwag
ganguly
srinath
kumble
dhoni
kohli
pandya
rohit
dhawan
shastri
manjarekar
gupta
agarkar
nehra
gawaskar
vengsarkar

Resize command prompt through commands

If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

Max size of an iOS application

50 Meg is the max for Cell data download.

But you might be able to keep it under that in the app store and then have the app download other content after the user install and runs the app, so the app can be bigger. But not sure what the apple rules are for this.

I know that all in-app purchases need to be approved, but not sure if this kind of content needs to be approved.

After updating Entity Framework model, Visual Studio does not see changes

I've also experienced this problem with none of the classes being generated under the model.tt file. In my case it was down to issues with how I had built the DB in SQL2012. I'd set a column in a table to nullable that was also a foreign key and although I think you should be able to do this it caused a problem in EF5.

As soon as this was cleared and the diagram updated from the database they reappeared.

EF5 VS2013

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

How to find schema name in Oracle ? when you are connected in sql session using read only user

To create a read-only user, you have to setup a different user than the one owning the tables you want to access.

If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:

  1. Set the current schema in your session:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
  1. Create synonyms for all tables:
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1

So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:

  1. Query the current schema setting:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
  1. List your synonyms:
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
  1. Investigate all tables (with the exception of the some well-known standard schemas):
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');

How can I view the Git history in Visual Studio Code?

I strongly recommend using a combination of GitLens & GitGraph.

Below snapshot highlights how gitlens is showing commit over time

enter image description here

And the below picture is for the the amazing vivid GitGraph

enter image description here

Node.js: for each … in not working

https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.

How can I measure the actual memory usage of an application or process?

While this question seems to be about examining currently running processes, I wanted to see the peak memory used by an application from start to finish. Besides Valgrind, you can use tstime, which is much simpler. It measures the "highwater" memory usage (RSS and virtual). From this answer.

Angular and debounce

Simple solution would be to create a directive which you can apply to any control.

import { Directive, ElementRef, Input, Renderer, HostListener, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
    selector: '[ngModel][debounce]',
})
export class Debounce 
{
    @Output() public onDebounce = new EventEmitter<any>();

    @Input('debounce') public debounceTime: number = 500;

    private modelValue = null;

    constructor(public model: NgControl, el: ElementRef, renderer: Renderer){
    }

    ngOnInit(){
        this.modelValue = this.model.value;

        if (!this.modelValue){
            var firstChangeSubs = this.model.valueChanges.subscribe(v =>{
                this.modelValue = v;
                firstChangeSubs.unsubscribe()
            });
        }

        this.model.valueChanges
            .debounceTime(this.debounceTime)
            .distinctUntilChanged()
            .subscribe(mv => {
                if (this.modelValue != mv){
                    this.modelValue = mv;
                    this.onDebounce.emit(mv);
                }
            });
    }
}

usage would be

<textarea [ngModel]="somevalue"   
          [debounce]="2000"
          (onDebounce)="somevalue = $event"                               
          rows="3">
</textarea>

convert nan value to zero

Where A is your 2D array:

import numpy as np
A[np.isnan(A)] = 0

The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.

How do I create delegates in Objective-C?

Here is a simple method to create delegates

Create Protocol in .h file. Make sure that is defined before the protocol using @class followed by the name of the UIViewController < As the protocol I am going to use is UIViewController class>.

Step : 1 : Create a new class Protocol named "YourViewController" which will be the subclass of UIViewController class and assign this class to the second ViewController.

Step : 2 : Go to the "YourViewController" file and modify it as below:

#import <UIKit/UIkit.h>
@class YourViewController;

@protocol YourViewController Delegate <NSObject>

 @optional
-(void)defineDelegateMethodName: (YourViewController *) controller;

@required
-(BOOL)delegateMethodReturningBool: (YourViewController *) controller;

  @end
  @interface YourViewController : UIViewController

  //Since the property for the protocol could be of any class, then it will be marked as a type of id.

  @property (nonatomic, weak) id< YourViewController Delegate> delegate;

@end

The methods defined in the protocol behavior can be controlled with @optional and @required as part of the protocol definition.

Step : 3 : Implementation of Delegate

    #import "delegate.h"

   @interface YourDelegateUser ()
     <YourViewControllerDelegate>
   @end

   @implementation YourDelegateUser

   - (void) variousFoo {
      YourViewController *controller = [[YourViewController alloc] init];
      controller.delegate = self;
   }

   -(void)defineDelegateMethodName: (YourViewController *) controller {
      // handle the delegate being called here
   }

   -(BOOL)delegateMethodReturningBool: (YourViewController *) controller {
      // handle the delegate being called here
      return YES;
   }

   @end

//test whether the method has been defined before you call it

 - (void) someMethodToCallDelegate {
     if ([[self delegate] respondsToSelector:@selector(defineDelegateMethodName:)]) {
           [self.delegate delegateMethodName:self]; 
     }
  }

Cannot download Docker images behind a proxy

Your APT proxy settings are not related to Docker.

Docker uses the HTTP_PROXY environment variable, if present. For example:

sudo HTTP_PROXY=http://192.168.1.1:3128/ docker pull busybox

But instead, I suggest you have a look at your /etc/default/dockerconfiguration file: you should have a line to uncomment (and maybe adjust) to get your proxy settings applied automatically. Then restart the Docker server:

service docker restart

Javascript checkbox onChange

Pure javascript:

_x000D_
_x000D_
const checkbox = document.getElementById('myCheckbox')

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})
_x000D_
My Checkbox: <input id="myCheckbox" type="checkbox" />
_x000D_
_x000D_
_x000D_

The remote server returned an error: (403) Forbidden

In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true

Setting "checked" for a checkbox with jQuery

Use:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

And if you want to check if a checkbox is checked or not:

$('.myCheckbox').is(':checked');

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

Angular 2 declaring an array of objects

public mySentences:Array<any> = [
    {id: 1, text: 'Sentence 1'},
    {id: 2, text: 'Sentence 2'},
    {id: 3, text: 'Sentence 3'},
    {id: 4, text: 'Sentenc4 '},
];

OR

public mySentences:Array<object> = [
    {id: 1, text: 'Sentence 1'},
    {id: 2, text: 'Sentence 2'},
    {id: 3, text: 'Sentence 3'},
    {id: 4, text: 'Sentenc4 '},
];

Differences between MySQL and SQL Server

Anyone have any good experience with a "port" of a database from SQL Server to MySQL?

This should be fairly painful! I switched versions of MySQL from 4.x to 5.x and various statements wouldn't work anymore as they used to. The query analyzer was "improved" so statements which previously were tuned for performance would not work anymore as expected.

The lesson learned from working with a 500GB MySQL database: It's a subtle topic and anything else but trivial!

How to check for changes on remote (origin) Git repository

You could git fetch origin to update the remote branch in your repository to point to the latest version. For a diff against the remote:

git diff origin/master

Yes, you can use caret notation as well.

If you want to accept the remote changes:

git merge origin/master

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How do I put a border around an Android textview?

The simple way is to add a view for your TextView. Example for the bottom border line:

<LinearLayout android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:text="@string/title"
        android:id="@+id/title_label"
        android:gravity="center_vertical"/>
    <View
        android:layout_width="fill_parent"
        android:layout_height="0.2dp"
        android:id="@+id/separator"
        android:visibility="visible"
        android:background="@android:color/darker_gray"/>

</LinearLayout>

For the other direction borders, please adjust the location of the separator view.

Undefined reference to pthread_create in Linux

For Linux the correct command is:

gcc -o term term.c -lpthread
  1. you have to put -lpthread just after the compile command,this command will tell to the compiler to execute program with pthread.h library.
  2. gcc -l links with a library file.Link -l with library name without the lib prefix.

Set selected item of spinner programmatically

In my case, this code saved my day:

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SpinnerAdapter adapter = spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

Regex replace uppercase with lowercase letters

Try this

  • Find: ([A-Z])([A-Z]+)\b
  • Replace: $1\L$2

Make sure case sensitivity is on (Alt + C)

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

Linux command line howto accept pairing for bluetooth device without pin

This worked like a charm for me, of-course it requires super-user privileges :-)

# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>

To get <target-bdaddr> you may issue below command:
$ hcitool scan

Note: Exclude # & $ as they are command line prompts.

Courtesy

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

SQL Group By with an Order By

I don't know about MySQL, but in MS SQL, you can use the column index in the order by clause. I've done this before when doing counts with group bys as it tends to be easier to work with.

So

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

Becomes

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20

Simple regular expression for a decimal with a precision of 2

In general, i.e. unlimited decimal places:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.

HTTP URL Address Encoding in Java

If anybody doesn't want to add a dependency to their project, these functions may be helpful.

We pass the 'path' part of our URL into here. You probably don't want to pass the full URL in as a parameter (query strings need different escapes, etc).

/**
 * Percent-encodes a string so it's suitable for use in a URL Path (not a query string / form encode, which uses + for spaces, etc)
 */
public static String percentEncode(String encodeMe) {
    if (encodeMe == null) {
        return "";
    }
    String encoded = encodeMe.replace("%", "%25");
    encoded = encoded.replace(" ", "%20");
    encoded = encoded.replace("!", "%21");
    encoded = encoded.replace("#", "%23");
    encoded = encoded.replace("$", "%24");
    encoded = encoded.replace("&", "%26");
    encoded = encoded.replace("'", "%27");
    encoded = encoded.replace("(", "%28");
    encoded = encoded.replace(")", "%29");
    encoded = encoded.replace("*", "%2A");
    encoded = encoded.replace("+", "%2B");
    encoded = encoded.replace(",", "%2C");
    encoded = encoded.replace("/", "%2F");
    encoded = encoded.replace(":", "%3A");
    encoded = encoded.replace(";", "%3B");
    encoded = encoded.replace("=", "%3D");
    encoded = encoded.replace("?", "%3F");
    encoded = encoded.replace("@", "%40");
    encoded = encoded.replace("[", "%5B");
    encoded = encoded.replace("]", "%5D");
    return encoded;
}

/**
 * Percent-decodes a string, such as used in a URL Path (not a query string / form encode, which uses + for spaces, etc)
 */
public static String percentDecode(String encodeMe) {
    if (encodeMe == null) {
        return "";
    }
    String decoded = encodeMe.replace("%21", "!");
    decoded = decoded.replace("%20", " ");
    decoded = decoded.replace("%23", "#");
    decoded = decoded.replace("%24", "$");
    decoded = decoded.replace("%26", "&");
    decoded = decoded.replace("%27", "'");
    decoded = decoded.replace("%28", "(");
    decoded = decoded.replace("%29", ")");
    decoded = decoded.replace("%2A", "*");
    decoded = decoded.replace("%2B", "+");
    decoded = decoded.replace("%2C", ",");
    decoded = decoded.replace("%2F", "/");
    decoded = decoded.replace("%3A", ":");
    decoded = decoded.replace("%3B", ";");
    decoded = decoded.replace("%3D", "=");
    decoded = decoded.replace("%3F", "?");
    decoded = decoded.replace("%40", "@");
    decoded = decoded.replace("%5B", "[");
    decoded = decoded.replace("%5D", "]");
    decoded = decoded.replace("%25", "%");
    return decoded;
}

And tests:

@Test
public void testPercentEncode_Decode() {
    assertEquals("", percentDecode(percentEncode(null)));
    assertEquals("", percentDecode(percentEncode("")));

    assertEquals("!", percentDecode(percentEncode("!")));
    assertEquals("#", percentDecode(percentEncode("#")));
    assertEquals("$", percentDecode(percentEncode("$")));
    assertEquals("@", percentDecode(percentEncode("@")));
    assertEquals("&", percentDecode(percentEncode("&")));
    assertEquals("'", percentDecode(percentEncode("'")));
    assertEquals("(", percentDecode(percentEncode("(")));
    assertEquals(")", percentDecode(percentEncode(")")));
    assertEquals("*", percentDecode(percentEncode("*")));
    assertEquals("+", percentDecode(percentEncode("+")));
    assertEquals(",", percentDecode(percentEncode(",")));
    assertEquals("/", percentDecode(percentEncode("/")));
    assertEquals(":", percentDecode(percentEncode(":")));
    assertEquals(";", percentDecode(percentEncode(";")));

    assertEquals("=", percentDecode(percentEncode("=")));
    assertEquals("?", percentDecode(percentEncode("?")));
    assertEquals("@", percentDecode(percentEncode("@")));
    assertEquals("[", percentDecode(percentEncode("[")));
    assertEquals("]", percentDecode(percentEncode("]")));
    assertEquals(" ", percentDecode(percentEncode(" ")));

    // Get a little complex
    assertEquals("[]]", percentDecode(percentEncode("[]]")));
    assertEquals("a=d%*", percentDecode(percentEncode("a=d%*")));
    assertEquals(")  (", percentDecode(percentEncode(")  (")));
    assertEquals("%21%20%2A%20%27%20%28%20%25%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%2F%20%3F%20%23%20%5B%20%5D%20%25",
                    percentEncode("! * ' ( % ) ; : @ & = + $ , / ? # [ ] %"));
    assertEquals("! * ' ( % ) ; : @ & = + $ , / ? # [ ] %", percentDecode(
                    "%21%20%2A%20%27%20%28%20%25%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%2F%20%3F%20%23%20%5B%20%5D%20%25"));

    assertEquals("%23456", percentDecode(percentEncode("%23456")));

}

Binding IIS Express to an IP Address

As mentioned above, edit the application host.config. An easy way to find this is run your site in VS using IIS Express. Right click the systray icon, show all applications. Choose your site, and then click on the config link at the bottom to open it.

I'd suggest adding another binding entry, and leave the initial localhost one there. This additional binding will appear in the IIS Express systray as a separate application under the site.

To avoid having to run VS as admin (lots of good reasons not to run as admin), add a netsh rule as follows (obviously replacing the IP and port with your values) - you'll need an admin cmd.exe for this, it only needs to be run once:

netsh http add urlacl url=http://192.168.1.121:51652/ user=\Everyone

netsh can add rules like url=http://+:51652/ but I failed to get this to place nicely with IIS Express. You can use netsh http show urlacl to list existing rules, and they can be deleted with netsh http delete urlacl url=blah.

Further info: http://msdn.microsoft.com/en-us/library/ms733768.aspx

Advantages of using display:inline-block vs float:left in CSS

While I agree that in general inline-block is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):

If you're using inline-block for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.

With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.

If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0; on the column container then reapply font size within each column.

For example:

Is there a unique Android device ID?

Get Device UUID, model number with brand name and its version number with the help of below function.

Work in Android 10 perfectly and no need to allow read phone state permission.

Code Snippets:

private void fetchDeviceInfo() {
    String uniquePseudoID = "35" +
            Build.BOARD.length() % 10 +
            Build.BRAND.length() % 10 +
            Build.DEVICE.length() % 10 +
            Build.DISPLAY.length() % 10 +
            Build.HOST.length() % 10 +
            Build.ID.length() % 10 +
            Build.MANUFACTURER.length() % 10 +
            Build.MODEL.length() % 10 +
            Build.PRODUCT.length() % 10 +
            Build.TAGS.length() % 10 +
            Build.TYPE.length() % 10 +
            Build.USER.length() % 10;

    String serial = Build.getRadioVersion();
    String uuid=new UUID(uniquePseudoID.hashCode(), serial.hashCode()).toString();
    String brand=Build.BRAND;
    String modelno=Build.MODEL;
    String version=Build.VERSION.RELEASE;
    Log.e(TAG, "fetchDeviceInfo: \n "+
            "\n uuid is : "+uuid+
            "\n brand is: "+brand+
            "\n model is: "+modelno+
            "\n version is: "+version);
}

Call Above function and to check output of above code. please see your log cat in android studio. It look likes below:

enter image description here

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How can I invert color using CSS?

Add the same color of the background to the paragraph and then invert with CSS:

_x000D_
_x000D_
div {_x000D_
    background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
    color: #f00;_x000D_
    -webkit-filter: invert(100%);_x000D_
    filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
    <p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove all whitespace from C# string with regex

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

How to copy a file from one directory to another using PHP?

Hi guys wanted to also add on how to copy using a dynamic copying and pasting.

let say we don't know the actual folder the user will create but we know in that folder we need files to be copied to, to activate some function like delete, update, views etc.

you can use something like this... I used this code in one of the complex project which I am currently busy on. i just build it myself because all answers i got on the internet was giving me an error.

    $dirPath1 = "users/$uniqueID"; #creating main folder and where $uniqueID will be called by a database when a user login.
    $result = mkdir($dirPath1, 0755);
            $dirPath2 = "users/$uniqueID/profile"; #sub folder
            $result = mkdir($dirPath2, 0755);
                $dirPath3 = "users/$uniqueID/images"; #sub folder 
                $result = mkdir($dirPath3, 0755);
                    $dirPath4 = "users/$uniqueID/uploads";#sub folder
                    $result = mkdir($dirPath4, 0755);
                    @copy('blank/dashboard.php', 'users/'.$uniqueID.'/dashboard.php');#from blank folder to dynamic user created folder
                    @copy('blank/views.php', 'users/'.$uniqueID.'/views.php'); #from blank folder to dynamic user created folder
                    @copy('blank/upload.php', 'users/'.$uniqueID.'/upload.php'); #from blank folder to dynamic user created folder
                    @copy('blank/delete.php', 'users/'.$uniqueID.'/delete.php'); #from blank folder to dynamic user created folder

I think facebook or twitter uses something like this to build every new user dashboard dynamic....

alternative to "!is.null()" in R

The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.

I suggest defining a function like this:

is.valid <- function(x) {
  require(shiny)
  is.null(need(x, message = FALSE))  
}

This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.

That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:

if (!is.null(x) && !is.na(x) && !is.nan(x)) {
  ...
}

one can write simply:

if (is.valid(x)) {
  ...
}

With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)

bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
  ...
}

How to get a substring of text?

Since you tagged it Rails, you can use truncate:

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Example:

 truncate(@text, :length => 17)

Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

String field value length in mongoDB

Queries with $where and $expr are slow if there are too many documents.

Using $regex is much faster than $where, $expr.

db.usercollection.find({ 
  "name": /^[\s\S]{40,}$/, // name.length >= 40
})

or 

db.usercollection.find({ 
  "name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})

This query is the same meaning with

db.usercollection.find({ 
  "$where": "this.name && this.name.length >= 40",
})

or

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] } 
})

I tested each queries for my collection.

# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms

# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms

jQuery AJAX cross domain

It is true that the same-origin policy prevents JavaScript from making requests across domains, but the CORS specification allows just the sort of API access you are looking for, and is supported by the current batch of major browsers.

See how to enable cross-origin resource sharing for client and server:

http://enable-cors.org/

"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access."

SQL Server insert if not exists best practice

Another option is to left join your Results table with your existing competitors Table and find the new competitors by filtering the distinct records that don´t match int the join:

INSERT Competitors (cName)
SELECT  DISTINCT cr.Name
FROM    CompResults cr left join
        Competitors c on cr.Name = c.cName
where   c.cName is null

New syntax MERGE also offer a compact, elegant and efficient way to do that:

MERGE INTO Competitors AS Target
USING (SELECT DISTINCT Name FROM CompResults) AS Source ON Target.Name = Source.Name
WHEN NOT MATCHED THEN
    INSERT (Name) VALUES (Source.Name);

How to open a folder in Windows Explorer from VBA?

You can use the following code to open a file location from vba.

Dim Foldername As String
Foldername = "\\server\Instructions\"

Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus

You can use this code for both windows shares and local drives.

VbNormalFocus can be swapper for VbMaximizedFocus if you want a maximized view.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Reportviewer tool missing in visual studio 2017 RC

** Update**: 11/19/2019

Microsoft has released a new version of the control 150.1400.0 in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0 and 150.1358.0 did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.

** Update**: 8/18/2019

Removing the latest version and rolling back to 150.900.148.0 seems to work on multiple computers I'm using with VS2017 and VS2019.

You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.

enter image description here

It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.

Remember to restart Visual Studio after changing the toolbox entry.

Update: 8/7/2019

A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.

Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.

This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.

While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.

I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.

Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control

Additional steps:

  • After adding the reportviewer to the WinForm
  • Add a Panel Control to the WinForm.
  • In the form's form.designer.cs file, add the Reportviewer control to the panel.

      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.reportViewer1);
    
  • Return to the form's designer, you should see the reportViewer on the panel

  • In the Properties panel select the ReportViewer in the controls list dropdown
  • Set the reportViewer's Dock property to Fill

Now you can position the reportViewer by actually interacting with the panel.

Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.

Visual Studio 2017 does not have the ReportViewer tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.

Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".

The following steps need to be followed for each project that requires ReportViewer.

  • If you have ReportViewer in the Toolbox, remove it. Highlight, right-click and delete.
    • You will have to have a project with a form open to do this.

Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.

  • If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.

  • Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.

  • Open your solution.
  • Open the NuGet Package Manager Console (Tools/NuGet Package Manager/Package Manager Console)
  • At the PM> prompt enter this command, case matters.

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms

    You should see text describing the installation of the package.

Now we can temporarily add the ReportViewer tool to the tool box.

  • Right-click in the toolbox and use Choose Items...

  • We need to browse to the proper DLL that is located in the solutions Packages folder, so hit the browse button.

  • In our example we can paste in the packages folder as shown in the text of Package Manager Console.

    C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages

  • Then double click on the folder named Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80

    The version number will probably change in the future.

  • Then double-click on lib and again on net40.

  • Finally, double click on the file Microsoft.ReportViewer.WinForms.dll

    You should see ReportViewer checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.

  • Click OK.

ReportViewer is now located in the ToolBox.

  • Drag the tool to the desired form(s).

  • Once completed, delete the ReportViewer tool from the tool box. You can't use it with another project.

  • You may save the project and are good to go.

Remember to restart Visual Studio any time you need to open a project with ReportViewer so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.“.

If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer to the form. I have seen it not work the first time and show up as a non-visual component.

When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.* references from the project, saving and restarting usually works.

Sorting a List<int>

double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)

{
    numbers[i] = double.Parse(Console.ReadLine());

}
Console.WriteLine("\n");

Array.Sort(numbers);

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(numbers[i]);

}

Console.ReadLine();

For loop for HTMLCollection elements

You want to change it to

var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
    console.log(list[key].id); //second console output
}

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

What's the right way to create a date in Java?

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

How to calculate an angle from three points?

If you mean the angle that P1 is the vertex of then using the Law of Cosines should work:

arccos((P122 + P132 - P232) / (2 * P12 * P13))

where P12 is the length of the segment from P1 to P2, calculated by

sqrt((P1x - P2x)2 + (P1y - P2y)2)

Adding subscribers to a list using Mailchimp's API v3

I got it working. I was adding the authentication to the header incorrectly:

$apikey = '<api_key>';
            $auth = base64_encode( 'user:'.$apikey );

            $data = array(
                'apikey'        => $apikey,
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array(
                    'FNAME' => $name
                )
            );
            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                        'Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

            $result = curl_exec($ch);

            var_dump($result);
            die('Mailchimp executed');

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

jQuery equivalent to Prototype array.last()

I use this:

array.reverse()[0]

You reverse the array with reverse() and then pick the first item of the reversed version with [0], that is the last one of the original array.

You can use this code if you don't care that the array gets reversed of course, because it will remain so.

How to run SQL script in MySQL?

Since mysql -u yourusername -p yourpassword yourdatabase < text_file did not work on a remote server (Amazon's EC2)...

Make sure that the Database is created first.

Then:

mysql --host=localhost --user=your_username --password=your_password your_database_name < pathTofilename.sql

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

Reload parent window from child window

You can reload parent window location using :

window.opener.location.href = window.opener.location.href;

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

Add column in dataframe from list

Old question; but I always try to use fastest code!

I had a huge list with 69 millions of uint64. np.array() was fastest for me.

df['hashes'] = hashes
Time spent: 17.034842014312744

df['hashes'] = pd.Series(hashes).values
Time spent: 17.141014337539673

df['key'] = np.array(hashes)
Time spent: 10.724546194076538

Only mkdir if it does not exist

mkdir -p

-p, --parents no error if existing, make parent directories as needed

Android: failed to convert @drawable/picture into a drawable

Also check if the resource-name contains any illegal characters (for me it was a "-" in my-image)

How can I divide two integers stored in variables in Python?

The 1./2 syntax works because 1. is a float. It's the same as 1.0. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float() on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division at the top of the module.

Is there any way to start with a POST request using Selenium?

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(12)
driver.set_page_load_timeout(10)

def _post_selenium(self, url: str, data: dict):
    input_template = '{k} <input type="text" name="{k}" id="{k}" value="{v}"><BR>\n'
    inputs = ""
    if data:
        for k, v in data.items():
            inputs += input_template.format(k=k, v=v)
    html = f'<html><body>\n<form action="{url}" method="post" id="formid">\n{inputs}<input type="submit" id="inputbox">\n</form></body></html>'

    html_file = os.path.join(os.getcwd(), 'temp.html')
    with open(html_file, "w") as text_file:
        text_file.write(html)

    driver.get(f"file://{html_file}")
    driver.find_element_by_id('inputbox').click()

_post_selenium("post.to.my.site.url", {"field1": "val1"})

driver.close()

Git stash pop- needs merge, unable to refresh index

Well, initially, we should know what caused the error to happen, then the solution will be easy. The reason have already been pointed out by the accepted answer, but it is somehow incomplete (also the solution).

The problem is, one or more files had conflict(s) previously, but Git sees them as unresolved. Yes, you might already edited those files and resolved the conflicts, but Git does not know about that. You should tell Git "Hey, there are no more conflicts from the previous merge!". Note that, the merge is not necessarily caused by a git merge, but also by a git stash pop, for example.

Remember, git status can tell you what Git knows now. If there are some unresolved merge conflicts to Git, then it is shown in a separated Unmerged paths section, with the files marked as both modified (always?). If you have noticed, this section is between two staged and unstaged sections. From this, I personally understand that, "Unmerged paths are those you should either move into staged or unstaged areas, as Git can work only with these two areas".

So, to tell Git the conflicts have been resolved, you should either move these changes to staged or unstaged areas. In recent versions of Git, when you do a git status, it tells you how (woah! You should ask yourself how you haven't seen this yet?):

$ git status
...
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   path/to/file.txt
...

So, to stage it (and maybe commit it):

$ git add path/to/file.txt

And to make it unstaged (e.g. you don't want to commit it now):

$ git restore --staged path/to/file.txt

Note: Forgetting to write --staged option possibly could spawn a super-hungry dragon to eat your past two days, in the case of not using a good text-editor or IDE.

Note: While git restore command is experimental yet, it should be stable enough to be used (thanks to a comment by @VonC, refer to it for more details on that).

What is TypeScript and why would I use it in place of JavaScript?

TypeScript's relation to JavaScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org.

JavaScript is a programming language that is developed by EMCA's Technical Committee 39, which is a group of people composed of many different stakeholders. TC39 is a committee hosted by ECMA: an internal standards organization. JavaScript has many different implementations by many different vendors (e.g. Google, Microsoft, Oracle, etc.). The goal of JavaScript is to be the lingua franca of the web.

TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.

Essentially TypeScript achieves its goals in three ways:

  1. Support for modern JavaScript features - The JavaScript language (not the runtime) is standardized through the ECMAScript standards. Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview). TypeScript allows for the use of many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing (see the list of compile targets under the --target compiler option). This means that you can safely use new features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backwards compatible with older browsers and JavaScript runtimes.

  2. Advanced type system - The type support is not part of the ECMAScript standard and will likely never be due to the interpreted nature instead of compiled nature of JavaScript. The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. The official website of TypeScript gives an overview of these features. Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful.

  3. Developer tooling support - TypeScript's compiler can run as a background process to support both incremental compilation and IDE integration such that you can more easily navigate, identify problems, inspect possibilities and refactor your codebase.

TypeScript's relation to other JavaScript targeting languages

TypeScript has a unique philosophy compared to other languages that compile to JavaScript. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can almost rename your .js files to .ts files and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript builds on the successes of JavaScript while improving on its weaknesses.

On the one hand, you have future proof tools that take modern ECMAScript standards and compile it down to older JavaScript versions with Babel being the most popular one. On the other hand, you have languages that may totally differ from JavaScript which target JavaScript, like CoffeeScript, Clojure, Dart, Elm, Haxe, Scala.js, and a whole host more (see this list). These languages, though they might be better than where JavaScript's future might ever lead, run a greater risk of not finding enough adoption for their futures to be guaranteed. You might also have more trouble finding experienced developers for some of these languages, though the ones you will find can often be more enthusiastic. Interop with JavaScript can also be a bit more involved, since they are farther removed from what JavaScript actually is.

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript is not a risky choice by any standard. It takes very little effort to get used to if you are familiar with JavaScript, since it is not a completely different language, has excellent JavaScript interoperability support and it has seen a lot of adoption recently.

Optionally static typing and type inference

JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript and catches type errors during compilation to JavaScript. Bugs that are caused by false assumptions of some variable being of a certain type can be completely eradicated if you play your cards right (how strict you type your code or if you type your code at all is up to you).

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var x = "hello" in TypeScript is the same as var x : string = "hello". The type is simply inferred from its use. Even it you don't explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.

TypeScript is optionally typed by default. For example function divideByTwo(x) { return x / 2 } is a valid function in TypeScript which can be called with any kind of parameter, even though calling it with a string will obviously result in a runtime error. Just like you are used to in JavaScript. This works, because when no type was explicitly assigned and the type could not be inferred, like in the divideByTwo example, TypeScript will implicitly assign the type any. This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any. There is a compiler flag to disallow this behavior: --noImplicitAny. Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing.

Types have a cost associated with them. First of all, there is a learning curve, and second of all, of course, it will cost you a bit more time to set up a codebase using proper strict typing too. In my experience, these costs are totally worth it on any serious codebase you are sharing with others. A Large Scale Study of Programming Languages and Code Quality in Github suggests that "statically typed languages, in general, are less defect prone than the dynamic types, and that strong typing is better than weak typing in the same regard".

It is interesting to note that this very same paper finds that TypeScript is less error-prone than JavaScript:

For those with positive coefficients we can expect that the language is associated with, ceteris paribus, a greater number of defect fixes. These languages include C, C++, JavaScript, Objective-C, Php, and Python. The languages Clojure, Haskell, Ruby, Scala, and TypeScript, all have negative coefficients implying that these languages are less likely than the average to result in defect fixing commits.

Enhanced IDE support

The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. This gives a couple of major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. Through code completion, you can get inline help on whatever functions a library might offer. No more need to remember them or look them up in online references. Compilation errors are reported directly in the IDE with a red squiggly line while you are busy coding. All in all, this allows for a significant gain in productivity compared to working with JavaScript. One can spend more time coding and less time debugging.

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime.

Strict null checks

Runtime errors of the form cannot read property 'x' of undefined or undefined is not a function are very commonly caused by bugs in JavaScript code. Out of the box TypeScript already reduces the probability of these kinds of errors occurring, since one cannot use a variable that is not known to the TypeScript compiler (with the exception of properties of any typed variables). It is still possible though to mistakenly utilize a variable that is set to undefined. However, with the 2.0 version of TypeScript you can eliminate these kinds of errors all together through the usage of non-nullable types. This works as follows:

With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let x : number = undefined will result in a compile error. This fits perfectly with type theory since undefined is not a number. One can define x to be a sum type of number and undefined to correct this: let x : number | undefined = undefined.

Once a type is known to be nullable, meaning it is of a type that can also be of the value null or undefined, the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefined through for example an if statement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

let x: number | undefined;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.

During the build, 2016 conference co-designer of TypeScript Anders Hejlsberg gave a detailed explanation and demonstration of this feature: video (from 44:30 to 56:30).

Compilation

To use TypeScript you need a build process to compile to JavaScript code. The build process generally takes only a couple of seconds depending of course on the size of your project. The TypeScript compiler supports incremental compilation (--watch compiler flag) so that all subsequent changes can be compiled at greater speed.

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. Source map information can be used by debugging utilities like the Chrome DevTools and other IDE's to relate the lines in the JavaScript to the ones that generated them in the TypeScript. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. Source map information works pretty well, it was around long before TypeScript, but debugging TypeScript is generally not as great as when using JavaScript directly. Take the this keyword for example. Due to the changed semantics of the this keyword around closures since ES2015, this may actually exists during runtime as a variable called _this (see this answer). This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. It should be noted that Babel suffers the exact same kind of issue.

There are a few other tricks the TypeScript compiler can do, like generating intercepting code based on decorators, generating module loading code for different module systems and parsing JSX. However, you will likely require a build tool besides the Typescript compiler. For example, if you want to compress your code you will have to add other tools to your build process to do so.

There are TypeScript compilation plugins available for Webpack, Gulp, Grunt and pretty much any other JavaScript build tool out there. The TypeScript documentation has a section on integrating with build tools covering them all. A linter is also available in case you would like even more build time checking. There are also a great number of seed projects out there that will get you started with TypeScript in combination with a bunch of other technologies like Angular 2, React, Ember, SystemJS, Webpack, Gulp, etc.

JavaScript interoperability

Since TypeScript is so closely related to JavaScript it has great interoperability capabilities, but some extra work is required to work with JavaScript libraries in TypeScript. TypeScript definitions are needed so that the TypeScript compiler understands that function calls like _.groupBy or angular.copy or $.fadeOut are not in fact illegal statements. The definitions for these functions are placed in .d.ts files.

The simplest form a definition can take is to allow an identifier to be used in any way. For example, when using Lodash, a single line definition file declare var _ : any will allow you to call any function you want on _, but then, of course, you are also still able to make mistakes: _.foobar() would be a legal TypeScript call, but is, of course, an illegal call at run-time. If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitions for an example).

Npm modules that come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation). For pretty much any other semi-popular JavaScript library that does not include its own definitions somebody out there has already made type definitions available through another npm module. These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped.

There is one caveat: the type definitions must match the version of the library you are using at run-time. If they do not, TypeScript might disallow you from calling a function or dereferencing a variable that exists or allow you to call a function or dereference a variable that does not exist, simply because the types do not match the run-time at compile-time. So make sure you load the right version of the type definitions for the right version of the library you are using.

To be honest, there is a slight hassle to this and it may be one of the reasons you do not choose TypeScript, but instead go for something like Babel that does not suffer from having to get type definitions at all. On the other hand, if you know what you are doing you can easily overcome any kind of issues caused by incorrect or missing definition files.

Converting from JavaScript to TypeScript

Any .js file can be renamed to a .ts file and ran through the TypeScript compiler to get syntactically the same JavaScript code as an output (if it was syntactically correct in the first place). Even when the TypeScript compiler gets compilation errors it will still produce a .js file. It can even accept .js files as input with the --allowJs flag. This allows you to start with TypeScript right away. Unfortunately, compilation errors are likely to occur in the beginning. One does need to remember that these are not show-stopping errors like you may be used to with other compilers.

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript checks all code for validity and thus it needs to know about all functions and variables that are used. Thus type definitions need to be in place for all of them otherwise compilation errors are bound to occur. As mentioned in the chapter above, for pretty much any JavaScript framework there are .d.ts files that can easily be acquired with the installation of DefinitelyTyped packages. It might, however, be that you've used some obscure library for which no TypeScript definitions are available or that you've polyfilled some JavaScript primitives. In that case, you must supply type definitions for these bits for the compilation errors to disappear. Just create a .d.ts file and include it in the tsconfig.json's files array, so that it is always considered by the TypeScript compiler. In it declare those bits that TypeScript does not know about as type any. Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs.

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. As mentioned in the chapter on compilation there are plenty of good resources out there and I encourage you to look for seed projects that use the combination of tools you want to be working with.

The biggest hurdle is the learning curve. I encourage you to play around with a small project at first. Look how it works, how it builds, which files it uses, how it is configured, how it functions in your IDE, how it is structured, which tools it uses, etc. Converting a large JavaScript codebase to TypeScript is doable when you know what you are doing. Read this blog for example on converting 600k lines to typescript in 72 hours). Just make sure you have a good grasp of the language before you make the jump.

Adoption

TypeScript is open-source (Apache 2 licensed, see GitHub) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project. It's a very active project; the TypeScript team has been releasing a lot of new features in the last few years and a lot of great ones are still planned to come (see the roadmap).

Some facts about adoption and popularity:

  • In the 2017 StackOverflow developer survey TypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category.
  • In the 2018 state of js survey TypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other).
  • In the 2019 StackOverlow deverloper survey TypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. It again took third place amongst most the most loved languages.

Why do people hate SQL cursors so much?

Can you post that cursor example or link to the question? There's probably an even better way than a recursive CTE.

In addition to other comments, cursors when used improperly (which is often) cause unnecessary page/row locks.

Reverting to a previous revision using TortoiseSVN

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

How to convert String to long in Java?

Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.

Which programming language for cloud computing?

That is a very interesting question.

On the Lang.Next conference there was a very interesting discussion about this topic, in which authors of several programming languages participate (Scala, Dart, C#). There was not a clear consensus at the end, but from my point of view there is one message:

The ideal language for this "cloud age" should be object oriented (because that is how we understand and are able to model the world) and also embrace functional programming.

The code in "cloud age" is almost always distributed: running on several cores/machines (in the cloud center) or just the client/server separation. And it is also asynchronous. We do not block the code when waiting for WS response. The callbacks come in any time.

When using standard imperative programming languages, handling the asynchrony and the distribution really complicated. You have to always take care of the "current state" and when the callbacks come in, you have to decide what to do, in dependences of this state.

Functional programming helps to eliminate the "state" and is much better suited for this new situation.

So I would say: In cloud computing the code is distributed, state-less, asynchronous. Functional programming can help you with that. Object oriented is almost a must to be able to model the world.

I have wrote a blog post about it, if you are interested. I like C#, but actually I would say Scala, Clojure, F# might fit even better.

On the other hand C++ will always be there, and lately is being modernized and getting more attention.

Git command to checkout any branch and overwrite local changes

Couple of points:

  • I believe git stash + git stash drop could be replaced with git reset --hard
  • ... or, even shorter, add -f to checkout command:

    git checkout -f -b $branch
    

    That will discard any local changes, just as if git reset --hard was used prior to checkout.

As for the main question: instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.

React img tag issue with url and class

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    

Android - Using Custom Font

Since I was not satisfied with all the presented solutions on SO, I've come up with mine. It's based on a little trick with tags (i.e. you can't use tags in your code), I put the font path there. So when defining views, you can do either this:

<TextView
        android:id="@+id/textViewHello1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 1"
        android:tag="fonts/Oswald-Regular.ttf"/>

or this:

<TextView
        android:id="@+id/textViewHello2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 2"
        style="@style/OswaldTextAppearance"/>

<style name="OswaldTextAppearance">
        <item name="android:tag">fonts/Oswald-Regular.ttf</item>
        <item name="android:textColor">#000000</item>
</style>

Now you can either explicitly access / setup the view as:

TextView textView = TextViewHelper.setupTextView(this, R.id.textViewHello1).setText("blah");

or just setup everything via:

TextViewHelper.setupTextViews(this, (ViewGroup) findViewById(R.id.parentLayout)); // parentLayout is the root view group (relative layout in my case)

And what is the magic class you ask? Mostly glued from another SO posts, with helper methods for both activity and fragments:

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

public class TextViewHelper {
    private static final Map<String, Typeface> mFontCache = new HashMap<>();

    private static Typeface getTypeface(Context context, String fontPath) {
        Typeface typeface;
        if (mFontCache.containsKey(fontPath)) {
            typeface = mFontCache.get(fontPath);
        } else {
            typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
            mFontCache.put(fontPath, typeface);
        }
        return typeface;
    }

    public static void setupTextViews(Context context, ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setupTextViews(context, (ViewGroup) child);
            } else {
                if (child != null) {
                    TextViewHelper.setupTextView(context, child);
                }
            }
        }
    }

    public static void setupTextView(Context context, View view) {
        if (view instanceof TextView) {
            if (view.getTag() != null) // also inherited from TextView's style
            {
                TextView textView = (TextView) view;
                String fontPath = (String) textView.getTag();
                Typeface typeface = getTypeface(context, fontPath);
                if (typeface != null) {
                    textView.setTypeface(typeface);
                }
            }
        }
    }

    public static TextView setupTextView(View rootView, int id) {
        TextView textView = (TextView) rootView.findViewById(id);
        setupTextView(rootView.getContext().getApplicationContext(), textView);
        return textView;
    }

    public static TextView setupTextView(Activity activity, int id) {
        TextView textView = (TextView) activity.findViewById(id);
        setupTextView(activity.getApplicationContext(), textView);
        return textView;
    }
}

How to $http Synchronous call with AngularJS

Since sync XHR is being deprecated, it's best not to rely on that. If you need to do a sync POST request, you can use the following helpers inside of a service to simulate a form post.

It works by creating a form with hidden inputs which is posted to the specified URL.

//Helper to create a hidden input
function createInput(name, value) {
  return angular
    .element('<input/>')
    .attr('type', 'hidden')
    .attr('name', name)
    .val(value);
}

//Post data
function post(url, data, params) {

    //Ensure data and params are an object
    data = data || {};
    params = params || {};

    //Serialize params
    const serialized = $httpParamSerializer(params);
    const query = serialized ? `?${serialized}` : '';

    //Create form
    const $form = angular
        .element('<form/>')
        .attr('action', `${url}${query}`)
        .attr('enctype', 'application/x-www-form-urlencoded')
        .attr('method', 'post');

    //Create hidden input data
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const value = data[key];
            if (Array.isArray(value)) {
                for (const val of value) {
                    const $input = createInput(`${key}[]`, val);
                    $form.append($input);
                }
            }
            else {
                const $input = createInput(key, value);
                $form.append($input);
            }
        }
    }

    //Append form to body and submit
    angular.element(document).find('body').append($form);
    $form[0].submit();
    $form.remove();
}

Modify as required for your needs.

Efficiently convert rows to columns in sql server

This is rather a method than just a single script but gives you much more flexibility.

First of all There are 3 objects:

  1. User defined TABLE type [ColumnActionList] -> holds data as parameter
  2. SP [proc_PivotPrepare] -> prepares our data
  3. SP [proc_PivotExecute] -> execute the script

CREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO

    CREATE PROCEDURE [dbo].[proc_PivotPrepare] 
    (
    @DB_Name        nvarchar(128),
    @TableName      nvarchar(128)
    )
    AS
            SELECT @DB_Name = ISNULL(@DB_Name,db_name())
    DECLARE @SQL_Code nvarchar(max)

    DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));

    SELECT @SQL_Code        =   'SELECT [<| SQL_Code |>] = '' '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----|'''
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''INSERT INTO  @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
                                        + 'FROM [' + @DB_Name + '].sys.columns  '
                                        + 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '                            
EXECUTE SP_EXECUTESQL @SQL_Code;

GO

CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions  ColumnActionList ReadOnly
,@TableName                     nvarchar(128)
)
AS


--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################

IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions; 
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;

--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################

DECLARE @ColumnName                     nvarchar(128)
DECLARE @Destiny                        nchar(1)

DECLARE @ListOfColumns_Stable           nvarchar(max)
DECLARE @ListOfColumns_Dimension    nvarchar(max)
DECLARE @ListOfColumns_Variable     nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################

DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
   END

CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;

--############################
--###| Cursor for List of Dimension Columns
--############################

DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
   END

CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;

--############################
--###| Cursor for List of Variable Columns
--############################

DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
   END

CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;

SELECT @ListOfColumns_Variable      = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable            = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);

--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB 
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';

DECLARE @DIM_ID smallint;
SELECT      @DIM_ID = 1;


DECLARE @SQL_Dimentions nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions; 

SELECT @SQL_Dimentions      = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
                                            + ' INTO ##ALL_Dimentions '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
                                            SELECT @DIM_ID = @DIM_ID + 1;
            WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
            BEGIN
            SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) +  ' IS NOT NULL ';
            SELECT @DIM_ID = @DIM_ID + 1;
            END

SELECT @SQL_Dimentions   = @SQL_Dimentions + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_Dimentions;

--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB 
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @StabPos_ID smallint;
SELECT      @StabPos_ID = 1;


DECLARE @SQL_MainStableColumnTable nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns; 

SELECT @SQL_MainStableColumnTable       = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
                                            + ' INTO ##ALL_StableColumns '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
                                            SELECT @StabPos_ID = @StabPos_ID + 1;
            WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
            BEGIN
            SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) +  ' IS NOT NULL ';
            SELECT @StabPos_ID = @StabPos_ID + 1;
            END

SELECT @SQL_MainStableColumnTable    = @SQL_MainStableColumnTable + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_MainStableColumnTable;

--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################

DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''

DECLARE @i smallint

IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab; 

SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
                                    + ' INTO ##FinalTab '
                                    +   'FROM ' + @TableName + ' t '
                                    +   'JOIN ##ALL_Dimentions dim '
                                    +   'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
                                SELECT @i = 2                               
                                WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
                                    BEGIN
                                    SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
                                    SELECT @i = @i +1
                                END
EXECUTE SP_EXECUTESQL @FULL_SQL_1

--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB 
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB 
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';

DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;


DECLARE @FinalCode nvarchar(max)

SELECT @FinalCode = ' SELECT ID1.*'
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                            BEGIN
                                                SELECT @z = 1
                                                WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
                                                    BEGIN
                                                        SELECT @FinalCode = @FinalCode +    ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] =  ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
                                                        SELECT @z = @z + 1
                                                    END
                                                    SELECT @y = @y + 1
                                                END
        SELECT @FinalCode = @FinalCode + 
                                        ' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                        BEGIN
                                            SELECT @x = 1
                                            SELECT @FinalCode = @FinalCode 
                                                                                + ' LEFT JOIN (SELECT ' +  @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable 
                                                                                + ' FROM ##FinalTab WHERE [xxx_ID_xxx] = ' 
                                                                                + CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))  
                                                                                + ' ON 1 = 1' 
                                                                                WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
                                                                                BEGIN
                                                                                    SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
                                                                                    SELECT @x = @x +1
                                                                                END
                                            SELECT @y = @y + 1
                                        END

SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;

From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)

Names and datatypes will be defined automatically!

I cant recommend it for any production environments but does the job for adhoc BI requests.

Testing web application on Mac/Safari when I don't own a Mac

https://turbo.net/ offers a browser sandbox in which containerised virtual machines run browser sessions for you. I tried it with Safari on my Windows development machine and it seems to work very well.

Change background color of edittext in android

Here the best way

First : make new xml file in res/drawable name it rounded_edit_text then paste this:

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Second: in res/layout copy and past following code (code of EditText)

<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

How to change the Jupyter start-up folder

After many tries I have done it. I have mentioned the easiest steps below:

  1. Right click on the jupyter launcher icon from start menu or desktop or anaconda navigator

  2. Now you need to change 2 things on the screen: Add your path to both target and start in the properties window

    Caveats:

    a. Your path needs to be in the same drive as the drive in which jupyter is installed. Since mine was in C drive, I used the following path "C:/JupyterWorkLibrary"

    b. For target, at the end of the existing path, i.e, after sript.py", add this after a space. Some people have mentioned removing %USERPROFILE% from target. I did not come across this. Image for jupyter properties

    c. For start in, add the same path. I have used a path without spaces to avoid issues. I would also suggest stick to using path in double quotes anyways d.I have also used forward slashes in the path

  3. Now just launch the notebook. It should open into the right folder.

Hope this helps.

PS: I am sure there are other ways, this worked for me. I am not even sure of the constraints mentioned. It's just that with these steps I could get my job done.

Proper use of errors

Simple solution to emit and show message by Exception.

try {
  throw new TypeError("Error message");
}
catch (e){
  console.log((<Error>e).message);//conversion to Error type
}

Caution

Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

Spring Boot default H2 jdbc connection (and H2 console)

From http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

H2 Web Console (H2ConsoleProperties):

spring.h2.console.enabled=true //Enable the console.
spring.h2.console.path=/h2-console //Path at which the console will be available.

Adding the above two lines to my application.properties file was enough to access the H2 database web console, using the default username (sa) and password (empty, as in don't enter a password when the ui prompts you).

HTML Display Current date

This helped me:

<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>    

Counting repeated characters in a string in Python

inputString =  input("Enter a String:")
countedArray = {}

for char in inputString:
    if char in countedArray:  
        countedArray[char] += 1    
    else:
        countedArray[char] = 1
    
print(countedArray) 

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

the answer is when you load the file, you need apply the "close" method, in any line of code, works to me

How to automatically generate a stacktrace when my program crashes

As a Windows-only solution, you can get the equivalent of a stack trace (with much, much more information) using Windows Error Reporting. With just a few registry entries, it can be set up to collect user-mode dumps:

Starting with Windows Server 2008 and Windows Vista with Service Pack 1 (SP1), Windows Error Reporting (WER) can be configured so that full user-mode dumps are collected and stored locally after a user-mode application crashes. [...]

This feature is not enabled by default. Enabling the feature requires administrator privileges. To enable and configure the feature, use the following registry values under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps key.

You can set the registry entries from your installer, which has the required privileges.

Creating a user-mode dump has the following advantages over generating a stack trace on the client:

  • It's already implemented in the system. You can either use WER as outlined above, or call MiniDumpWriteDump yourself, if you need more fine-grained control over the amount of information to dump. (Make sure to call it from a different process.)
  • Way more complete than a stack trace. Among others it can contain local variables, function arguments, stacks for other threads, loaded modules, and so on. The amount of data (and consequently size) is highly customizable.
  • No need to ship debug symbols. This both drastically decreases the size of your deployment, as well as makes it harder to reverse-engineer your application.
  • Largely independent of the compiler you use. Using WER does not even require any code. Either way, having a way to get a symbol database (PDB) is very useful for offline analysis. I believe GCC can either generate PDB's, or there are tools to convert the symbol database to the PDB format.

Take note, that WER can only be triggered by an application crash (i.e. the system terminating a process due to an unhandled exception). MiniDumpWriteDump can be called at any time. This may be helpful if you need to dump the current state to diagnose issues other than a crash.

Mandatory reading, if you want to evaluate the applicability of mini dumps:

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

How to convert an enum type variable to a string?

Personally, I would go for something simple and use an operator to do so.

Considering the following enum:

enum WeekDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

We can create an operator to output the result in an std::ostream.

std::ostream &operator<<(std::ostream &stream, const WeekDay day) {
  switch (day) {
    case MONDAY:
      stream << "Monday";
      break;
    case TUESDAY:
      stream << "Tuesday";
      break;
    case WEDNESDAY:
      stream << "Wednesday";
      break;
    case THURSDAY:
      stream << "Thursday";
      break;
    case FRIDAY:
      stream << "Friday";
      break;
    case SATURDAY:
      stream << "Saturday";
      break;
    case SUNDAY:
      stream << "Sunday";
      break;
  }

  return stream;
}

The boilerplate code is indeed pretty big compared to some other methods presented in this thread. Still, it has the avantage of being pretty straightforward and easy to use.

std::cout << "First day of the week is " << WeekDay::Monday << std::endl;

How to use icons and symbols from "Font Awesome" on Native Android Application

As above is great example and works great:

Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf" );

Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);

BUT! > this will work if string inside button you set from xml:

<string name="icon_heart">&#xf004;</string>
button.setText(getString(R.string.icon_heart));

If you need to add it dynamically can use this:

String iconHeart = "&#xf004;";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
button.setText((char) valLong + "");

How to display line numbers in 'less' (GNU)

You can set an enviroment variable to always have these options apply to all less'd file:

export LESS='-RS#3NM~g'

git rm - fatal: pathspec did not match any files

In your case, use git filter-branch instead of git rm.

git rm will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images.

The git filter-branch, on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them.

  1. Use the command

    git filter-branch --force --index-filter \
      'git rm -r --cached --ignore-unmatch public/photos' \
      --prune-empty --tag-name-filter cat -- --all
    
  2. After the filter branch is complete, verify that no unintended file was lost.

  3. Now add a .gitignore rule

    echo public/photos >> .gitignore
    git add .gitignore && git commit -m "ignore rule for photos"
    
  4. Now do a push

    git push -f origin branch
    

Check this, this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions.

As for your orignial error message, it is happening because you already untracked them using git rm, and hence git is complaining because it can't remove a file it isn't tracking. Read more about this here.

How to create a sticky footer that plays well with Bootstrap 3

What worked for me was adding the position relative to the html tag.

html {
  min-height:100%;
  position:relative;
}
body {
  margin-bottom:60px;
}
footer {
  position:absolute;
  bottom:0;
  height:60px;
}

Removing whitespace between HTML elements when using line breaks

You could use CSS. Setting display:block, or float:left on the images will let you have define your own spacing and format the HTML however you want but will affect the layout in ways that might or might not be appropriate.

Otherwise you are dealing with inline content so the HTML formatting is important - as the images will effectively act like words.

Changing Underline color

You can use this CSS to "simulate" an underline:

text-decoration: none;
border-bottom: 1px solid #000;

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from: https://dev.mysql.com/downloads/connector/python/

Iterating through all the cells in Excel VBA or VSTO 2005

My VBA skills are a little rusty, but this is the general idea of what I'd do.
The easiest way to do this would be to iterate through a loop for every column:

public sub CellProcessing()
on error goto errHandler

    dim MAX_ROW as Integer   'how many rows in the spreadsheet
    dim i as Integer
    dim cols as String

    for i = 1 to MAX_ROW
        'perform checks on the cell here
        'access the cell with Range("A" & i) to get cell A1 where i = 1
    next i

exitHandler:
    exit sub
errHandler:
    msgbox "Error " & err.Number & ": " & err.Description
    resume exitHandler
end sub

it seems that the color syntax highlighting doesn't like vba, but hopefully this will help somewhat (at least give you a starting point to work from).

  • Brisketeer

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Depend on a branch or tag using a git URL in a package.json?

per @dantheta's comment:

As of npm 1.1.65, Github URL can be more concise user/project. npmjs.org/doc/files/package.json.html You can attach the branch like user/project#branch

So

"babel-eslint": "babel/babel-eslint",

Or for tag v1.12.0 on jscs:

"jscs": "jscs-dev/node-jscs#v1.12.0",

Note, if you use npm --save, you'll get the longer git

From https://docs.npmjs.com/cli/v6/configuring-npm/package-json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls are of the form:

git+ssh://[email protected]:npm/cli.git#v1.0.27 git+ssh://[email protected]:npm/cli#semver:^5.0 git+https://[email protected]/npm/cli.git
git://github.com/npm/cli.git#v1.0.27

If #<commit-ish> is provided, it will be used to clone exactly that commit. If > the commit-ish has the format #semver:<semver>, <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

GitHub URLs

As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:

{
 "name": "foo",
 "version": "0.0.0",
 "dependencies": {
   "express": "expressjs/express",
   "mocha": "mochajs/mocha#4727d357ea",
   "module": "user/repo#feature\/branch"
 }
}```

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

Sadly, they want us to use a tag to let their browser know what to do. Look at this documentation, it tell us to use:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

and it should do.

reducing number of plot ticks

Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params,

pyplot.locator_params(nbins=4)

You can specify specific axis in this method as mentioned below, default is both:

# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)

Get exception description and stack trace which caused an exception, all as a string

You might also consider using the built-in Python module, cgitb, to get some really good, nicely formatted exception information including local variable values, source code context, function parameters etc..

For instance for this code...

import cgitb
cgitb.enable(format='text')

def func2(a, divisor):
    return a / divisor

def func1(a, b):
    c = b - 5
    return func2(a, c)

func1(1, 5)

we get this exception output...

ZeroDivisionError
Python 3.4.2: C:\tools\python\python.exe
Tue Sep 22 15:29:33 2015

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

 c:\TEMP\cgittest2.py in <module>()
    7 def func1(a, b):
    8   c = b - 5
    9   return func2(a, c)
   10
   11 func1(1, 5)
func1 = <function func1>

 c:\TEMP\cgittest2.py in func1(a=1, b=5)
    7 def func1(a, b):
    8   c = b - 5
    9   return func2(a, c)
   10
   11 func1(1, 5)
global func2 = <function func2>
a = 1
c = 0

 c:\TEMP\cgittest2.py in func2(a=1, divisor=0)
    3
    4 def func2(a, divisor):
    5   return a / divisor
    6
    7 def func1(a, b):
a = 1
divisor = 0
ZeroDivisionError: division by zero
    __cause__ = None
    __class__ = <class 'ZeroDivisionError'>
    __context__ = None
    __delattr__ = <method-wrapper '__delattr__' of ZeroDivisionError object>
    __dict__ = {}
    __dir__ = <built-in method __dir__ of ZeroDivisionError object>
    __doc__ = 'Second argument to a division or modulo operation was zero.'
    __eq__ = <method-wrapper '__eq__' of ZeroDivisionError object>
    __format__ = <built-in method __format__ of ZeroDivisionError object>
    __ge__ = <method-wrapper '__ge__' of ZeroDivisionError object>
    __getattribute__ = <method-wrapper '__getattribute__' of ZeroDivisionError object>
    __gt__ = <method-wrapper '__gt__' of ZeroDivisionError object>
    __hash__ = <method-wrapper '__hash__' of ZeroDivisionError object>
    __init__ = <method-wrapper '__init__' of ZeroDivisionError object>
    __le__ = <method-wrapper '__le__' of ZeroDivisionError object>
    __lt__ = <method-wrapper '__lt__' of ZeroDivisionError object>
    __ne__ = <method-wrapper '__ne__' of ZeroDivisionError object>
    __new__ = <built-in method __new__ of type object>
    __reduce__ = <built-in method __reduce__ of ZeroDivisionError object>
    __reduce_ex__ = <built-in method __reduce_ex__ of ZeroDivisionError object>
    __repr__ = <method-wrapper '__repr__' of ZeroDivisionError object>
    __setattr__ = <method-wrapper '__setattr__' of ZeroDivisionError object>
    __setstate__ = <built-in method __setstate__ of ZeroDivisionError object>
    __sizeof__ = <built-in method __sizeof__ of ZeroDivisionError object>
    __str__ = <method-wrapper '__str__' of ZeroDivisionError object>
    __subclasshook__ = <built-in method __subclasshook__ of type object>
    __suppress_context__ = False
    __traceback__ = <traceback object>
    args = ('division by zero',)
    with_traceback = <built-in method with_traceback of ZeroDivisionError object>

The above is a description of an error in a Python program.  Here is
the original traceback:

Traceback (most recent call last):
  File "cgittest2.py", line 11, in <module>
    func1(1, 5)
  File "cgittest2.py", line 9, in func1
    return func2(a, c)
  File "cgittest2.py", line 5, in func2
    return a / divisor
ZeroDivisionError: division by zero

How do I match any character across multiple lines in a regular expression?

Note that (.|\n)* can be less efficient than (for example) [\s\S]* (if your language's regexes support such escapes) and than finding how to specify the modifier that makes . also match newlines. Or you can go with POSIXy alternatives like [[:space:][:^space:]]*.

Android Viewpager as Image Slide Gallery

Hi if your are looking for simple android image sliding with circle indicator you can download the complete code from here http://javaant.com/viewpager-with-circle-indicator-in-android/#.VysQQRV96Hs . please check the live demo which will give the clear idea.

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

Could not resolve all dependencies for configuration ':classpath'

The solution is in your build.gradle change this block:

allprojects {
  repositories {
    jcenter()
    google()
  }
}

to google in first position :

allprojects {
  repositories {
    google()
    jcenter()
  }
}

Display current date and time without punctuation

Interesting/funny way to do this using parameter expansion (requires bash 4.4 or newer):

${parameter@operator} - P operator

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.

$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251

How can I show figures separately in matplotlib?

Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py, etc).

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

Checking for a null int value from a Java ResultSet

Just check if the field is null or not using ResultSet#getObject(). Substitute -1 with whatever null-case value you want.

int foo = resultSet.getObject("foo") != null ? resultSet.getInt("foo") : -1;

Or, if you can guarantee that you use the right DB column type so that ResultSet#getObject() really returns an Integer (and thus not Long, Short or Byte), then you can also just typecast it to an Integer.

Integer foo = (Integer) resultSet.getObject("foo");

How do I use the CONCAT function in SQL Server 2008 R2?

I suggest you cast all columns before you concat them

cast('data1' as varchar) + cast('data2' as varchar) + cast('data3' as varchar)

This should work for you.

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

Disable submit button ONLY after submit

Test with a setTimeout, that worked for me and I could submit my form, refers to this answer https://stackoverflow.com/a/779785/5510314

$(document).ready(function () {
    $("#btnSubmit").click(function () {
        setTimeout(function () { disableButton(); }, 0);
    });

    function disableButton() {
        $("#btnSubmit").prop('disabled', true);
    }
});

Copy all values from fields in one class to another through reflection

This is a late post, but can still be effective for people in future.

Spring provides a utility BeanUtils.copyProperties(srcObj, tarObj) which copies values from source object to target object when the names of the member variables of both classes are the same.

If there is a date conversion, (eg, String to Date) 'null' would be copied to the target object. We can then, explicitly set the values of the date as required.

The BeanUtils from Apache Common throws an error when there is a mismatch of data-types (esp. conversion to and from Date)

Hope this helps!

How to combine 2 plots (ggplot) into one plot?

Dummy data (you should supply this for us)

visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))

combine:

visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour

Now do:

 ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) + 
   geom_point() + geom_smooth()

and adjust colours etc to taste.

enter image description here

What is Express.js?

Express is a module framework for Node that you can use for applications that are based on server/s that will "listen" for any input/connection requests from clients. When you use it in Node, it is just saying that you are requesting the use of the built-in Express file from your Node modules.

Express is the "backbone" of a lot of Web Apps that have their back end in NodeJS. From what I know, its primary asset being the providence of a routing system that handles the services of "interaction" between 2 hosts. There are plenty of alternatives for it, such as Sails.

How to initialise a string from NSData in Swift

Objective - C

NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);

Swift

//This your data containing the string
   let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)

   //Use this method to convert the data into String
   let myStringFromData =  String(data:myStringData!, encoding: NSUTF8StringEncoding)

   print("My string value:" + myStringFromData!)

http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

@PreRemove
private void removeGroupsFromUsers() {
    for (User u : users) {
        u.getGroups().remove(this);
    }
}

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

How can I copy a file on Unix using C?

There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now:

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int cp(const char *to, const char *from)
{
    int fd_to, fd_from;
    char buf[4096];
    ssize_t nread;
    int saved_errno;

    fd_from = open(from, O_RDONLY);
    if (fd_from < 0)
        return -1;

    fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
    if (fd_to < 0)
        goto out_error;

    while (nread = read(fd_from, buf, sizeof buf), nread > 0)
    {
        char *out_ptr = buf;
        ssize_t nwritten;

        do {
            nwritten = write(fd_to, out_ptr, nread);

            if (nwritten >= 0)
            {
                nread -= nwritten;
                out_ptr += nwritten;
            }
            else if (errno != EINTR)
            {
                goto out_error;
            }
        } while (nread > 0);
    }

    if (nread == 0)
    {
        if (close(fd_to) < 0)
        {
            fd_to = -1;
            goto out_error;
        }
        close(fd_from);

        /* Success! */
        return 0;
    }

  out_error:
    saved_errno = errno;

    close(fd_from);
    if (fd_to >= 0)
        close(fd_to);

    errno = saved_errno;
    return -1;
}

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.