Programs & Examples On #Tandem

Tandem Computers, Inc. was the dominant manufacturer of fault-tolerant computer systems for ATM networks, banks, stock exchanges, telephone switching centers, and other similar commercial transaction processing applications requiring maximum uptime and zero data loss. The company was founded in 1974 and remained independent until 1997. It is now a server division within Hewlett Packard.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

A pitfall some might step into that is covered by this question but isn't addressed in the answers as it is slightly different in the code structure but returns the exact same error.

This error occurs when using bindActionCreators and not passing the dispatch function

Error Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

Fixed Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
    }, dispatch);

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

The function dispatch was missing in the Error code

Python equivalent of a given wget command

urllib.request should work. Just set it up in a while(not done) loop, check if a localfile already exists, if it does send a GET with a RANGE header, specifying how far you got in downloading the localfile. Be sure to use read() to append to the localfile until an error occurs.

This is also potentially a duplicate of Python urllib2 resume download doesn't work when network reconnects

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

Can I set background image and opacity in the same property?

I just added position=absolute,top=0,width=100% in the #main and set the opacity value to the #background

#main{height:100%;position:absolute; top:0;width:100%}
#background{//same height as main;background-image:url(image URL);opacity:0.2}

I applied the background to a div before the main.

Java Process with Input/Output Stream

I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

Thread T=new Thread(new Runnable() {

    public void run() {
            String input = scan.nextLine();
            input += "\n";
            try {
            } catch (IOException e) {
                // TODO Auto-generated catch block


} );

and you can reader will be same as above i.e.

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);

make your writer as final otherwise it wont be able to accessible by inner class.

SVG Positioning

There are two ways to group multiple SVG shapes and position the group:

The first to use <g> with transform attribute as Aaron wrote. But you can't just use a x attribute on the <g> element.

The other way is to use nested <svg> element.

<svg id="parent">
   <svg id="group1" x="10">
      <!-- some shapes -->

In this way, the #group1 svg is nested in #parent, and the x=10 is relative to the parent svg. However, you can't use transform attribute on <svg> element, which is quite the contrary of <g> element.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

The other answers only show the changed files.

git log -p DIR is very useful, if you need the full diff of all changed files in a specific subdirectory.

Example: Show all detailed changes in a specific version range

git log -p 8a5fb..HEAD -- A B

commit 62ad8c5d
Author: Scott Tiger
Date:   Mon Nov 27 14:25:29 2017 +0100

    My comment

@@ -216,6 +216,10 @@ public class MyClass {

+  Added
-  Deleted

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.ContentType = "application/json; charset=utf-8";

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

Using setTimeout to delay timing of jQuery actions

Try this:

function explode(){
setTimeout(explode, 2000);

How to make an Android device vibrate? with different frequency?

Above answer is very correct but I'm giving an easy step to do it:

 private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };

  public void longVibrate(View v) 

  private void vibrateMulti(long[] cycles) {
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      Notification notification = new Notification();

      notification.vibrate = cycles; 
      notificationManager.notify(0, notification);

And then in your xml file:

<button android:layout_height="wrap_content" 
        android:layout_width ="wrap_content" 
        android:onclick      ="longVibrate" 
        android:text         ="VibrateThrice">

That's the easiest way.

How to count number of records per day?

You could also try this:

SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Your code probably isn't using a correct machine name, you should double check that.

Your error is:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

This is the result you get when a machine is not reachable. So the firewall suggestions are reasonable, but in this case probably not correct because you say this works:

Get-WmiObject win32_SystemEnclosure -Computer hostname

So in your case it seems when this line is executed:

Get-WmiObject win32_SystemEnclosure -Computer $_

$_ doesn't contain a proper computer name. You could check type and contents of $_. Probably there is a problem with the file contents. If the file looks right, then maybe the lines are not properly terminated. Maybe take a closer look using Write-Host:

ForEach ($_ in gc u:\pub\list.txt) {
    Write-Host "Get-WmiObject win32_SystemEnclosure -Computer '$_'"
    Get-WmiObject win32_SystemEnclosure -Computer $_ | select serialnumber | format-table -auto @{Label="Hostname"; Expression={$_}}, @{Label="Service Tag"; Expression={$_.serialnumber}}

How to access full source of old commit in BitBucket?

Just in case anyone is in my boat where none of these answers worked exactly, here's what I did.

Perhaps our in house Bitbucket server is set up a little differently than most, but here's the URL that I'd normally go to just to view the files in the master branch:


If I select a different branch than master from the drop down menu, I get this:


So I tried doing this and it worked:


Now I can browse the whole repo as it was at the time of that commit.

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream: -> player.getName().contains(name))

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

HashSet vs. List performance

It's essentially pointless to compare two structures for performance that behave differently. Use the structure that conveys the intent. Even if you say your List<T> wouldn't have duplicates and iteration order doesn't matter making it comparable to a HashSet<T>, its still a poor choice to use List<T> because its relatively less fault tolerant.

That said, I will inspect some other aspects of performance,

| Collection | Random | Containment | Insertion | Addition |  Removal | Memory    |
|            | access |             |           |          |          |           |
| List<T>    | O(1)   | O(n)        | O(n)      | O(1)*    | O(n)     | Lesser    |
| HashSet<T> | O(n)   | O(1)        | n/a       | O(1)     | O(1)     | Greater** |
  • Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.

  • The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. This article might give you an idea.

Write-back vs Write-Through caching?

maybe this article can help you link here

Write-through: Write is done synchronously both to the cache and to the backing store.

Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.

Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.

Unable to ping vmware guest from another vmware guest

  1. Check the firewall on all the windows system. If it's enabled, disable it.
  2. If you still are unable to ping, Open the virtual network editor and check if you are using the same VMnet adapter for both the VM's, this adapter should be present in the host machine's network adapters as well. Share a screenshot of what you are seeing in the virtual network editor.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:


We can capture IDENTITY values in a table variable for further consumption.


-- minor change to INSERT statement; add an OUTPUT clause:
  OUTPUT inserted.ID INTO @IDs(ID)


The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

What is the garbage collector in Java?

Garbage collector can be viewed as a reference count manager. if an object is created and its reference is stored in a variable, its reference count is increased by one. during the course of execution if that variable is assigned with NULL. reference count for that object is decremented. so the current reference count for the object is 0. Now when Garbage collector is executed, It checks for the objects with reference count 0. and frees the resources allocated to it.

Garbage collector invocation is controlled by garbage collection policies.

You can get some data here.

Deleting row from datatable in C#

Advance for loop works better for this case

public void deleteRow(DataRow selectedRow)
            foreach (DataRow  in StudentTable.Rows)
                if (SR[TableColumn.StudentID.ToString()].ToString() == StudentIndex)


What is object serialization?

Return the file as an Object :


        public class SerializeDemo
           public static void main(String [] args)
              Employee e = new Employee();
     = "Reyan Ali";
              e.address = "Phokka Kuan, Ambehta Peer";
              e.SSN = 11122333;
              e.number = 101;

                 FileOutputStream fileOut =
                 new FileOutputStream("/tmp/employee.ser");
                 ObjectOutputStream out = new ObjectOutputStream(fileOut);
                 System.out.printf("Serialized data is saved in /tmp/employee.ser");
              }catch(IOException i)

    public class DeserializeDemo
       public static void main(String [] args)
          Employee e = null;
             FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             e = (Employee) in.readObject();
          }catch(IOException i)
          }catch(ClassNotFoundException c)
             System.out.println("Employee class not found");
          System.out.println("Deserialized Employee...");
          System.out.println("Name: " +;
          System.out.println("Address: " + e.address);
          System.out.println("SSN: " + e.SSN);
          System.out.println("Number: " + e.number);

Document Root PHP

<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
    <br />
<a href="/hello.html">go to with html</a>

Try this yourself and find that they are not exactly the same.

$_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

HTML's / renders the root of the server url, in my case, localhost/

But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
    if ($result->num_rows > 0)
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
                $start = 0;
                $end = $per_page;

            $start = 0;
            $end = $per_page;

        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
            if (isset($_GET['page']) && $_GET['page'] == $i)
                echo  $i . " ";
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";

        echo "</p>";

        echo "No result to display.";

    echo "Error: " . $mysqli->error;


Ping a site in Python?

using subprocess ping command to ping decode it because the response is binary:

import subprocess
ping_response = subprocess.Popen(["ping", "-a", ""], stdout=subprocess.PIPE)
result = ping_response.decode('utf-8')

Check if string ends with one of the strings from a list

another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

How do I clear a C++ array?


Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

Build Android Studio app via command line

For Mac use this command

  ./gradlew task-name

How does Google calculate my location on a desktop?

  • So Google keep records of Wifi router location by using any cellphone GPS that connected to that router when you use Google maps or location on cellphone. then google knows every device that connected to that Wifi router uses the same location.
  • when GPS off or no cellphone connected to router Google uses IP geolocation

MySQL compare DATE string with string from DATETIME field

If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:

WHERE startTime = '2010-04-29'

because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes

WHERE startTime = '2010-04-29 00:00:00'

Certainly not what you want!

The condition is a range and hence it should be given as range. There are several possibilities:

WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)

