Programs & Examples On #Feature envy

How to configure log4j with a properties file

I have this code in my application today

File log4jfile = new File("./conf/");

The relative path is from the working directory of the JVM (where the JVM starts).


We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

Intent.putExtra List

If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.

private List<Item> data;

How to yum install Node.JS on Amazon Linux

As mentioned in official documentation , simple below 2 steps -

curl -sL | sudo -E bash -
sudo apt-get install -y nodejs

How to kill zombie process

I tried

kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')

and it works for me.

Find all matches in workbook using Excel VBA

Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
    Set rFND = Nothing
    With SHT.UsedRange
        Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
        If Not rFND Is Nothing Then
            sFirstAddress = rFND.Address
                If strResults = vbNullString Then
                    strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
                    strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
                End If
                Set rFND = .FindNext(rFND)
            Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
        End If
    End With
If strResults = vbNullString Then
    GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
    GetSearchArray = Array(strResults)
    GetSearchArray = Split(strResults, "|")
End If
End Function

Sub test2()
For Each X In GetSearchArray("1")
    Debug.Print X
End Sub

Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.

How to test REST API using Chrome's extension "Advanced Rest Client"

Add authorization header and click pencil button to enter username and passwords

enter image description here

How to create Custom Ratings bar in Android

first add images to drawable:

enter image description here enter image description here

the first picture "ratingbar_staroff.png" and the second "ratingbar_staron.png"

After, create "ratingbar.xml" on res/drawable

<?xml version="1.0" encoding="utf-8"?>
<!--suppress AndroidDomInspection -->
<layer-list xmlns:android="">
    <item android:id="@+android:id/background"
        android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@+android:id/secondaryProgress"
        android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@+android:id/progress"
        android:drawable="@drawable/ratingbar_filled" />

the next xml the same on res/drawable


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">

    <item android:state_pressed="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:state_focused="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:state_selected="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:drawable="@drawable/ratingbar_staroff" />



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">

    <item android:state_pressed="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:state_focused="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:state_selected="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:drawable="@drawable/ratingbar_staron" />


the next to do, add these lines of code on res/values/styles

<style name="CustomRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar</item>
    <item name="android:minHeight">18dp</item>
    <item name="android:maxHeight">18dp</item>

Now, already can add style to ratingbar resource

            style= "@style/CustomRatingBar"

finally on your activity only is declare:

RatingBar ratingbar = (RatingBar) findViewById(;

enter image description here

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Python re.sub replace with matched content

A backreference to the whole match value is \g<0>, see re.sub documentation:

The backreference \g<0> substitutes in the entire substring matched by the RE.

See the Python demo:

import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:

Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
            } else {
                element.replaceWith(' ')

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <div ng-if="showFrom(message)">
       <div>From: {{}}</div>
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{}}</div>
   <div ng-if="showTo(message)">
      <div>To: {{}}</div>


replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a changes in the model, the view will update. But if you delete $[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

How to check the differences between local and github before the pull

If you're not interested in the details that git diff outputs you can just run git cherry which will output a list of commits your remote tracking branch has ahead of your local branch.

For example:

git fetch origin
git cherry master origin/master

Will output something like :

+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9

Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.

This also works the other way :

    git cherry origin/master master

Will show you a list of local commits that you haven't pushed to your remote repository yet.

CSS class for pointer cursor

I don't have enough reputation to comment on the relevant answers, but to people reading this; adding .btn does not just add the pointer cursor but adds a lot of other styling as well. Which is great if it's a button and you want the bootstap button styling, but in other cases it would mess a lot up for other elements.

The best thing you can do, like Hari Das suggested, and which I also always do, is to add the following css:

.cursor-pointer {
  cursor: pointer;

After which you can add it to any element

<div class="cursor-pointer"> .. </div>

How to increase request timeout in IIS?

Add this to your Web Config

    <httpRuntime executionTimeout="180" />

Optional TimeSpan attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.

The default is "00:01:50" (110 seconds).

PHP: date function to get month of the current date

As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.

$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";

// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);

// Output it month is various formats according to

echo date('M',$dateAsUnixTimestamp);
// Will output Apr

echo date('n',$dateAsUnixTimestamp);
// Will output 4

echo date('m',$dateAsUnixTimestamp);
// Will output 04

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".


EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Not sure if this would be helpful. I am using a similar Amazon Linux AMI, which has tomcat7 living under /usr/share/tomcat7.

If tomcat is already running on your machine you can try:

ps -ef | grep tomcat


ps -ef | grep java

to check where it's running from.

jQuery get content between <div> tags

Give the div a class or id and do something like this:


That works at the DOM level.

Is null reference possible?

If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).

Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?

Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -

// Error.h
class Error {
  static Error& NOT_FOUND;
  static Error& UNKNOWN;
  static Error& NONE; // singleton object that represents null

  static vector<shared_ptr<Error>> _instances;
  static Error& NewInstance(const string& name, bool isNull = false);

  bool _isNull;
  Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
  Error() {};
  Error(const Error& src) {};
  Error& operator=(const Error& src) {};

  operator Error*() { return _isNull ? nullptr : this; }

// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
  shared_ptr<Error> pNewInst(new Error(name, isNull)).
  return *pNewInst.get();

Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");

// Main.cpp
#include "Error.h"

Error& getError() {
  return Error::UNKNOWN;

// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
  return Error::NONE;

int main(void) {
  if(getError() != Error::NONE) {
    return EXIT_FAILURE;

  // Edit: To see the overload of "Error*()" in Error.h actually working
  if(getErrorNone() != nullptr) {
    return EXIT_FAILURE;

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

what do <form action="#"> and <form method="post" action="#"> do?

Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))

An action of # indicates that the form stays on the same page, simply suffixing the url with a #. Similar use occurs in anchors. <a href=#">Link</a> for example, will stay on the same page.

Thus, the form is submitted to the same page, which then processes the data etc.

How to read integer values from text file

Try this:-

File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
  // Read values here like long input = scanner.nextLong();

Add context path to Spring Boot application

In Spring Boot 1.5:

Add the following property in


Note: /demo is your context path URL.

How do I determine the current operating system with Node.js

const path = require('path');

if (path.sep === "\\") {
} else {
console.log("Not Windows");

Calling startActivity() from outside of an Activity context

In my opinion, it's better to use the method of startActivity() just in the your code of the Activity.class. If you use that in the Adapter or other class, it will result in that.

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

How can I convert a PFX certificate file for use with Apache on a linux server?

Took some tooling around but this is what I ended up with.

Generated and installed a certificate on IIS7. Exported as PFX from IIS

Convert to pkcs12

openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.

Saved as certificate.key

Saved as certificate.crt

Added to apache vhost w/ Webmin.

Failed to authenticate on SMTP server error using gmail

Nothing wrong with your method, it's a G-mail security issue.

  1. Login g-mail account settings.

  2. Enable 2-step verification.

  3. Generate app-password.

  4. Use new-generated password in place of your real g-mail password.

Don't forget to clear cache.

php artisan config:cache.
php artisan config:clear.

[email protected]

Sending images using Http Post

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

What does it mean "No Launcher activity found!"

If you are using the standard eclipse IDE provided by google for Android development, you can check the "Launcher Activity" check-box while creating a new Activity. Please find below:

enter image description here

How can I throw a general exception in Java?

Well, there are lots of exceptions to throw, but here is how you throw an exception:

throw new IllegalArgumentException("INVALID");

Also, yes, you can create your own custom exceptions.

A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.

}catch(IllegalArgumentException e)

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Selecting only first-level elements in jquery

.add_to_cart >>> .form-item:eq(1)

the second .form-item at tree level child from the .add_to_cart

jQuery: Slide left and slide right

This code works well :

        <script src=""></script>
        <script src=""></script>
        <script src=""></script>
            var options = {};
                 $("#c").toggle( "slide", options, 500 );
                 $("#d").toggle( "slide", options, 500 );
            border:1px solid olive;
            border:2px solid blue;
            <button id="a">Register 1</button>
            <button id="b">Register 2</button>

        <article id="c">
                <label>User name:</label>
                <input type="text" name="123" value="something"/>
                <input type="text" name="456" value="something"/>
        <article id="d">
</html> and

Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.

Calling Oracle stored procedure from C#?

Instead of

cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";

You can also use this syntax:

cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";

Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.

In case of a function call the command string would be like this:

cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);    
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code

Why doesn't the Scanner class have a nextChar method?

I would imagine that it has to do with encoding. A char is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner to represent a UTF-32 codepoint in a single char.

You can specify an encoding to Scanner when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char primitive (since char is only 16 bytes). So you would end up getting inconsistent results.

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

Find all files with name containing string

find $HOME -name "hello.c" -print

This will search the whole $HOME (i.e. /home/username/) system for any files named “hello.c” and display their pathnames:


However, it will not match HELLO.C or HellO.C. To match is case insensitive pass the -iname option as follows:

find $HOME -iname "hello.c" -print

Sample outputs:


Pass the -type f option to only search for files:

find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print

The -iname works either on GNU or BSD (including OS X) version find command. If your version of find command does not supports -iname, try the following syntax using grep command:

find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"

OR try

find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print

Sample outputs:


Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

you can follow this step, By reseeding table you can delete the data of the table.

delete from table_name
dbcc checkident('table_name',reseed,0)

if some error comes then you have to reseed the primary table.

make iframe height dynamic based on content inside- JQUERY/Javascript

There are four different properties you can look at to get the height of the content in an iFrame.


Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.

function getIFrameHeight(){
    function getComputedBodyStyle(prop) {
        function getPixelValue(value) {
            var PIXEL = /^\d+(px)?$/i;

            if (PIXEL.test(value)) {
                return parseInt(value,base);

                style =,
                runtimeStyle = el.runtimeStyle.left;

            el.runtimeStyle.left = el.currentStyle.left;
   = value || 0;
            value =;
   = style;
            el.runtimeStyle.left = runtimeStyle;

            return value;

            el = document.body,
            retVal = 0;

        if (document.defaultView && document.defaultView.getComputedStyle) {
            retVal =  document.defaultView.getComputedStyle(el, null)[prop];
        } else {//IE8 & below
            retVal =  getPixelValue(el.currentStyle[prop]);

        return parseInt(retVal,10);

    return document.body.offsetHeight +
        getComputedBodyStyle('marginTop') +

Remove scrollbar from iframe

This is a last resort, but worth mentioning - you can use the ::-webkit-scrollbar pseudo-element on the iframe's parent to get rid of those famous 90's scroll bars.

::-webkit-scrollbar {
    width: 0px;
    height: 0px;

Edit: though it's relatively supported, ::-webkit-scrollbar may not suit all browsers. use with caution :)

How to run a cron job inside a docker container?

The most robust way I found so far is run an independent cron container - install the docker client and bind mount the docker sock so you can talk to the docker server on the host.

Then just use env vars for each cron job and an entrypoint script to generate the /etc/crontab

Here is an image that I created using this principle and using it in production for the last 3-4 years.

How to add a scrollbar to an HTML5 table?

you can try this


          #table-wrapper {
          #table-wrapper table {
          #table-wrapper table thead th .text {
                  border:1px solid red;


<div id="table-wrapper">

                <th><span class="text">album</span></th>
                <th><span class="text">song</span></th>
                <th><span class="text">genre</span></th>
<tr> <td> album 0</td> <td> song0</td> <td> genre0</td> </tr>
<tr> <td>album 1</td> <td>song 1</td> <td> genre1</td> </tr>
<tr> <td> album2</td> <td>song 2</td> <td> genre2</td> </tr>
<tr> <td> album3</td> <td>song 3</td> <td> genre3</td> </tr>
<tr> <td> album4</td> <td>song 4</td> <td>genre 4</td> </tr>
<tr> <td> album5</td> <td>song 5</td> <td>genre 5</td> </tr>
<tr> <td>album 6</td> <td> song6</td> <td> genre6</td> </tr>
<tr> <td>album 7</td> <td> song7</td> <td> genre7</td> </tr>
<tr> <td> album8</td> <td> song8</td> <td>genre 8</td> </tr>
<tr> <td> album9</td> <td> song9</td> <td> genre9</td> </tr>
<tr> <td> album10</td> <td>song 10</td> <td> genre10</td> </tr>
<tr> <td> album11</td> <td>song 11</td> <td> genre11</td> </tr>
<tr> <td> album12</td> <td> song12</td> <td> genre12</td> </tr>
<tr> <td>album 13</td> <td> song13</td> <td> genre13</td> </tr>
<tr> <td> album14</td> <td> song14</td> <td> genre14</td> </tr>
<tr> <td> album15</td> <td> song15</td> <td> genre15</td> </tr>
<tr> <td>album 16</td> <td> song16</td> <td> genre16</td> </tr>
<tr> <td>album 17</td> <td> song17</td> <td> genre17</td> </tr>
<tr> <td> album18</td> <td> song18</td> <td> genre18</td> </tr>
<tr> <td> album19</td> <td> song19</td> <td> genre19</td> </tr>
<tr> <td> album20</td> <td> song20</td> <td> genre20</td> </tr>    

Check this fiddle :

this will keep the table head fixed ,and scroll only the table content .

How to remove items from a list while iterating?

Most of the answers here want you to create a copy of the list. I had a use case where the list was quite long (110K items) and it was smarter to keep reducing the list instead.

First of all you'll need to replace foreach loop with while loop,

i = 0
while i < len(somelist):
    if determine(somelist[i]):
         del somelist[i]
        i += 1

The value of i is not changed in the if block because you'll want to get value of the new item FROM THE SAME INDEX, once the old item is deleted.

convert month from name to number

$date = 'Dec 25 2099';
echo date('d/m/Y', strtotime($date));

This returns 01/01/1970, that means php doesn't support all dates, it returns correct formatted date till Jan 19 2038 but Jan 20 2038 returns 01/01/1970

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

private string ConvertTime(double miliSeconds)
    var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
    // Converts the total miliseconds to the human readable time format
    return timeSpan.ToString(@"hh\:mm\:ss\:fff");


    [TestCase(1002, "00:00:01:002")]
    [TestCase(700011, "00:11:40:011")]
    [TestCase(113879834, "07:37:59:834")]
    public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
        // Arrange
        var obj = new Class();;

        // Act
        var resultMessage = obj.ConvertTime(totalMiliSeconds);

        // Assert
        Assert.AreEqual(expectedMessage, resultMessage);

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
  exit 1

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
      exit 1

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

How to iterate through a list of dictionaries in Jinja template?


parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}


Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your If the dict is unicode object, you have to encode into utf-8.

Return list of items in list greater than some value

You can use a list comprehension:

[x for x in j if x >= 5]

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

jQuery UI DatePicker to show year only

  $(function() {
    $('#datepicker1').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));

Style should be

.ui-datepicker-calendar {
    display: none;

working demo

Copy struct to struct in C

Also a good example.....

struct point{int x,y;};
typedef struct point point_t;
typedef struct
    struct point ne,se,sw,nw;
rect_t temp;

int main()
    return 0;

void RotateRect(rect_t *givenRect)
    point_t temp_point;
    /*Copy struct data from struct to struct within a struct*/
    temp_point = givenRect->sw;
    givenRect->sw = givenRect->se;
    givenRect->se = givenRect->ne;
    givenRect->ne = givenRect->nw;
    givenRect->nw = temp_point;

How to concatenate two MP4 files using FFmpeg?

Here is a script I made to concatenate several GoPro mp4's into a 720p mp4. Hope it's of help.

cmd="( "
for i; do
    cmd="${cmd}ffmpeg -i $i -ab 256000 -vb 10000000 -mbd rd -trellis 2 -cmp 2 -subcmp 2 -g 100 -f mpeg -; "
cmd="${cmd} ) | ffmpeg -i - -vb 10000000 -ab 256000 -s 1280x720 -y out-`date +%F-%H%M.%S`.mp4"
echo "${cmd}"
eval ${cmd}

Setting size for icon in CSS

this works for me try it.

font-size: 3.75em;

How to compare datetime with only date in SQL Server

DON'T be tempted to do things like this:

Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

This is a better way:

Select * from [User] U 
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')

see: What does the word “SARGable” really mean?

EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 2014-02-07. It is far more efficient to alter the criteria to suit the data instead.

"Amending the criteria to suit the data" is my way of describing "use SARGABLE predicates"

And do not use between either.

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable. (Itzik Ben-Gan)

You need to use a Theme.AppCompat theme (or descendant) with this activity

This is when you want a AlertDialog in a Fragment

            AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
            adb.setTitle("My alert Dialogue \n");
            adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                  //some code

            } });
            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {


                } });

WPF global exception handler

You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException

How to replace special characters in a string?

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9&, _]|^\s)", "");

Here all the special characters except space, comma, and ampersand are replaced. You can also omit space, comma and ampersand by the following regular expression.

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9_]|^\s)", "");