There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.

Both variants can use an index on startTime which will become important when the table grows.

jQuery posting JSON

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',

if you pass an object as jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

Difference between Return and Break statements

break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

 <input type="text" id="input1" value="">

<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();

Object Dump JavaScript

for better readability you can convert the object to a json string as below:

console.log(obj, JSON.stringify(obj));

Check if value exists in Postgres array

When looking for the existence of a element in an array, proper casting is required to pass the SQL parser of postgres. Here is one example query using array contains operator in the join clause:

For simplicity I only list the relevant part:

table1 other_name text[]; -- is an array of text

The join part of SQL shown

from table1 t1 join table2 t2 on t1.other_name::text[] @> ARRAY[t2.panel::text]

The following also works

on t2.panel = ANY(t1.other_name)

I am just guessing that the extra casting is required because the parse does not have to fetch the table definition to figure the exact type of the column. Others please comment on this.

How to obtain the start time and end time of a day?

I think the easiest would be something like:

// Joda Time

DateTime dateTime=new DateTime(); 

StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();

These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

Twitter Bootstrap - full width navbar

I'm very late to the party but this answer pulls up top in Google search results.

Bootstrap 3 has an answer for this built in, set your container div in your navbar to container-fluid and it'll fall to screen width.

Like so:

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container-fluid">
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li><a href="/">More Stuff</a></li>

How do I create dynamic variable names inside a loop?

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

iOS: set font size of UILabel Programmatically

This code is perfectly working for me.

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
  [label setFont:[UIFont systemFontOfSize:11]];

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks


They have a different human-readable meaning.

However, depending on the query optimizer, they may have the same meaning to the machine.

You should always code to be readable.

That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.

Add leading zeroes to number in Java?

String.format (

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
                new += so_far[i]    # same value as before
        so_far = new


I tried to write it for py3k with a py2k ide, be careful with errors.

'No JUnit tests found' in Eclipse

Some time if lots if Test files are there then Eclipse failed to pass -classpath options for all libs and path due to classpath param lenght limitations. To Solve it go to Run

Configerations -> JUnit -> Your Project Config -> ClassPath -> Check "Use Temporary Jar Options"

At least it solved my problem.

Usage of \b and \r in C

The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.

How do you find out which version of GTK+ is installed on Ubuntu?

This suggestion will tell you which minor version of 2.0 is installed. Different major versions will have different package names because they can co-exist on the system (in order to support applications built with older versions).

Even for development files, which normally would only let you have one version on the system, you can have a version of gtk 1.x and a version of gtk 2.0 on the same system (the include files are in directories called gtk-1.2 or gtk-2.0).

So in short there isn't a simple answer to "what version of GTK is on the system". But...

Try something like:

dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]'

to list all the libgtk packages, including -dev ones, that are on your system. dpkg -l will list all the packages that dpkg knows about, including ones that aren't currently installed, so I've used grep to list only ones that are installed (line starts with i).

Alternatively, and probably better if it's the version of the headers etc that you're interested in, use pkg-config:

pkg-config --modversion gtk+

will tell you what version of GTK 1.x development files are installed, and

pkg-config --modversion gtk+-2.0

will tell you what version of GTK 2.0. The old 1.x version also has its own gtk-config program that does the same thing. Similarly, for GTK+ 3:

pkg-config --modversion gtk+-3.0

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

How to "set a breakpoint in malloc_error_break to debug"

Set a breakpoint on malloc_error_break() by opening the Breakpoint Navigator (View->Navigators->Show Breakpoint Navigator or ?8), clicking the plus button in the lower left corner, and selecting "Add Symbolic Breakpoint". In the popup that comes up, enter malloc_error_break in the Symbol field, then click Done.

EDIT: openfrog added a screenshot and indicated that he's already tried these steps without success after I posted my answer. With that edit, I'm not sure what to say. I haven't seen that fail to work myself, and indeed I always keep a breakpoint on malloc_error_break set.

mongodb service is not starting up

just re-installed mongo and it worked. No collections lost. Easiest solution atleast for me

Disable same origin policy in Chrome

For Windows users:

The problem with the solution accepted here, in my opinion is that if you already have Chrome open and try to run this it won't work.

However, when researching this, I came across a post on Super User, Is it possible to run Chrome with and without web security at the same time?.

Basically, by running the following command (or creating a shortcut with it and opening Chrome through that)

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

you can open a new "insecure" instance of Chrome at the same time as you keep your other "secure" browser instances open and working as normal. Important: delete/clear C:/Chrome dev session folder every time when you open a window as second time --disable-web-security is not going to work. So you cannot save your changes and then open it again as a second insecure instance of Chrome with --disable-web-security.