Where Input is the string which we need to replace the characters.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.\SQLEXPRESS next step select your new destination server ex.\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

How to monitor SQL Server table changes by using c#?

You can use the SqlDependency Class. Its intended use is mostly for ASP.NET pages (low number of client notifications).


Implement the OnChange event to get notified:

void OnChange(object sender, SqlNotificationEventArgs e)

And in code:

SqlCommand cmd = ...
cmd.Notification = null;

SqlDependency dependency = new SqlDependency(cmd);

dependency.OnChange += OnChange;

It uses the Service Broker (a message-based communication platform) to receive messages from the database engine.

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

Add a auto increment primary key to existing table in oracle

If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row

UPDATE table_name
   SET new_pk_column = sequence_name.nextval;

Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)

ALTER TABLE table_name
  ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )

If you want to generate the key automatically, you'd need to add a trigger

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  :new.new_pk_column := sequence_name.nextval;

If you are on an older version of Oracle, the syntax is a bit more cumbersome

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  SELECT sequence_name.nextval
    INTO :new.new_pk_column
    FROM dual;

HTML 5 video or audio playlist

I created a JS fiddle for this here:

First, your HTML markup looks like this:

<video id="videoarea" controls="controls" poster="" src=""></video>

<ul id="playlist">
    <li movieurl="VideoURL1.webm" moviesposter="VideoPoster1.jpg">First video</li>
    <li movieurl="VideoURL2.webm">Second video</li>