C# Get a control's position on a form

You can use the controls PointToScreen method to get the absolute position with respect to the screen.

You can do the Forms PointToScreen method, and with basic math, get the control's position.

Update R using RStudio

If you are using windows, you can use installr. Example usage here

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I don't have Anaconda so the steps I took are:

  • brew uninstall python3
  • brew install python3
    • got an error message stating,Your Xcode (10.2) is too outdated. Please update to Xcode 11.3 (or delete it). Xcode can be updated from the App Store.**So, I deleted Xcode since no update would show, then I reinstalled it.
    • ran xcode-select --install after. If you don't.. you'll get an error: The following formula python cannot be installed as binary package and must be built from source. Install the Command Line Tools: xcode-select --install
  • ran brew install python3 and it completed successfully.

Used this script just to see if it works

import requests
r = requests.get('')

Ran the script python3 and python3.7 and output was <Response [200]> instead of SSLError.

Should I use pt or px?

pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.

px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.

Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "captital" characters where placed in a box (case) above the non-captitalized characters which were place in a box below, and thus the "lower" case.

There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.

Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.

Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.

Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch repectivly.

Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.

Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.

As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.

EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.

How can I cast int to enum?

You simply use Explicit conversion Cast int to enum or enum to int

class Program
    static void Main(string[] args)
        Console.WriteLine((int)Number.three); //Output=3

        Console.WriteLine((Number)3);// Outout three

    public enum Number
        Zero = 0,
        One = 1,
        Two = 2,
        three = 3

Static methods in Python?

You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

Mostly, you just use functions though...

Storing images in SQL Server?

I would prefer to store the image in a directory, then store a reference to the image file in the database.

However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.

You can read more about using filegroups here

Tried to Load Angular More Than Once

I had this problem when missing a closing tag in the html.

enter image description here

So instead of:

<table></table> HTML was


Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..

Solution was to fix the missing closing tag.

Getting Unexpected Token Export

To use ES6 add babel-preset-env

and in your .babelrc:

  "presets": ["@babel/preset-env"]

Answer updated thanks to @ghanbari comment to apply babel 7.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))


As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can use the HTML5 pattern attribute or use JavaScript.

The pattern could look for example like this:

<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />

But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.

As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.

Selecting a row of pandas series/dataframe by integer index

To index-based access to the pandas table, one can also consider numpy.as_array option to convert the table to Numpy array as

np_df = df.as_matrix()

and then


would work.

adb command not found

Type the below command in terminal:

nano .bash_profile

And add the following lines (replace USERNAME with your own user name).

export ANDROID_HOME=/Users/USERNAME/Library/Android/sdk 
export PATH=${PATH}:${ANDROID_HOME}/tools 
export PATH=${PATH}:${ANDROID_HOME}/platform-tools

Close the text editor, and then enter the command below:

source .bash_profile

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Rails - Could not find a JavaScript runtime?

if you already install nodejs from source for example, and execjs isn't recognizing it you might want to try this tip:

Convert String to System.IO.Stream

Try this:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);


// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.putExtra("EXIT", true);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

Convert date to YYYYMM format

A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:


Adds two zeros to the right side of the year and then adds the month to the added two zeros.

How to change background color in the Notepad++ text editor?

You may need admin access to do it on your system.

  1. Create a folder 'themes' in the Notepad++ installation folder i.e. C:\Program Files (x86)\Notepad++
  2. Search or visit pages like to download the favourite theme. It will be an SML file.
    • Note: I prefer Neon any day.
  3. Download the themes from the site and drag them to the themes folder.
    • Note: I was unable to copy-paste or create new files in 'themes' folder so I used drag and that worked.
  4. Follow the steps provided by @triforceofcourage to select the new theme in Notepad++ preferences.

How to change the MySQL root account password on CentOS7?

Use the below Steps to reset the password.

$ sudo systemctl start mysqld

Reset the MySql server root password.

$sudo grep 'temporary password' /var/log/mysqld.log

Output Something like-:

 10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa

Use the above password during reset mysql_secure_installation process.

    $ sudo mysql_secure_installation
   Securing the MySQL server deployment.

   Enter password for user root: 

You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.

$ mysql -u root -p

Is there a way to override class variables in Java?

Variables don't take part in overrinding. Only methods do. A method call is resolved at runtime, that is, the decision to call a method is taken at runtime, but the variables are decided at compile time only. Hence that variable is called whose reference is used for calling and not of the runtime object.

Take a look at following snippet:

package com.demo;

class Bike {
  int max_speed = 90;
  public void disp_speed() {
    System.out.println("Inside bike");

public class Honda_bikes extends Bike {
  int max_speed = 150;
  public void disp_speed() {
    System.out.println("Inside Honda");

public static void main(String[] args) {
    Honda_bikes obj1 = new Honda_bikes();
    Bike obj2 = new Honda_bikes();
    Bike obj3 = new Bike();


    System.out.println("Max_Speed = " + obj1.max_speed);
    System.out.println("Max_Speed = " + obj2.max_speed);
    System.out.println("Max_Speed = " + obj3.max_speed);


When you run the code, console will show:

Inside Honda
Inside Honda
Inside bike

Max_Speed = 150
Max_Speed = 90
Max_Speed = 90

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :


to return a list in JSON format.

"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",

How to check if array element exists or not in javascript?

This also works fine, testing by type against undefined.

if (currentData[index] === undefined){return}


const fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
if (fruits["Raspberry"] === undefined){_x000D_
  console.log("No Raspberry entry in fruits!")_x000D_

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:


As you require the filename with path, enjoy!

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

jQuery: checking if the value of a field is null (empty)

I would also trim the input field, cause a space could make it look like filled

if ($.trim($('#person_data[document_type]').val()) != '')


Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

Convert a tensor to numpy array in Tensorflow?

I was searching for days for this command.

This worked for me outside any session or somthing like this.

# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())

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

You should write textcolor in xml as




Adding and removing extensionattribute to AD object

I used the following today - It works!

Add a value to an extensionAttribute

 $ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
    Set-ADUser –Identity $ThisUser -add @{"extensionattribute1"="MyString"}

Remove a value from an extensionAttribute

  $ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
  Set-ADUser –Identity $ThisUser -Clear "extensionattribute1" 

Powershell 2 copy-item which creates a folder if doesn't exist

In PowerShell 2.0, it is still not possible to get the Copy-Item cmdlet to create the destination folder, you'll need code like this:

$destinationFolder = "C:\My Stuff\Subdir"

if (!(Test-Path -path $destinationFolder)) {New-Item $destinationFolder -Type Directory}
Copy-Item "\\server1\Upgrade.exe" -Destination $destinationFolder

If you use -Recurse in the Copy-Item it will create all the subfolders of the source structure in the destination but it won't create the actual destination folder, even with -Force.

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

Uninstall homebrew:

 ruby -e "$(curl -fsSL"

Then reinstall

ruby -e "$(curl -fsSL"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

self referential struct definition?

There is sort of a way around this:

struct Cell {
  bool isParent;
  struct Cell* child;

struct Cell;
typedef struct Cell Cell;

If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.

Python time measure function

My way of doing it:

from time import time

def printTime(start):
    end = time()
    duration = end - start
    if duration < 60:
        return "used: " + str(round(duration, 2)) + "s."
        mins = int(duration / 60)
        secs = round(duration % 60, 2)
        if mins < 60:
            return "used: " + str(mins) + "m " + str(secs) + "s."
            hours = int(duration / 3600)
            mins = mins % 60
            return "used: " + str(hours) + "h " + str(mins) + "m " + str(secs) + "s."

Set a variable as start = time() before execute the function/loops, and printTime(start) right after the block.

and you got the answer.

Javascript getElementById based on a partial string

I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.

var base = "common";
var num = 3;

var o = document.getElementById(base + num);  // will find id="common3"

If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).

Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":

// get a list of all form objects that have the right type of ID
function findPollForms() {
    var list = getElementsByTagName("form");
    var results = [];
    for (var i = 0; i < list.length; i++) {
        var id = list[i].id;
        if (id &&^poll-/) != -1) {

// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
    var list = getElementsByTagName("form");
    var results = [];
    for (var i = 0; i < list.length; i++) {
        var id = list[i].id;
        if (id &&^poll-/) != -1) {

Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site:

Github page:

Disclaimer: I'm the author.

PHP function overloading

In PHP 5.6 you can use the splat operator ... as the last parameter and do away with func_get_args() and func_num_args():

function example(...$args)
   count($args); // Equivalent to func_num_args()

example(1, 2);
example(1, 2, 3, 4, 5, 6, 7);

You can use it to unpack arguments as well:

$args[] = 1;
$args[] = 2;
$args[] = 3;

Is equivalent to:

example(1, 2, 3);

java.lang.NoClassDefFoundError in junit

The same problem can occur if you have downloaded JUnit jar from the JUnit website, but forgotten to download the Hamcrest jar - both are required (the instructions say to download both, but I skipped ahead! Oops)

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

Very Simple, Very Smooth, JavaScript Marquee

I've made very simple function for marquee. See: It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;

function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
            'left': -width
        }, time, 'linear', function() {

    'width': width,
    'left': start_pos
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over

$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element

Mocking HttpClient in unit tests

You could use RichardSzalay MockHttp library which mocks the HttpMessageHandler and can return an HttpClient object to be used during tests.

GitHub MockHttp

PM> Install-Package RichardSzalay.MockHttp

From the GitHub documentation

MockHttp defines a replacement HttpMessageHandler, the engine that drives HttpClient, that provides a fluent configuration API and provides a canned response. The caller (eg. your application's service layer) remains unaware of its presence.

Example from GitHub

 var mockHttp = new MockHttpMessageHandler();

// Setup a respond for the user api (including a wildcard in the URL)
        .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

var response = await client.GetAsync("http://localhost/api/user/1234");
// or without async: var response = client.GetAsync("http://localhost/api/user/1234").Result;

var json = await response.Content.ReadAsStringAsync();

// No network connection required
Console.Write(json); // {'name' : 'Test McGee'}

Javascript AES encryption

This post is now old, but the crypto-js, may be now the most complete javascript encryption library.

CryptoJS is a collection of cryptographic algorithms implemented in JavaScript. It includes the following cyphers: AES-128, AES-192, AES-256, DES, Triple DES, Rabbit, RC4, RC4Drop and hashers: MD5, RIPEMD-160, SHA-1, SHA-256, SHA-512, SHA-3 with 224, 256, 384, or 512 bits.

You may want to look at their Quick-start Guide which is also the reference for the following node.js port.

node-cryptojs-aes is a node.js port of crypto-js

How to convert column with dtype as object to string in Pandas Dataframe

Not answering the question directly, but it might help someone else.

I have a column called Volume, having both - (invalid/NaN) and numbers formatted with ,

df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')

Casting to string is required for it to apply to str.replace


extract the date part from DateTime in C#

When comparing only the date of the datatimes, use the Date property. So this should work fine for you

datetime1.Date == datetime2.Date

How to stop console from closing on exit?

What about Console.Readline();?

How do I get TimeSpan in minutes given two Dates?

double totalMinutes = (end-start).TotalMinutes;

Click event on select option element in chrome

Looking for this on 2018. Click event on option tag, inside a select tag, is not fired on Chrome.

Use change event, and capture the selected option:

$(document).delegate("select", "change", function() {
    //capture the option
    var $target = $("option:selected",$(this));

Be aware that $target may be a collection of objects if the select tag is multiple.

How to export data as CSV format from SQL Server using sqlcmd?

You can do it in a hackish way. Careful using the sqlcmd hack. If the data has double quotes or commas you will run into trouble.

You can use a simple script to do it properly:

' Data Exporter                                                 '
'                                                               '
' Description: Allows the output of data to CSV file from a SQL '
'       statement to either Oracle, SQL Server, or MySQL        '
' Author: C. Peter Chen,                   '
' Version Tracker:                                              '
'       1.0   20080414 Original version                         '
'   1.1   20080807 Added email functionality                '
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr

' Configuration '
dbType = "oracle"                 ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost"                 ' Hostname of the database server
dbName = "dbname"                 ' Name of the database/SID
dbUser = "username"               ' Name of the user
dbPass = "password"               ' Password of the above-named user
outputFile = "c:\output.csv"      ' Path and file name of the output CSV file
email = "[email protected]"           ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
  subj = "Email Subject"          ' The subject of your email; required only if you send the CSV over email
  body = "Put a message here!"    ' The body of your email; required only if you send the CSV over email
  smtp = ""        ' Name of your SMTP server; required only if you send the CSV over email
  smtpPort = 25                   ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual"  ' SQL statement you wish to execute
' End Configuration '

dim fso, conn

'Create filesystem object 
set fso = CreateObject("Scripting.FileSystemObject")

'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then"Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then"Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then"DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if

' Subprocedure to generate data.  Two parameters:
'   1. fPath=where to create the file
'   2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
    dim a, showList, intcount
    set a = fso.createtextfile(fPath)

    set showList = conn.execute(sqlstr)
    for intcount = 0 to showList.fields.count -1
        if intcount <> showList.fields.count-1 then
            a.write """" & showList.fields(intcount).name & ""","
            a.write """" & showList.fields(intcount).name & """"
        end if
    a.writeline ""

    do while not showList.eof
        for intcount = 0 to showList.fields.count - 1
            if intcount <> showList.fields.count - 1 then
                a.write """" & showList.fields(intcount).value & ""","
                a.write """" & showList.fields(intcount).value & """"
            end if
        a.writeline ""
    set showList = nothing

    set a = nothing
end sub

' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)

' Close
set fso = nothing
set conn = nothing

if email <> "" then
    dim objMessage
    Set objMessage = CreateObject("CDO.Message")
    objMessage.Subject = "Test Email from vbs"
    objMessage.From = email
    objMessage.To = email
    objMessage.TextBody = "Please see attached file."
    objMessage.AddAttachment outputFile

    objMessage.Configuration.Fields.Item ("") = 2
    objMessage.Configuration.Fields.Item ("") = smtp
    objMessage.Configuration.Fields.Item ("") = smtpPort


end if

'You're all done!!  Enjoy the file created.
msgbox("Data Writer Done!")

Source: Writing SQL output to CSV with VBScript.

Extension mysqli is missing, phpmyadmin doesn't work

You need the MySQLi module. This error usually occurs when manually installing phpMyAdmin.

sudo apt-get install php7.3-mysql

It will return you with.

[Creating config file /etc/php/7.3/mods-available/mysqlnd.ini with new version]

[Creating config file /etc/php/7.3/mods-available/mysqli.ini with new version]


sudo service apache2 restart.


Press F5 on your browser.

gnuplot plotting multiple line graphs

andyras is completely correct. One minor addition, try this (for example)

plot 'ls.dat' using 4:xtic(1)

This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

There's the more general but perhaps not as helpful to you Wireshark.

One of the SO server sites might be better suited for your question. In fact, it's already been asked on SuperUser.

jquery AJAX and json format

   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
   success: function(response) {
   error: function(response) {

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

"int cannot be dereferenced" in Java


id == list[pos].getItemNumber()

instead of


CodeIgniter - return only one row?

To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:

if ($query->num_rows() > 0) {
    return $query->first_row();

To retrieve the first row.

Count number of rows within each group

Considering @Ben answer, R would throw an error if df1 does not contain x column. But it can be solved elegantly with paste:

aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)

Similarly, it can be generalized if more than two variables are used in grouping:

aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)

Accessing bash command line args $@ vs $*

A nice handy overview table from the Bash Hackers Wiki:

Syntax Effective result
$* $1 $2 $3 … ${N}
$@ $1 $2 $3 … ${N}
"$*" "$1c$2c$3c…c${N}"
"$@" "$1" "$2" "$3" … "${N}"

where c in the third row is the first character of $IFS, the Input Field Separator, a shell variable.

If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*" trick with the input field separator set to tab IFS=$'\t'.

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

How to make use of SQL (Oracle) to count the size of a string?

Regardless to Your example

select length('Burger') from dual;

I hope this will help :)

How to convert minutes to Hours and minutes (hh:mm) in java

Try this code:

import java.util.Scanner;

public class BasicElement {
    public static void main(String[] args){
        Scanner input = new Scanner(;
        int hours;
        System.out.print("Enter the hours to convert:");
        hours =input.nextInt();
        int d=hours/24;
        int m=hours%24;
        System.out.println(d+"days"+" "+m+"hours");     


"Please provide a valid cache path" error in laravel

The cause of this error can be traced from Illuminate\View\Compilers\Compiler.php

public function __construct(Filesystem $files, $cachePath)
    if (! $cachePath) {
        throw new InvalidArgumentException('Please provide a valid cache path.');

    $this->files = $files;
    $this->cachePath = $cachePath;

The constructor is invoked by BladeCompiler in Illuminate\View\ViewServiceProvider

 * Register the Blade engine implementation.
 * @param  \Illuminate\View\Engines\EngineResolver  $resolver
 * @return void
public function registerBladeEngine($resolver)
    // The Compiler engine requires an instance of the CompilerInterface, which in
    // this case will be the Blade compiler, so we'll first create the compiler
    // instance to pass into the engine so it can compile the views properly.
    $this->app->singleton('blade.compiler', function () {
        return new BladeCompiler(
            $this->app['files'], $this->app['config']['view.compiled']

    $resolver->register('blade', function () {
        return new CompilerEngine($this->app['blade.compiler']);

So, tracing back further, the following code:


is generally located in your /config/view.php, if you use the standard laravel structure.

return [
    | View Storage Paths
    | Most templating systems load templates from disk. Here you may specify
    | an array of paths that should be checked for your views. Of course
    | the usual Laravel view path has already been registered for you.
    'paths' => [
    | Compiled View Path
    | This option determines where all the compiled Blade templates will be
    | stored for your application. Typically, this is within the storage
    | directory. However, as usual, you are free to change this value.
    'compiled' => realpath(storage_path('framework/views')),

realpath(...) returns false, if the path does not exist. Thus, invoking

'Please provide a valid cache path.' error.

Therefore, to get rid of this error, what you can do is to ensure that




exists :)

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

How to get the first five character of a String

Below is an extension method that checks if a string is bigger than what was needed and shortens the string to the defined max amount of chars and appends '...'.

public static class StringExtensions
    public static string Ellipsis(this string s, int charsToDisplay)
        if (!string.IsNullOrWhiteSpace(s))
            return s.Length <= charsToDisplay ? s : new string(s.Take(charsToDisplay).ToArray()) + "...";
        return String.Empty;

remove white space from the end of line in linux

If your lines are exactly the way you depict them(no leading or embedded spaces), the following should serve as well

awk '{$1=$1;print}' file.txt

Calling async method synchronously

I need to call this method from a synchronously method.

It's possible with GenerateCodeAsync().Result or GenerateCodeAsync().Wait(), as the other answer suggests. This would block the current thread until GenerateCodeAsync has completed.

However, your question is tagged with , and you also left the comment:

I was hoping for a simpler solution, thinking that handled this much easier than writing so many lines of code

My point is, you should not be blocking on an asynchronous method in ASP.NET. This will reduce the scalability of your web app, and may create a deadlock (when an await continuation inside GenerateCodeAsync is posted to AspNetSynchronizationContext). Using Task.Run(...).Result to offload something to a pool thread and then block will hurt the scalability even more, as it incurs +1 more thread to process a given HTTP request.

ASP.NET has built-in support for asynchronous methods, either through asynchronous controllers (in ASP.NET MVC and Web API) or directly via AsyncManager and PageAsyncTask in classic ASP.NET. You should use it. For more details, check this answer.

Changing background color of ListView items on Android

Take a look at List14 example. In getView() you can call convertView.setBackgroundDrawable() for each entry. You could have a class member counter to decide which background to call it with to get alternating backgrounds, for example.

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.

  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.

So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.

Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

How to manually include external aar package using new Gradle Android Build System

I've just succeeded!

  1. Copy the mylib-0.1.aar file into the libs/ folder

  2. Add these lines to the bottom of build.gradle (should be app, not project):

    repositories {
       flatDir {
           dirs 'libs'
    dependencies {
        compile 'com.example.lib:mylib:0.1@aar'
  3. So far so good. Here comes the most important point:

Gradle needs to access the network for dependencies unless offline mode is enabled.

Make sure that you have enabled Offline work via the checkbox in Project Structures/Gradle

-- OR --

Configure the proxy settings in order to access the network.

To configure the proxy settings you have to modify the project's file, configuring http and https separately as below:
systemProp.http.auth.ntlm.domain=example <for NT auth>
systemProp.https.auth.ntlm.domain=example <for NT auth>

Hope this works.

Cloning specific branch

you can use this command for particular branch clone :

git clone <url of repo> -b <branch name to be cloned>

Eg: git clone -b master

Does Python have a package/module management system?

The Python Package Index (PyPI) seems to be standard:

  • To install a package: pip install MyProject
  • To update a package pip install --upgrade MyProject
  • To fix a version of a package pip install MyProject==1.0

You can install the package manager as follows:

curl -O
easy_install pip


Handling null values in Freemarker

Starting from freemarker 2.3.7, you can use this syntax :


or, if you want display a default text when the attribute is null :

${(object.attribute)!"default text"}

Convert an integer to a float number


// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml

... and now, some examples:


adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000


adapter: mysql
database: my_db
username: root
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

How to make a JTable non-editable

You can override the method isCellEditable and implement as you want for example:

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;



//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

   public boolean isCellEditable(int row, int column) {
       //Only the third column
       return column == 3;


Note for if your JTable disappears

If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.

//instance table model
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {

    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;


SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
     while (reader.Read())
         int count = reader.VisibleFieldCount;

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help
  2. Install New Software ---> Add
  3. inside Add Repository write the Name: ADT (or whatever you want)
  4. and Location:
  5. after loading you should get Developer Tools and NDK Plugins
  6. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  7. click Next
  8. Finish

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...

enter image description here

All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

Windows-1252 to UTF-8 encoding

If you want to rename multiple files in a single command - let's say you want to convert all *.txt files - here is the command:

find . -name "*.txt" -exec iconv -f WINDOWS-1252 -t UTF-8 {} -o {}.ren \; -a -exec mv {}.ren {} \;

How Stuff and 'For Xml Path' work in SQL Server?

STUFF((SELECT distinct ',' + CAST(T.ID) FROM Table T where T.ID= 1 FOR XML PATH('')),1,1,'') AS Name

Difference between partition key, composite key and clustering key in Cassandra?

In brief sense:

Partition Key is nothing but identification for a row, that identification most of the times is the single column (called Primary Key) sometimes a combination of multiple columns (called Composite Partition Key).

Cluster key is nothing but Indexing & Sorting. Cluster keys depend on few things:

  1. What columns you use in where clause except primary key columns.

  2. If you have very large records then on what concern I can divide the date for easy management. Example, I have data of 1million a county population records. So for easy management, I cluster data based on state and after pincode and so on.

Execution time of C program

(All answers here are lacking, if your sysadmin changes the systemtime, or your timezone has differing winter- and sommer-times. Therefore...)

On linux use: clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable); It's not affected if the system-admin changes the time, or you live in a country with winter-time different from summer-time, etc.

#include <stdio.h>
#include <time.h>

#include <unistd.h> /* for sleep() */

int main() {
    struct timespec begin, end;
    clock_gettime(CLOCK_MONOTONIC_RAW, &begin);

    sleep(1);      // waste some time

    clock_gettime(CLOCK_MONOTONIC_RAW, &end);

    printf ("Total time = %f seconds\n",
            (end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
            (end.tv_sec  - begin.tv_sec));


man clock_gettime states:

              Clock  that  cannot  be set and represents monotonic time since some unspecified starting point.  This clock is not affected by discontinuous jumps in the system time
              (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.

PHP, getting variable from another php-file

You could also use file_get_contents


 echo $data_a;

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

How to open link in new tab on html?

When to use target='_blank' :

The HTML version (Some devices not support it):

<a href="" target="_blank">This link will open in new window/tab</a>

The JavaScript version for all Devices :

The use of rel="external" is perfectly valid

<script type="text/javascript" src=""></script>
<script type="text/javascript">
    $('a[rel="external"]').attr('target', '_blank');

and for Jquery can try with the below one:

$("#content a[href^='http://']").attr("target","_blank");

If browser setting don't allow you to open in new windows :

href = "";
onclick=" (this.href, ''); return false";

How to change spinner text size and text color?

To change the color of spinner text :

 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);}

Mysql command not found in OS X 10.7

Maybe I'll help someone else. None of the above answers worked for Catalina. Finally, this solved the problem

echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> /Users/$(whoami)/.bash_profile

Of course, you have to change for the version of mysql you have installed

Android. WebView and loadData

 String strWebData="html...." //**Your html string**

 WebView webDetail=(WebView) findViewById(;

 WebSettings websetting = webDetail.getSettings();


 webDetail.loadData(strWebData, "text/html; charset=utf-8", null);

How to set image in circle in swift

// code to make the image round

import UIKit

extension UIImageView {
public func maskCircle(anyImage: UIImage) {

    self.contentMode = UIViewContentMode.ScaleAspectFill
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = false
    self.clipsToBounds = true

    // make square(* must to make circle),
    // resize(reduce the kilobyte) and
    // fix rotation.
    //        self.image = prepareImage(anyImage)

// to call the function from the view controller


What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I ran into this issue when we changed to Visual Studio 2015. None of the above answers worked for us. In the end we got it working by adding the following config file to ALL sgen.exe executables on the machine

<?xml version ="1.0"?>
        <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0" />

Particularly in this location, even when we were targeting .NET 4.0:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Component based game engine design

I am currently researching this exact topic in the many (MANY) threads at and found the following two solutions to be good candidates on what I will develop for my game:

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.

The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM

Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

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

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

            android:permission="" ]]>
                <action android:name="" />
                <category android:name="" />


Add GCM Service declaration

     <service android:name=".GcmIntentService" />

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

protected void onCreate(Bundle savedInstanceState) {
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");

protected void onResume() {

// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
        return false;
    return true;

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    return registrationId;

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);

private void registerInBackground() {
    new AsyncTask() {
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            return null;
        protected void onPostExecute(Object result) {
            //to do here
    }.execute(null, null, null);

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

How do I convert from int to Long in Java?

Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :

public  static  long  integerToLong (int minute ){
    int delay = minute*1000;
    long diff = (long) delay;
    return  diff ; 

Temporary tables in stored procedures

For short: No


According to the official docs:

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
<script src=""></script>_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>

The above example can be simplified, but wanted to show the usage of this in the not() selector.

How to Get JSON Array Within JSON Object?

Solved, use array list of string to get name from Ingredients. Use below code:

JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();

//loop to get all json objects from data json array
for(int i=0; i<length; i++){
    JSONObject jObj = ja_data.getJSONObject(i);
    Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
    // getting inner array Ingredients
    JSONArray ja = jObj.getJSONArray("Ingredients");
    int len = ja.length();
    ArrayList<String> Ingredients_names = new ArrayList<>();
    for(int j=0; j<len; j++){
        JSONObject json = ja.getJSONObject(j);

Making a triangle shape using xml definitions?

Using vector drawable:

<vector xmlns:android=""
        android:pathData="M0,0 L24,0 L0,24 z"

enter image description here

How does cookie based authentication work?

A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.

To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.

There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.

A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like It would be unacceptable for a browser to ever sends cookies to a different domain.

IIS7 folder permissions for web application

In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE.

Specify an Identity for an Application Pool (IIS 7)

In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName instead of NT Authority\Network Service.

Read and overwrite a file in Python

The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")

How to get the version of ionic framework?

The method version on ionic object returns the current version in string format.

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

How to initialize weights in PyTorch?

    import torch.nn as nn        

    # a simple network
    rand_net = nn.Sequential(nn.Linear(in_features, h_size),
                             nn.Linear(h_size, h_size),
                             nn.Linear(h_size, 1),

    # initialization function, first checks the module type,
    # then applies the desired changes to the weights
    def init_normal(m):
        if type(m) == nn.Linear:

    # use the modules apply function to recursively apply the initialization

Count rows with not empty value

Solved using a solution i found googling by Yogi Anand:

The example below counts the number of non-empty rows in the range A3:C, remember to update both ranges in the formula with your range of interest.


Also make sure to avoid circular dependencies, it will happen if you for example count the number of non-empty rows in A:C and place this formula in the A or C column.

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger


Execute In Debug


Switch case in C# - a constant value is expected

switch is very picky in the sense that the values in the switch must be a compile time constant. and also the value that's being compared must be a primitive (or string now). For this you should use an if statement.

The reason may go back to the way that C handles them in that it creates a jump table (because the values are compile time constants) and it tries to copy the same semantics by not allowing evaluated values in your cases.

Looping through dictionary object

It depends on what you are after in the Dictionary

Models.TestModels obj = new Models.TestModels();

foreach (var keyValuPair in obj.sp)
    // KeyValuePair<int, dynamic>

foreach (var key in obj.sp.Keys)
     // Int 

foreach (var value in obj.sp.Values)
    // dynamic

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

Which data structures and algorithms book should I buy?

If you want the algorithms to be implemented specifically in Java then there is Mitchell Waite's Series book "Data Structures & Algorithms in Java". It starts from basic data structures like linked lists, stacks and queues, and the basic algorithms for sorting and searching. Working your way through it you will eventually get to Tree data structures, Red-Black trees, 2-3 trees and Graphs.

All-in-all its not an extremely theoretical book, but if you just want an introduction in a language you are familiar with then its a good book. At the end of the day, if you want a deeper understanding of algorithms you're going to have to learn some of the more theoretical concepts, and read one of the classics, like Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms.

How can I loop through a C++ map of maps?

Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:

std::map<std::string, std::map<std::string, std::string>> mymap;

for(auto const &ent1 : mymap) {
  // ent1.first is the first key
  for(auto const &ent2 : ent1.second) {
    // ent2.first is the second key
    // ent2.second is the data

this should be much cleaner than the earlier versions, and avoids unnecessary copies.

Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):

for(auto const &ent1 : mymap) {
  auto const &outer_key = ent1.first;
  auto const &inner_map = ent1.second;
  for(auto const &ent2 : inner_map) {
    auto const &inner_key   = ent2.first;
    auto const &inner_value = ent2.second;

How to get the selected radio button value using js

If you can use jQuery "Chamika Sandamal" answer is the correct way to go. In the case you can't use jQuery you can do something like this:

function selectedRadio() {
    var radio = document.getElementsByName('mailCopy');


  • In general for the inputs you want to have unique IDs (not a requirement but a good practice)
  • All the radio inputs that are from the same group MUST have the same name attribute, for example
  • You have to set the value attribute for each input

Here is an example of input radios:

<input type="radio" name="mailCopy" value="1" />1<br />
<input type="radio" name="mailCopy" value="2" />2<br />

Set the table column width constant regardless of the amount of text in its cells?

You need to write this inside the corresponding CSS


Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }

How can I convert an RGB image into grayscale in Python?

How about doing it with Pillow:

from PIL import Image
img ='image.png').convert('LA')'greyscale.png')

Using matplotlib and the formula

Y' = 0.2989 R + 0.5870 G + 0.1140 B 

you could do:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return[...,:3], [0.2989, 0.5870, 0.1140])

img = mpimg.imread('image.png')     
gray = rgb2gray(img)    
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT DISTINCT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month


SELECT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

Can’t delete docker image with dependent child images

Image Layer: Repositories are often referred to as images or container images, but actually they are made up of one or more layers. Image layers in a repository are connected together in a parent-child relationship. Each image layer represents changes between itself and the parent layer.

The docker building pattern uses inheritance. It means the version i depends on version i-1. So, we must delete the version i+1 to be able to delete version i. This is a simple dependency.

If you wanna delete all images except the last one (the most updated) and the first (base) then we can export the last (the most updated one) using docker save command as below.

docker save -o <output_file> <your_image-id> | gzip <output_file>.tgz

Then, now, delete all the images using image-id as below.

docker rm -f <image-id i> | docker rm -f <image i-1> | docker rm -f <image-id i-2> ... <docker rm -f <image-id i-k> # where i-k = 1

Now, load your saved tgz image as below.

gzip -c <output_file.tgz> | docker load

see the image-id of your loaded image using docker ps -q. It doesn't have tag and name. You can simply update tag and name as done below.

docker tag <image_id> group_name/name:tag

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        for(int n = numOfArgs - 1; n >= 0; n--)
            char next;
            next = list[n];
            __asm push next;
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

How do I make a Mac Terminal pop-up/alert? Applescript?

Use osascript. For example:

osascript -e 'tell app "Finder" to display dialog "Hello World"' 

Replacing “Finder” with whatever app you desire. Note if that app is backgrounded, the dialog will appear in the background too. To always show in the foreground, use “System Events” as the app:

osascript -e 'tell app "System Events" to display dialog "Hello World"'

Read more on Mac OS X Hints.

Set the text in a span

Give an ID to your span and then change the text of target span.


<i id="StatusTitleIcon" class="fa fa-exclamation fa-fw"></i>
<span id="StatusTitle">Error</span>

Here "Error" text will become "Info" and their fontawesome icons will be changed as well.

Mysql adding user for remote access

Follow instructions (steps 1 to 3 don't needed in windows):

  1. Find mysql config to edit:

    /etc/mysql/my.cnf (Mysql 5.5)

    /etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)

  2. Find bind-address= in config file change bind-address= (you can set bind address to one of your interface ips or like me use

  3. Restart mysql service run on console: service restart mysql

  4. Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql and if you set password for root run mysql -p):

     ON *.* TO 'remote'@'%' 
     IDENTIFIED BY 'safe_password' 

Now you should have a user with name of user and password of safe_password with capability of remote connect.

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Alternatively, if nothing works (as was my case) you can revert to searching and downloading a whl file here:

Before installing it via pip using the downloaded file which won't require any certificate anymore:

python3.7 -m pip install Myfile.whl

when exactly are we supposed to use "public static final String"?

Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.

Calculating arithmetic mean (one type of average) in Python

You don't even need numpy or scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))

Select all DIV text with single mouse click

$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
        } else if (window.getSelection) {
            var range = document.createRange();

Above answer is not working in Chrome because addRange remove previous added range. I didnt find any solution for this beside fake selection with css.

How to convert a String into an ArrayList?


List<String> list = Arrays.asList("hello");


List<String> list = new ArrayList<String>(Arrays.asList("hello"));

In my opinion, Option1 is better because

  1. we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.
  2. its performance is much better (but it returns a fixed-size list).

Please refer to the documentation here

Exiting out of a FOR loop in a batch file?

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on
for /l %%n in (1,1,10) do (
  goto :eof
  echo %%n

How to refresh token with Google API client?

So i finally figured out how to do this. The basic idea is that you have the token you get the first time you ask for authentication. This first token has a refresh token. The first original token expires after an hour. After an hour you have to use the refresh token from the first token to get a new usable token. You use $client->refreshToken($refreshToken) to retrieve a new token. I will call this "temp token." You need to store this temp token as well because after an hour it expires as well and note it does not have a refresh token associated with it. In order to get a new temp token you need to use the method you used before and use the first token's refreshtoken. I have attached code below, which is ugly, but im new at this...

//pull token from database
$tokenquery="SELECT * FROM token WHERE type='original'";
$tokenresult = mysqli_query($cxn,$tokenquery);
$time_created = json_decode($token)->created;
echo $timediff."<br>";
$refreshToken= json_decode($token)->refresh_token;

//start google client note:
$client = new Google_Client();

//resets token if expired
    echo $refreshToken."</br>";
    $refreshquery="SELECT * FROM token WHERE type='refresh'";
    $refreshresult = mysqli_query($cxn,$refreshquery);
    //if a refresh token is in there...
        $refresh_created = json_decode($token)->created;
        echo "Refresh Time Diff: ".$refreshtimediff."</br>";
        //if refresh token is expired
        echo $newtoken."</br>";
        $tokenupdate="UPDATE token SET token='$newtoken' WHERE type='refresh'";
        echo "refreshed again";
        //if the refresh token hasn't expired, set token as the refresh token
           echo "use refreshed token but not time yet";
    //if a refresh token isn't in there...
        echo $newtoken."</br>";
        $tokenupdate="INSERT INTO token (type,token) VALUES ('refresh','$newtoken')";
        echo "refreshed for first time";

//if token is still good.

$service = new Google_DfareportingService($client);

DB query builder toArray() laravel 4

Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

In this case, it might be more efficient to do:

$result = DB::table('user')->where('name',=,'Jhon')->get();

That way, you won't waste time creating objects and then converting them back into arrays.

How can I remove the decimal part from JavaScript number?

You could use...

...dependent on how you wanted to remove the decimal.

Math.trunc() isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.

Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.

You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.

Required Reading - What Every Computer Scientist Should Know About Floating-Point Arithmetic.

How does java do modulus calculations with negative numbers?

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

If you want to get a negative number for negative inputs then you can use this:

int r = x % n;
if (r > 0 && x < 0)
    r -= n;

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n;
if (r < 0)
    r += n;

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Try this:

On first row set value 1 (e.g cell A1)

on next row set: =A1+1

Finally autocomplete the remaining rows

Update ViewPager dynamically?

This solution won't work for everyone, but in my case, every Fragment in my ViewPager is a different class, and only one of them ever exist at a time.

With this constraint, this solution is safe and should be safe to use in production.

private void updateFragment(Item item) {

    List<Fragment> fragments = getSupportFragmentManager().getFragments();
    for (Fragment fragment : fragments) {

        if (fragment instanceof MyItemFragment && fragment.isVisible()) {
            ((MyItemFragment) fragment).update(item);


If you have multiple versions of the same fragment, you can use this same strategy to call methods on those fragments to determine if it is the fragment you wish to update.

java.text.ParseException: Unparseable date

Pattern is wrong

    String date="Sat Jun 01 12:53:10 IST 2013";
    SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");
    Date currentdate;

How do you add an action to a button programmatically in xcode

UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];


    // Here You can write functionality 


How to Update a Component without refreshing full page - Angular

You can use a BehaviorSubject for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject to which you can subscribe and emit changes.

Define a data sharing service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export class DataSharingService {
    public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

Add the DataSharingService in your AppModule providers entry.

Next, import the DataSharingService in your <app-header> and in the component where you perform the sign-in operation. In <app-header> subscribe to the changes to isUserLoggedIn subject:

import { DataSharingService } from './data-sharing.service';

export class AppHeaderComponent { 
    // Define a variable to use for showing/hiding the Login button
    isUserLoggedIn: boolean;

    constructor(private dataSharingService: DataSharingService) {

        // Subscribe here, this will automatically update 
        // "isUserLoggedIn" whenever a change to the subject is made.
        this.dataSharingService.isUserLoggedIn.subscribe( value => {
            this.isUserLoggedIn = value;

In your <app-header> html template, you need to add the *ngIf condition e.g.:

<button *ngIf="!isUserLoggedIn">Login</button> 
<button *ngIf="isUserLoggedIn">Sign Out</button>

Finally, you just need to emit the event once the user has logged in e.g:

someMethodThatPerformsUserLogin() {
    // Some code 
    // .....
    // After the user has logged in, emit the behavior subject changes.;

Android Studio - Importing external Library/Jar

you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.)

Excel: Searching for multiple terms in a cell

Another way


Also, if you keep a list of values in, say A1 to A3, then you can use


The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.

Android error: Failed to install *.apk on device *: timeout

What I usually do when I get this error is restarting the adb server by typing in the cmd:

adb kill-server

adb start-server

EDIT: With some never versions of the Platform Tools you can do this from the DDMS Perspective in the Devices Tab menu (near the Capture Button), click on Reset adb.

EDIT2: Also I found out that it is preferable to use the USB port in the back of your PC, since most of the front USB ports are low powered, and really seem to be slower when uploading apks on your devices.

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_

Android "Only the original thread that created a view hierarchy can touch its views."

If you couldn't find a UIThread you can use this way .

yourcurrentcontext mean, you need to parse Current Context

 new Thread(new Runnable() {
        public void run() {
            while (true) {
                (Activity) yourcurrentcontext).runOnUiThread(new Runnable() {
                    public void run() { 
                        Log.d("Thread Log","I am from UI Thread");
                try {
                } catch (Exception ex) {


Java reading a file into an ArrayList?

This Java code reads in each word and puts it into the ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.