Second, your JavaScript code via JQuery library will look like this:

$(function() {
    $("#playlist li").on("click", function() {
            "src": $(this).attr("movieurl"),
            "poster": "",
            "autoplay": "autoplay"
        "src": $("#playlist li").eq(0).attr("movieurl"),
        "poster": $("#playlist li").eq(0).attr("moviesposter")

And last but not least, your CSS:

#playlist {
#playlist li{
#playlist li:hover{
#videoarea {
    border:1px solid silver;

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;

[type=radio] + img {
  cursor: pointer;

[type=radio]:checked + img {
  outline: 2px solid #f00;
  <input type="radio" name="test" value="small" checked>
  <img src="">

  <input type="radio" name="test" value="big">
  <img src="">

Don't forget to add a class to your labels and in CSS use that class instead.

Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

body{color:#444;font:100%/1.4 sans-serif;}

  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
.ckb > i {
  width: 25px;
  border-radius: 3px;
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2


<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2

SQL INSERT INTO from multiple tables

Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

Insert Into #TempResult
select CountA, CountB, CountC  from

select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult

Single Form Hide on Startup

    static void Main()
            Form1 form1 = new Form1();
            form1.Visible = false;

 private void ExitToolStripMenuItem_Click(object sender, EventArgs e)

Change NULL values in Datetime format to empty string

I had something similar, and here's (an edited) version of what I ended up using successfully:

ISNULL(CONVERT(VARCHAR(50),[column name goes here],[date style goes here] ),'')

Here's why this works: If you select a date which is NULL, it will show return NULL, though it is really stored as 01/01/1900. This is why an ISNULL on the date field, while you're working with any date data type will not treat this as a NULL, as it is technically not being stored as a NULL.

However, once you convert it to a new datatype, it will convert it as a NULL, and at that point, you're ISNULL will work as you expect it to work.

I hope this works out for you as well!


Update, nearly one year later:

I had a similar situation, where I needed the output to be of the date data-type, and my aforementioned solution didn't work (it only works if you need it displayed as a date, not be of the date data type.

If you need it to be of the date data-type, there is a way around it, and this is to nest a REPLACE within an ISNULL, the following worked for me:

            [DATE COLUMN NAME],
    '') AS [MeaningfulAlias]

reading external sql script in python

A very simple way to read an external script into an sqlite database in python is using executescript():

import sqlite3

conn = sqlite3.connect('csc455_HW3.db')

with open('ZooDatabase.sql', 'r') as sql_file:


Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

Keep only first n characters in a string?

var myString = "Hello, how are you?";

Can I get Unix's pthread.h to compile in Windows?

pthread.h is a header for the Unix/Linux (POSIX) API for threads. A POSIX layer such as Cygwin would probably compile an app with #include <pthreads.h>.

The native Windows threading API is exposed via #include <windows.h> and it works slightly differently to Linux's threading.

Still, there's a replacement "glue" library maintained at ; note that it has some slight incompatibilities with MinGW/VS (e.g. see here).

How to change text color of cmd with windows batch script every 1 second

on particular computer color codes can be assigned to different RGB color by editing color values in cmd window properties. Easy click color on color palete and change their rgb values.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.

Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

That way, you will be "sure that they are present in remote so that other developers can pull them".

SQL: how to select a single id ("row") that meets multiple criteria from a single column

brute force (and only tested on an Oracle system, but I think this is pretty standard):

select distinct usr_id from users where user_id in (
    select user_id from (
      Select user_id, Count(User_Id) As Cc
      From users 
      GROUP BY user_id
    ) Where Cc =3
  and ancestry in ('England', 'France', 'Germany')

edit: I like @HuckIt's answer even better.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Try like this:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'

Python debugging tips


PyDev has a pretty good interactive debugger. It has watch expressions, hover-to-evaluate, thread and stack listings and (almost) all the usual amenities you expect from a modern visual debugger. You can even attach to a running process and do remote debugging.

Like other visual debuggers, though, I find it useful mostly for simple problems, or for very complicated problems after I've tried everything else. I still do most of the heavy lifting with logging.

Why I've got no crontab entry on OS X when using vim?

As the previous posts didn't work for me because of some permissions issues, I found that creating a separate crontab file and adding it to the user's crontab with the -u parameter while root worked for me.

sudo crontab -u {USERNAME} ~/{PATH_TO_CRONTAB_FILE}

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

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:


$(function () {
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        x = x+5;
        $('#myList li').slice(0, x).slideDown();


#myList li{display:none;
#loadMore {
#loadMore:hover {

line breaks in a textarea

PHP Side: from Textarea string to PHP string

$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);

PHP Side: PHP string back to TextArea string:

$list = str_replace('|', '&#13;&#10;', $r['db_field_name']);

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://", "root", "root");
  /* Connect to the MySQL test database */

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;

cout << endl;


Converting string to date in mongodb

I had some strings in the MongoDB Stored wich had to be reformated to a proper and valid dateTime field in the mongodb.

here is my code for the special date format: "2014-03-12T09:14:19.5303017+01:00"

but you can easyly take this idea and write your own regex to parse the date formats:

// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;

db.Product.find().forEach(function(doc) { 
   var matches = myregexp.exec(doc.metadata.insertTime);

   if myregexp.test(doc.metadata.insertTime)) {
       var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
       var hours = matches[4]-(-offset)+1
       var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
       db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
       print("succsessfully updated");
    } else {
        print("not updated");

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

File.Move Does Not Work - File Already Exists

1) With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:


In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.

2) For all other versions of .Net, is the best answer. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

As of today (Feb 27), there is a new For-Each toolbox on the MATLAB File Exchange that accomplishes the concept of foreach. foreach is not a part of the MATLAB language but use of this toolbox gives us the ability to emulate what foreach would do.

How can I pretty-print JSON in a shell script?

Install yajl-tools with the command below:

sudo apt-get install yajl-tools


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

How to get response using cURL in PHP

If anyone else comes across this, I'm adding another answer to provide the response code or other information that might be needed in the "response".

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => '',

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);




string(0) ""

// change to
string(42) "Could not resolve host:"

How to insert tab character when expandtab option is on in Vim

You can disable expandtab option from within Vim as below:

:set expandtab!


:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

Converting a String array into an int Array in java

To get rid of additional whitespace, you could change the code like this:

intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line

Can I set enum start value in Java?


An enum is like a Singleton. The JVM creates the instance.

If you would create it by yourself with classes it could be look like that

public static class MyEnum {

    final public static MyEnum ONE;
    final public static MyEnum TWO;

    static {
        ONE = new MyEnum("1");
        TWO = new MyEnum("2");

    final String enumValue;

    private MyEnum(String value){
        enumValue = value;    

    public String toString(){
        return enumValue;


And could be used like that:

public class HelloWorld{

   public static class MyEnum {

       final public static MyEnum ONE;
       final public static MyEnum TWO;

       static {
          ONE = new MyEnum("1");
          TWO = new MyEnum("2");

       final String enumValue;

       private MyEnum(String value){
           enumValue = value;    

       public String toString(){
           return enumValue;


    public static void main(String []args){


       System.out.println(MyEnum.ONE == MyEnum.ONE);

       System.out.println("Hello World");

SQL Server: Examples of PIVOTing String data


FROM Product) up
) AS Unpvt

How do I split a multi-line string into multiple lines?

Might be overkill in this particular case but another option involves using StringIO to create a file-like object

for line in StringIO.StringIO(inputString):

How to add icons to React Native app

You'll need different sized icons for iOS and Android, like Rockvic said. In addition, I recommend this site for generating different sized icons if anybody is interested. You don't need to download anything and it works perfectly.

Hope it helps.

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method:

How to use setArguments() and getArguments() methods in Fragments?

for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.

How to print formatted BigDecimal values?

BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)

Duplicate Symbols for Architecture arm64

Well, some times when using SDK like FB or Libraries like Vuforia or GoogleAnalytics , adding sample projects may cause the problem that they're already including Frameworks and like so ,so you must make sure not repeating symbols you add manually while they're already included in samples

How do I connect C# with Postgres?

You want the NPGSQL library. Your only other alternative is ODBC.

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

get an element's id

In events handler you can get id as follows

function show(btn) {_x000D_
  console.log('Button id:',;_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>

How to get the xml node value in string

You should use .Load and not .LoadXML


"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Found this: where Nathan Walker (near bottom of page) suggests a decorator in $rootScope to create func 'safeApply', code:

  '$provide', function($provide) {
    return $provide.decorator('$rootScope', [
      '$delegate', function($delegate) {
        $delegate.safeApply = function(fn) {
          var phase = $delegate.$$phase;
          if (phase === "$apply" || phase === "$digest") {
            if (fn && typeof fn === 'function') {
          } else {
        return $delegate;

How do I rename the android package name?

I found a good work around for this problem. Taking the example mentioned in the question, following are the steps for changing the package name from com.example.test to com.example2.test :

  1. create a temporary directory, say temp inside the directory example (alongside directory test).
  2. Go back to the Intellij project, select the folder com.example and Click Shift + F6. Now it offers to rename the text example. Here you can enter the new text you want and IntelliJ will do the rest for you.
  3. Delete the temporary directory temp from the file system.

This idea can be used to refactor any part of the package name.

Good luck!!

Questions every good Java/Java EE Developer should be able to answer?

Core: 1. What are checked and unchecked exceptions ? 2. While adding new exception in code what type (Checked/Unchecked) to use when ?

Servlet: 1. What is the difference between response.sendRedirect() and request.forward() ?

Allow multi-line in EditText view in Android?

To disable number of lines that was previously assigned in theme use xml attribute: android:lines="@null"

How to convert signed to unsigned integer in python


  1. You have 2's-complement representations in mind; and,
  2. By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 << 32) to the negative value.

For example, apply this to -1:

>>> -1
>>> _ + 2**32
>>> bin(_)

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.

Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").

And to duplicate what the platform C compiler does, you can use the ctypes module:

>>> import ctypes
>>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long
>>> _.value

C's unsigned long happens to be 4 bytes on the box that ran this sample.

Running interactive commands in Paramiko

The full paramiko distribution ships with a lot of good demos.

In the demos subdirectory, and have full interactive TTY examples which would probably be overkill for your situation.

In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.

I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.

do-while loop in R

See ?Control or the R Language Definition:

> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

So do_while does not exist as a separate construct in R, but you can fake it with:

repeat( { expressions}; if (! end_cond_expr ) {break} )

If you want to see the help page you cannot type ?while or ?repeat at the console but rather need to use ?'repeat' or ?'while'. All the "control-constructs" including if are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".

Unpivot with column name

Another way around using cross join would be to specify column names inside cross join

select name, Subject, Marks 
from studentmarks
Cross Join (
values (Maths,'Maths'),(Science,'Science'),(English,'English')
) un(Marks, Subject)
where marks is not null;

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.

How to use MySQL DECIMAL?

Although the answers above seems correct, just a simple explanation to give you an idea of how it works.

Suppose that your column is set to be DECIMAL(13,4). This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.

So, in summary, for that column you would have a max value of: 999999999.9999

Binding List<T> to DataGridView in WinForm

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

But I would even go further and bind your grid to a BindingSource

var list = new List<Person>()
    new Person { Name = "Joe", },
    new Person { Name = "Misha", },
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

Batch script: how to check for admin rights

The whoami /groups doesn't work in one case. If you have UAC totally turned off (not just notification turned off), and you started from an Administrator prompt then issued:

runas /trustlevel:0x20000 cmd

you will be running non-elevated, but issuing:

whoami /groups

will say you're elevated. It's wrong. Here's why it's wrong:

When running in this state, if IsUserAdmin ( returns FALSE and UAC is fully disabled, and GetTokenInformation returns TokenElevationTypeDefault ( then the process is not running elevated, but whoami /groups claims it is.

really, the best way to do this from a batch file is:

net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%

You should do net session twice because if someone did an at before hand, you'll get the wrong information.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not really a COM dll (you can't register it).

What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

If nothing works from above solutions follow these steps

From Targets select appnameTests Under "Info"

Change following

Bundle Identifier: com.ProjectName.$(PRODUCT_NAME:rfc1034identifier)

to com.ProjectName.appname

Bundle name: $(PRODUCT_NAME)

Bundle name: appname

Compile & execute

Why does range(start, end) not include end?

It's just more convenient to reason about in many cases.

Basically, we could think of a range as an interval between start and end. If start <= end, the length of the interval between them is end - start. If len was actually defined as the length, you'd have:

len(range(start, end)) == start - end

However, we count the integers included in the range instead of measuring the length of the interval. To keep the above property true, we should include one of the endpoints and exclude the other.

Adding the step parameter is like introducing a unit of length. In that case, you'd expect

len(range(start, end, step)) == (start - end) / step

for length. To get the count, you just use integer division.

Resize font-size according to div size

The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.

See this:Demo

For more details:Main tutorial :connection timed out: connect?

If you're pointing the config at a domain (eg, do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:


Test-NetConnection <IP returned from NSLOOKUP> -port 389

Adding image inside table cell in HTML

You have a TH floating at the top of your table which isn't within a TR. Fix that.

With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.

You also have a closing tag which shouldn't be there.

It should be:

<img src="h.gif" alt="" border="3" height="100" width="100" />

Also this:

<table border = 5 bordercolor = red align = center>

Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.

Should be:

<table border="5" bordercolor="red" align="center">

Also you have no DOCTYPE declared. You should at least add:

<!DOCTYPE html> 

How to set the title text color of UIButton?

func setTitleColor(_ color: UIColor?, 
               for state: UIControl.State)


The color of the title to use for the specified state.

The state that uses the specified color. The possible values are described in UIControl.State.


let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)

sql ORDER BY multiple values in specific order?

For someone who is new to ORDER BY with CASE this may be useful

         WHEN GRADE = 'B' THEN 1
         ELSE 2 END

Position buttons next to each other in the center of page

This can be solved using the following CSS:

#container {
  text-align: center;

button {
  display: inline-block;

display: inline-block will put the buttons side by side and text-align: center places the buttons in the center of the page.


How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

How to write a file or data to an S3 object using boto3

boto3 also has a method for uploading a file directly:

s3 = boto3.resource('s3')    

How to change the color of an image on hover

If the icon is from Font Awesome ( then you could tap into the color css property to change it's background.



This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.

Accessing localhost:port from Android emulator

I faced the same issue on Visual Studio executing an web app on IIS Express. to fix it you need to go to your project properties then click on Debug Tab and change http://localhost:[YOUR PORT] to[YOUR PORT] and set the android url to[YOUR PORT]. it worked for me.

What is the correct way to create a single-instance WPF application?

From here.

A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here's how it's done:

class OneAtATimePlease {

  // Use a name unique to the application (eg include your company URL)
  static Mutex mutex = new Mutex (false, " OneAtATimeDemo");

  static void Main()
    // Wait 5 seconds if contended – in case another instance
    // of the program is in the process of shutting down.
    if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))
        Console.WriteLine("Another instance of the app is running. Bye!");

        Console.WriteLine("Running - press Enter to exit");

A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"

  'Click the export to file button

  'Choose the export format

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

The type or namespace name could not be found

I solved mine because the other project was coded with .NET 4.5 and the other one was coded 4.0

Best way to work with transactions in MS SQL Server Management Studio

I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.

Example below:

USE AdventureWorks;
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute

     IF @TEST= 1
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;

     IF @TEST= 1
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
            IF @@TRANCOUNT > 0

        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0


When do I need to use AtomicBoolean in Java?

The AtomicBoolean class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.

The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.

input file appears to be a text format dump. Please use psql

For me when i try to restore from remote host i used

psql -U username -p 5432 -h -d database < db.dump

worked fine. And if not remote just following command worked.

psql -d database < db.dump

Error while inserting date - Incorrect date value:

As MySql accepts the date in y-m-d format in date type column, you need to STR_TO_DATE function to convert the date into yyyy-mm-dd format for insertion in following way:

INSERT INTO table_name(today) 

Similary, if you want to select the date in different format other than Mysql format, you should try DATE_FORMAT function

SELECT DATE_FORMAT(today, '%m-%d-%y') from table_name; 

Fragment MyFragment not attached to Activity

I've faced two different scenarios here:

1) When I want the asynchronous task to finish anyway: imagine my onPostExecute does store data received and then call a listener to update views so, to be more efficient, I want the task to finish anyway so I have the data ready when user cames back. In this case I usually do this:

protected void onPostExecute(void result) {
    // do whatever you do to save data
    if (this.getView() != null) {
        // update views

2) When I want the asynchronous task only to finish when views can be updated: the case you're proposing here, the task only updates the views, no data storage needed, so it has no clue for the task to finish if views are not longer being showed. I do this:

protected void onStop() {
    // notice here that I keep a reference to the task being executed as a class member:
    if (this.myTask != null && this.myTask.getStatus() == Status.RUNNING) this.myTask.cancel(true);

I've found no problem with this, although I also use a (maybe) more complex way that includes launching tasks from the activity instead of the fragments.

Wish this helps someone! :)

Is there a JavaScript function that can pad a string to get to a determined length?

Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

function(string, length, pad_char, append) {
    string = string.toString();
    length = parseInt(length) || 1;
    pad_char = pad_char || ' ';

    while (string.length < length) {
        string = append ? string+pad_char : pad_char+string;
    return string;

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
header {_x000D_
  background: tomato;_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
    main content: fills remaining space<br>_x000D_
    footer: fixed height in px_x000D_

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

    url: '/getData',
    timeout:3000 //3 second timeout
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?

jQuery 1.8+

    url: '/getData',
    timeout:3000 //3 second timeout
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
        alert('Failed from timeout'); 
        //do something. Try again perhaps?

jQuery <= 1.7.2

    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
             alert('Failed from timeout');         
            //do something. Try again perhaps?
    success: function(){
        //do something
    timeout:3000 //3 second timeout

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.


How to change color of the back arrow in the new material theme?

On compileSdkVersoin 25, you could do this:


<style name="AppTheme" parent="Theme.AppCompat.Light">
     <item name="android:textColorSecondary">@color/your_color</item>

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

I also had this same problem.

I build .apk file of the project and installed it into mobile(android) and got it working

Convert nested Python dict to object?

This also works well too

class DObj(object):

dobj = Dobj()
dobj.__dict__ = {'a': 'aaa', 'b': 'bbb'}

print dobj.a
>>> aaa
print dobj.b
>>> bbb

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

This worked in my case:

brew uninstall postgresql
rm -fr /usr/local/var/postgres/
brew install postgresql

VBA: Conditional - Is Nothing

In my sample code, I was setting my object to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing and also if not My_Object is nothing. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:

if My_Object is Nothing Then
    'do nothing
    'Do something
End if

ImportError: No module named 'Tkinter'

Tkinter should come with the latest Python, I don't think it comes with Python2. I had the same problem but once. I upgraded to Python 3.8 Tkinter was installed.

Change location of

In Eclipse you can set a VM argument to:


Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

Where to place $PATH variable assertions in zsh?

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.

   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:

/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

C# Iterate through Class properties

// the index of each item in fieldNames must correspond to 
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};

for (int e = 0; e < fieldNames.Length - 1; e++)
       .SetValue(newRecord, resultItems[e]);

How to initialize a struct in accordance with C programming language standards

You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).


a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 };
a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false };

The designations in the initializers are optional; you could also write:

a = (MY_TYPE) { true,  123, 0.456 };
a = (MY_TYPE) { false, 234, 1.234 };

Multiple inputs on one line

Yes, you can.


Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

Java: Get first item from a collection

If you know that the collection is a queue then you can cast the collection to a queue and get it easily.

There are several structures you can use to get the order, but you will need to cast to it.

Open files in 'rt' and 'wt' modes

t refers to the text mode. There is no difference between r and rt or w and wt since text mode is the default.

Documented here:

Character   Meaning
'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt').

In Python script, how do I set PYTHONPATH?

I linux this works too:

import sys

What's the yield keyword in JavaScript?

Simplifying/elaborating on Nick Sotiros' answer (which I think is awesome), I think it's best to describe how one would start coding with yield.

In my opinion, the biggest advantage of using yield is that it will eliminate all the nested callback problems we see in code. It's hard to see how at first, which is why I decided to write this answer (for myself, and hopefully others!)

The way it does it is by introducing the idea of a co-routine, which is a function that can voluntarily stop/pause until it gets what it needs. In javascript, this is denoted by function*. Only function* functions can use yield.

Here's some typical javascript:

loadFromDB('query', function (err, result) {
  // Do something with the result or handle the error

This is clunky because now all of your code (which obviously needs to wait for this loadFromDB call) needs to be inside this ugly looking callback. This is bad for a few reasons...

  • All of your code is indented one level in
  • You have this end }) which you need to keep track of everywhere
  • All this extra function (err, result) jargon
  • Not exactly clear that you're doing this to assign a value to result

On the other hand, with yield, all of this can be done in one line with the help of the nice co-routine framework.

function* main() {
  var result = yield loadFromDB('query')

And so now your main function will yield where necessary when it needs to wait for variables and things to load. But now, in order to run this, you need to call a normal (non-coroutine function). A simple co-routine framework can fix this problem so that all you have to do is run this:


And start is defined (from Nick Sotiro' answer)

function start(routine, data) {
    result =;
    if(!result.done) {
        result.value(function(err, data) {
            if(err) routine.throw(err); // continue next iteration of routine with an exception
            else start(routine, data);  // continue next iteration of routine normally

And now, you can have beautiful code that is much more readable, easy to delete, and no need to fiddle with indents, functions, etc.

An interesting observation is that in this example, yield is actually just a keyword you can put before a function with a callback.

function* main() {
  console.log(yield function(cb) { cb(null, "Hello World") })

Would print "Hello World". So you can actually turn any callback function into using yield by simply creating the same function signature (without the cb) and returning function (cb) {}, like so:

function yieldAsyncFunc(arg1, arg2) {
  return function (cb) {
    realAsyncFunc(arg1, arg2, cb)

Hopefully with this knowledge you can write cleaner, more readable code that is easy to delete!

validation of input text field in html using javascript

function hasValue( val ) { // Return true if text input is valid/ not-empty
    return val.replace(/\s+/, '').length; // boolean

For multiple elements you can pass inside your input elements loop their value into that function argument.

If a user inserted one or more spaces, thanks to the regex s+ the function will return false.

'App not Installed' Error on Android

Clearly there are many causes of this problem. For me the situation was this: I had deployed to my nexus 7 (actual device) from within the Android Studio (v1.3.2). All worked fine. I then created a signed apk and uploaded to my Google Drive. After disconnecting my nexus from the usb, I went to the settings/apps and uninstalled my app (App1). I then opened google drive and clicked on my App1.apk and chose to install it (need to ensure you have allowed installation of apks in settings). Then I got the dreaded message "App not Installed"

Solution for me: go back into settings/apps and scroll though all apps and at the bottom was a pale version of my App1 (note the original App1 was at the top in Alphabetical order which was deleted as above). When clicking on the pale version it said "Not installed for this user". (I had set up my nexus to have more than one user). But in the top right corner there is a three dot button. I pressed this and it said "Uninstall for all users". Which I did and it fixed the problem. I was now able to click on App1.apk and it installed fine without the error.

Failed linking file resources

It's Obvious that if you have a big project, it will be a nightmare to check each and every xml file.

Run the following command in android studio terminal and it will give you the filename with the issue

gradlew build --stacktrace

enter image description here

Update row with data from another row in the same table

Try this:

                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

Eclipse can't find / load main class

Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

If you are getting following exception:

Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file

Then first check-in all the the directories and then all the files. It will work.

How do I compile with -Xlint:unchecked?

I know it sounds weird, but I'm pretty sure this is your problem:

Somewhere in you're using a generic collection without specifying the type. For example if you're using an ArrayList somewhere, you are doing this:

List list = new ArrayList();

When you should be doing this:

List<String> list = new ArrayList<String>();

Can not find the tag library descriptor for ""

Use taglib definition in your JSP or better include it in every page by the first line.

<%@ taglib prefix="c" uri="" %>

There's also fix jstl-1.2 dependency in your project. Also use servlet specification at least 2.4 in your web.xml.

The maven dependencies are (maven is a open source development tool)


In the web.xml start writing

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 


I'd like to add a note that @informatik01 has mentioned in the comment about newer version of JSTL libraries available from Maven repository: JSTL version 1.2.1 API and JSTL 1.2.1 .

How to set connection timeout with OkHttp

Adding in gradle file and sync project:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile ''

Adding in Java class:

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;

Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client =;

Using a SELECT statement within a WHERE clause

Subquery is the name.

At times it's required, but good/bad depends on how it's applied.

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
#myWorkContent a {
    display: inline;

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;

which would also vertically align images of different heights if required

test code

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    return new Blob(byteArrays, { type: contentType });

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });


I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

Android: Go back to previous activity

Add this in your onCLick() method, it will go back to your previous activity


or You can use this. It worked perfectly for me

  public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();

      if ( id == ) {
         return true;

  return super.onOptionsItemSelected(item);

MySQL Workbench Edit Table Data is read only

In MySQL Workbench you need an INDEX to edit, no need it to be PK (although adding a PK is a solution as well).

You can make a regular INDEX or compound INDEX. That's all MySQL WB needs to fix the Read only thing (I have v. 6.2 with MariaDB v. 10.1.4):

Just right click table, select "Alter table..." then go to "Indexes" tab. In the left pane put a custom name for your index, and in the middle pane checkmark one (make sure the vale will be unique) or more fields (just make sure the combination is unique)

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

| P(dBm) |        P(mW)      |
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace

Update records using LINQ

Strangely, for me it's SubmitChanges as opposed to SaveChanges:

    foreach (var item in w)
        if (Convert.ToInt32(e.CommandArgument) == item.ID)
            item.Sort = 1;
            item.Sort = null;

How to Export Private / Secret ASC Key to Decrypt GPG Files

All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key

gpg --edit-key (keyIDNumber)
gpg> trust

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

and select 5 to enable that imported private key as one of your keys

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

How can I generate an MD5 hash?

You can generate MD5 hash for a given text by making use of the methods in the MessageDigest class in the package. Below is the complete code snippet,

import javax.xml.bind.DatatypeConverter;

public class MD5HashGenerator 

   public static void main(String args[]) throws NoSuchAlgorithmException
       String stringToHash = "MyJavaCode"; 
       MessageDigest messageDigest = MessageDigest.getInstance("MD5");
       byte[] digiest = messageDigest.digest();
       String hashedOutput = DatatypeConverter.printHexBinary(digiest);

The output from the MD5 function is a 128 bit hash represented by 32 hexadecimal numbers.

In case, if you are using a database like MySQL, you can do this in a more simpler way as well. The query Select MD5(“text here”) will return the MD5 hash of the text in the bracket.

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

One way to solve this problem is by turning the warnings off.


Could not find method compile() for arguments Gradle

Make sure that you are editing the correct build.gradle file. I received this error when editing android/build.gradle rather than android/app/build.gradle.

SQLite: How do I save the result of a query as a CSV file?

Alternatively you can do it in one line (tested in win10)

sqlite3 -help
sqlite3 -header -csv db.sqlite 'select * from tbl1;' > test.csv

Bonus: Using powershell with cmdlet and pipe (|).

get-content query.sql | sqlite3 -header -csv db.sqlite > test.csv

where query.sql is a file containing your SQL query

How to define a default value for "input type=text" without using attribute 'value'?

The value is there. The source is not updated as the values on the form change. The source is from when the page initially loaded.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.


is not a static method. Either you have to create an instance of Program

Program p = new Program();

or make

GetRandomBits() static.

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

How do I print a list of "Build Settings" in Xcode project?

This has been answered above, but I wanted to suggest an alternative.

When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles, select this to change back to the original view.

This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

seeing how the rules are fairly complicated, I'd suggest the following:


match the whole string and capture intermediate characters. Then either with the string functions or the following regex:


check if the captured part has two underscores in a row. For example in Python it would look like this:

>>> import re
>>> def valid(s):
    match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
    if match is not None:
        return'__') == 0
    return False

PHP array() to javascript array()

 <script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
 $(function() {
     function disableRangeOfDays(d) {

in the above assign array to javascript variable "disableDaysRange"

$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
 $disallowDates .= "'".$disableDates."',";

echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";

so your javascript var diableDateRange shoudl be 

var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];

Correct location of openssl.cnf file


is soft link of


You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

Insert a line break in mailto body

For plaintext email using JavaScript, you may also use \r with encodeURIComponent().

For example, this message:

hello\rthis answer is now well formated\rand it contains good knowleadge\rthat is why I am up voting

URI Encoded, results in:


And, using the href:

mailto:[email protected]?body=hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting

Will result in the following email body text:

this answer is now well formated
and it contains good knowleadge
that is why I am up voting

How to remove specific elements in a numpy array

If you don't know the index, you can't use logical_and

x = 10*np.random.randn(1,100)
low = 5
high = 27

Error 5 : Access Denied when starting windows service

I had this issue on a service that I was deploying, and none of the other suggestions on this question worked. In my case, it was because my .config (xml) wasn't valid. I made a copy and paste error when copying from qualif to prod.

How to check if JSON return is empty with jquery

if ( json.length == 0 ) 
console.log("NO !")

Python 3 print without parenthesis

The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:

SetTitleMatchMode,2         ;;; allows for a partial search 
#IfWinActive, .py           ;;; scope limiter to only python files
:b*:print ::print(){Left}   ;;; I forget what b* does
#IfWinActive                ;;; remove the scope limitation

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

With the support of CSS custom properties (variables) in iOS, you can set these with JS and use them on iOS only.

const iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (iOS) {
  const vh = window.innerHeight / 100;
    .setProperty('--ios-10-vh', `${10 * vh}px`);
    .setProperty('--ios-50-vh', `${50 * vh}px`);
    .setProperty('--ios-100-vh', `${100 * vh}px`);
body.ios {
    .side-nav {
        top: var(--ios-50-vh);
    section {
        min-height: var(--ios-100-vh);
        .container {
            position: relative;
            padding-top: var(--ios-10-vh);
            padding-bottom: var(--ios-10-vh);