Programs & Examples On #Inet socket

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

Check if a user has scrolled to the bottom

Please check this answer

 window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
       console.log("bottom");
    }
};

You can do footerHeight - document.body.offsetHeight to see if you are near the footer or reached the footer

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u

chmod +x test.py
./test.py
moçambique
moçambique

./test.py > output.txt
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    print u
UnicodeEncodeError: 'ascii' codec can't encode character 
u'\xe7' in position 2: ordinal not in range(128)

on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

import sys
if (sys.stdout.encoding is None):            
    print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
    exit(1)


so, using same example:

export PYTHONIOENCODING=UTF-8
./test.py > output.txt

will work

no such file to load -- rubygems (LoadError)

gem install bundler

fixed the issue for me.

Extreme wait-time when taking a SQL Server database offline

Closing the instance of SSMS (SQL Service Manager) from which the request was made solved the problem for me.....

Cannot stop or restart a docker container

Worth knowing:

If you are running an ENTRYPOINT script ... the script will work with the shebang

#!/bin/bash -x

But will stop the container from stopping with

#!/bin/bash -xe

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

In httpd.conf instead:

Listen *:443

you need write Listen 127.0.0.1:443 It works for me.

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

pretty-print JSON using JavaScript

Here is how you can print without using native function.

function pretty(ob, lvl = 0) {

  let temp = [];

  if(typeof ob === "object"){
    for(let x in ob) {
      if(ob.hasOwnProperty(x)) {
        temp.push( getTabs(lvl+1) + x + ":" + pretty(ob[x], lvl+1) );
      }
    }
    return "{\n"+ temp.join(",\n") +"\n" + getTabs(lvl) + "}";
  }
  else {
    return ob;
  }

}

function getTabs(n) {
  let c = 0, res = "";
  while(c++ < n)
    res+="\t";
  return res;
}

let obj = {a: {b: 2}, x: {y: 3}};
console.log(pretty(obj));

/*
  {
    a: {
      b: 2
    },
    x: {
      y: 3
    }
  }
*/

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

How do I run a Python program in the Command Prompt in Windows 7?

You need to edit the environment variable named PATH, and add ;c:\python27 to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH).

Alternately, you can just type

c:\python27\python

at the command prompt without having to modify any environment variables at all.

How can I know when an EditText loses focus?

Its Working Properly

EditText et_mobile= (EditText) findViewById(R.id.edittxt);

et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {          
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // code to execute when EditText loses focus
            if (et_mobile.getText().toString().trim().length() == 0) {
                CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
            }
        }
    }
});



public static void showAlert(String message, Activity context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message).setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    try {
        builder.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Display only 10 characters of a long string?

Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.

Ternary operator will sort that out:

var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;

var result = text.slice(0, count) + (text.length > count ? "..." : "");

Can be closed to function:

function fn(text, count){
    return text.slice(0, count) + (text.length > count ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10));

And expand to helpers class so You can even choose if You want the dots or not:

function fn(text, count, insertDots){
    return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));

Convert to binary and keep leading zeros in Python

You can use zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

prints:

01
10
100

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. - x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.

How to connect android emulator to the internet

There are different solutions to this problem . One of these , i will show you on my experiment and outcomes seen on results using a recent android studio and AVD images downloaded 2017.

  1. First thing you have to do is launch your AVD from android studio.(in my case i choose NEXUSAPI25 android 7.1 image)

  2. Goto Settings->Wirless and Networking - > Cellular Network - > Access Points -> (+) press add - > enter the following if you dont have NTLM proxy or proxy at all (that means you are directly connected)

    a. add apn name as myAPN b. add apn server => www c. save and try browsing the internet.

if this doesn work add 'ANDROID_SDK_ROOT' in you environment variable

Then , launch AVD using emulator command as follow

emulator -avd Nexus25 -dns-server 8.8.8.8
  1. For those who use NTLM proxies , i will show you how it work for me next.

  2. add your Android_sdk_root path into your environment variable. THis make command line code read succesfully like using AVD names and so on.

  3. Launch your emaulator using the following command

>emulator -avd Nexus_5X_API_25 -http-proxy http://username:password@ipaddress:port

ENTER

enter image description here

enter image description here

How to hide the title bar for an Activity in XML with existing custom theme

In my case, if you are using android studio 2.1, and your compile SDK version is 6.0, then just go to your manifest.xml file, and change the following code:

Here is the code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lesterxu.testapp2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And here is the snip shoot(see the highlight code): enter image description here

How do I escape only single quotes?

After a long time fighting with this problem, I think I have found a better solution.

The combination of two functions makes it possible to escape a string to use as HTML.

One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.

Solution:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

  • a PHP line created to call a JavaScript function like

echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"

How merge two objects array in angularjs?

You can use angular.extend(dest, src1, src2,...);

In your case it would be :

angular.extend($scope.actions.data, data);

See documentation here :

https://docs.angularjs.org/api/ng/function/angular.extend

Otherwise, if you only get new values from the server, you can do the following

for (var i=0; i<data.length; i++){
    $scope.actions.data.push(data[i]);
}

Handling NULL values in Hive

Try to include length > 0 as well.

column1 is not NULL AND column1 <> '' AND length(column1) > 0 

How to join (merge) data frames (inner, outer, left, right)

New in 2014:

Especially if you're also interested in data manipulation in general (including sorting, filtering, subsetting, summarizing etc.), you should definitely take a look at dplyr, which comes with a variety of functions all designed to facilitate your work specifically with data frames and certain other database types. It even offers quite an elaborate SQL interface, and even a function to convert (most) SQL code directly into R.

The four joining-related functions in the dplyr package are (to quote):

  • inner_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are matching values in y, and all columns from x and y
  • left_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x, and all columns from x and y
  • semi_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are matching values in y, keeping just columns from x.
  • anti_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are not matching values in y, keeping just columns from x

It's all here in great detail.

Selecting columns can be done by select(df,"column"). If that's not SQL-ish enough for you, then there's the sql() function, into which you can enter SQL code as-is, and it will do the operation you specified just like you were writing in R all along (for more information, please refer to the dplyr/databases vignette). For example, if applied correctly, sql("SELECT * FROM hflights") will select all the columns from the "hflights" dplyr table (a "tbl").

When should I use double or single quotes in JavaScript?

I've been running the following about 20 times. And it appears that double quotes are about 20% faster.

The fun part is, if you change part 2 and part 1 around, single quotes are about 20% faster.

//Part1
var r='';
var iTime3 = new Date().valueOf();
for(var j=0; j<1000000; j++) {
    r+='a';
}
var iTime4 = new Date().valueOf();
alert('With single quote : ' + (iTime4 - iTime3));  

//Part 2                
var s="";
var iTime1 = new Date().valueOf();
for(var i=0; i<1000000; i++) {
    s += "a";
}
var iTime2 = new Date().valueOf();
alert('With double quote: ' + (iTime2 - iTime1));

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

Create a button programmatically and set a background image

Try below:

let image = UIImage(named: "ImageName.png") as UIImage
var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button .setBackgroundImage(image, forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)
menuView.addSubview(button)

Let me know whether if it works or not?

How do I capture response of form.submit

Building on the answer by @rajesh_kw (https://stackoverflow.com/a/22567796/4946681), I handle form post errors and success:

    $('#formName').on('submit', function(event) {
        event.preventDefault(); // or return false, your choice
        $.ajax({
            url: $(this).attr('action'),
            type: 'post',
            data: $(this).serialize(),
            success: function(data, textStatus, jqXHR) {
                // if success, HTML response is expected, so replace current
                if(textStatus === 'success') {
                    // https://stackoverflow.com/a/1236378/4946681
                    var newDoc = document.open('text/html', 'replace');
                    newDoc.write(data);
                    newDoc.close();
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            if(jqXHR.status == 0 || jqXHR == 302) {
                alert('Your session has ended due to inactivity after 10 minutes.\nPlease refresh this page, or close this window and log back in to system.');
            } else {
                alert('Unknown error returned while saving' + (typeof errorThrown == 'string' && errorThrown.trim().length > 0 ? ':\n' + errorThrown : ''));
            }
        });
    });

I make use of this so that my logic is reusable, I expect HTML to be returned on a success so I render it and replace the current page, and in my case I expect a redirect to the login page if the session is timed out, so I intercept that redirect in order to preserve the state of the page.

Now users can log in via another tab and try their submit again.

Process all arguments except the first one (in a bash script)

Came across this looking for something else. While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}" where # is the starting number of the array element we want to preserve forward:

    #!/bin/bash

    someVar="${1}"
    someOtherVar="${2}"
    set -- "${@:3}"
    input=${@}

    [[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"

    echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"

Basically, the set -- "${@:3}" just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.

Parsing boolean values with argparse

Convert the value:

def __arg_to_bool__(arg):
    """__arg_to_bool__

        Convert string / int arg to bool
    :param arg: argument to be converted
    :type arg: str or int
    :return: converted arg
    :rtype: bool
    """
    str_true_values = (
        '1',
        'ENABLED',
        'ON',
        'TRUE',
        'YES',
    )
    str_false_values = (
        '0',
        'DISABLED',
        'OFF',
        'FALSE',
        'NO',
    )

    if isinstance(arg, str):
        arg = arg.upper()
        if arg in str_true_values:
            return True
        elif arg in str_false_values:
            return False

    if isinstance(arg, int):
        if arg == 1:
            return True
        elif arg == 0:
            return False

    if isinstance(arg, bool):
        return arg

    # if any other value not covered above, consider argument as False
    # or you could just raise and error
    return False

[...]


args = ap.parse_args()
my_arg = options.my_arg
my_arg = __arg_to_bool__(my_arg)

Fastest way to convert JavaScript NodeList to Array?

Assuming nodeList = document.querySelectorAll("div"), this is a concise form of converting nodelist to array.

var nodeArray = [].slice.call(nodeList);

See me use it here.

How can I create tests in Android Studio?

I would suggest to use gradle.build file.

  1. Add a src/androidTest/java directory for the tests (Like Chris starts to explain)

  2. Open gradle.build file and specify there:

    android {
    
        compileSdkVersion rootProject.compileSdkVersion
        buildToolsVersion rootProject.buildToolsVersion
    
        sourceSets {
    
            androidTest {
                java.srcDirs = ['androidTest/java']
            }
        }
    }
    
  3. Press "Sync Project with Gradle file" (at the top panel). You should see now a folder "java" (inside "androidTest") is a green color.

  4. Now You are able to create there any test files and execute they.

How to replace an entire line in a text file by line number

in bash, replace N,M by the line numbers and xxx yyy by what you want

i=1
while read line;do
  if((i==N));then
    echo 'xxx'
  elif((i==M));then
    echo 'yyy'
  else
    echo "$line"
  fi
  ((i++))
done  < orig-file > new-file

EDIT

In fact in this solution there are some problems, with characters "\0" "\t" and "\"

"\t", can be solve by putting IFS= before read: "\", at end of line with -r

IFS= read -r line

but for "\0", the variable is truncated, there is no a solution in pure bash : Assign string containing null-character (\0) to a variable in Bash But in normal text file there is no nul character \0

perl would be a better choice

perl -ne 'if($.==N){print"xxx\n"}elsif($.==M){print"yyy\n"}else{print}' < orig-file > new-file

How to get the excel file name / path in VBA

ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.

If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.

500 Internal Server Error for php file not for html

I was having this problem because I was trying to connect to MySQL but I didn't have the required package. I figured it out because of @Amadan's comment to check the error log. In my case, I was having the error: Call to undefined function mysql_connect()

If your PHP file has any code to connect with a My-SQL db then you might need to install php5-mysql first. I was getting this error because I hadn't installed it. All my file permissions were good. In Ubuntu, you can install it by the following command:

sudo apt-get install php5-mysql

python selenium click on button

The following debugging process helped me solve a similar issue.

with open("output_init.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))


xpath1 = "the xpath of the link you want to click on"
destination_page_link = driver.find_element_by_xpath(xpath1)
destination_page_link.click()


with open("output_dest.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))

You should then have two textfiles with the initial page you were on ('output_init.txt') and the page you were forwarded to after clicking the button ('output_dest.txt'). If they're the same, then yup, your code did not work. If they aren't, then your code worked, but you have another issue. The issue for me seemed to be that the necessary javascript that transformed the content to produce my hook was not yet executed.

Your options as I see it:

  1. Have the driver execute the javascript and then call your find element code. Look for more detailed answers on this on stackoverflow, as I didn't follow this approach.
  2. Just find a comparable hook on the 'output_dest.txt' that will produce the same result, which is what I did.
  3. Try waiting a bit before clicking anything:

xpath2 = "your xpath that you are going to click on"

WebDriverWait(driver, timeout=5).until(lambda x: x.find_element_by_xpath(xpath2))

The xpath approach isn't necessarily better, I just prefer it, you can also use your selector approach.

Start service in Android

I like to make it more dynamic

Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }

do not forget the Manifest

<service android:enabled="true" android:name=".MyService.class" />

How do you push just a single Git branch (and no other branches)?

Minor update on top of Karthik Bose's answer - you can configure git globally, to affect all of your workspaces to behave that way:

git config --global push.default upstream

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

How to get started with Windows 7 gadgets

Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.

Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.

Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.

Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.

Fast way to get the min/max values among properties of object

// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]


//Min:
Sorted.shift()
>> [ 'c', 0.35 ]

// Max:
Sorted.pop()
>> [ 'd', 5 ]

select from one table, insert into another table oracle sql query

You can use

insert into <table_name> select <fieldlist> from <tables>

Jquery $.ajax fails in IE on cross domain calls

I had a similar problem in IE9 where some CORS calls were aborting, while others weren't. My app is also dependent on a promise interface, so the XDomainRequest suggestions above weren't EXACTLY what I needed, so I added a deferred into my service.get workaround for IE9. Hopefully it can be useful to someone else running across this problem. :

    get: function (url) {
        if ('XDomainRequest' in window && window.XDomainRequest !== null) {
            var deferred = $.Deferred();
            var xdr      = new XDomainRequest();

            xdr.open("get", url);

            xdr.onload = function() {
              json = xdr.responseText;
              parsed_json = $.parseJSON(json);
              deferred.resolve(parsed_json);
            }

            xdr.send();
            return deferred;
        } else {
            return $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                crossDomain: true
            });
        }
    }

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

How to use pagination on HTML tables?

There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.

.map() a Javascript ES6 Map?

You can use myMap.forEach, and in each loop, using map.set to change value.

_x000D_
_x000D_
myMap = new Map([_x000D_
  ["a", 1],_x000D_
  ["b", 2],_x000D_
  ["c", 3]_x000D_
]);_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}_x000D_
_x000D_
_x000D_
myMap.forEach((value, key, map) => {_x000D_
  map.set(key, value+1)_x000D_
})_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}
_x000D_
_x000D_
_x000D_

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

Favicon: .ico or .png / correct tags?

For compatibility with all browsers stick with .ico.

.png is getting more and more support though as it is easier to create using multiple programs.

for .ico

<link rel="shortcut icon" href="http://example.com/myicon.ico" />

for .png, you need to specify the type

<link rel="icon" type="image/png" href="http://example.com/image.png" />

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

How can a LEFT OUTER JOIN return more records than exist in the left table?

Could it be a one to many relationship between the left and right tables?

Map vs Object in JavaScript

These two tips can help you to decide whether to use a Map or an Object:

  • Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.

  • Use maps in case if there is a need to store primitive values as keys because object treats each key as a string either its a number value, boolean value or any other primitive value.

  • Use objects when there is logic that operates on individual elements.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_Collections#Object_and_Map_compared

mongodb service is not starting up

This can also happen if your file permissions get changed somehow. Removing the lock file didn't help, and we were getting errors in the log file like:

2016-01-20T09:14:58.210-0800 [initandlisten] warning couldn't write to / rename file /var/lib/mongodb/journal/prealloc.0: couldn't open file    /var/lib/mongodb/journal/prealloc.0 for writing errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] couldn't open /var/lib/mongodb/local.ns errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] error couldn't open file /var/lib/mongodb/local.ns terminating

So, went to check permissions:

ls -l /var/lib/mongodb

total 245780
drwxr-xr-x 2 mongodb mongodb     4096 Jan 20 09:14 journal
drwxr-xr-x 2 root    root        4096 Jan 20 09:11 local
-rw------- 1 root    root    67108864 Jan 20 09:11 local.0
-rw------- 1 root    root    16777216 Jan 20 09:11 local.ns
-rwxr-xr-x 1 mongodb nogroup        0 Jan 20 09:14 mongod.lock

To fix:

# chown -R mongodb:mongodb /var/lib/mongodb

Remove the lock file if it's still there:

# rm /var/lib/mongodb/mongod.lock

Start mongodb

# service mongodb start

Tail the log and you should see at the end of it:

tail -f /var/log/mongodb/mongodb.log
2016-01-20T09:16:02.025-0800 [initandlisten] waiting for connections on port 27017

How to get time difference in minutes in PHP

Subtract the past most one from the future most one and divide by 60.

Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT

Team Build Error: The Path ... is already mapped to workspace

Simplest way to do this is to go to your AppData and delete the TFS cache (depending on the version 3.0 or 4.0)

C:\Users{UserName}\AppData\Local\Microsoft\Team Foundation\3.0\Cache or C:\Users{UserName}\AppData\Local\Microsoft\Team Foundation\4.0\Cache

How to access the php.ini file in godaddy shared hosting linux

Not php.ini file, but a way around it. Go to GoDaddy's

Files > Backup > Restore a MySQL Database Backup

Choose your file and click Upload. No timeouts. Rename the DB if needed, and assign a user in

Databases > MySQL Databases

Image.open() cannot identify image file - Python?

In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.

cat, grep and cut - translated to python

you need to use os.system module to execute shell command

import os
os.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

Show which git tag you are on?

Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:

git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)

original answer follows:

git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...

This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.

The $() syntax above assumes you're using bash or similar.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

prevent property from being serialized in web API

Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute and DataMemberAttribute, found in the System.Runtime.Serialization namespace.

The DataContactAttribute is applied to the class, and the DataMemberAttribute is applied to each member you want to be serialized:

[DataContract]
public class MyClass {

  [DataMember]
  public int Id { get; set;} // Serialized

  [DataMember]
  public string Name { get; set; } // Serialized

  public string DontExposeMe { get; set; } // Will not be serialized
}

Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.

Tools for making latex tables in R

Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.

library(datasets)
library(taRifx)
library(xtable)

test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
#   then add \usepackage{multirow} to the preamble of your LaTeX document
#   for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble

sample table output

How to save MySQL query output to excel or .txt file?

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

Django MEDIA_URL and MEDIA_ROOT

This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

Android camera android.hardware.Camera deprecated

Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight

   public class MainActivity extends AppCompatActivity {

     Button button;

     Boolean light=true;

     CameraDevice cameraDevice;

     private CameraManager cameraManager;

     private CameraCharacteristics cameraCharacteristics;

     String cameraId;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        cameraManager = (CameraManager) 
        getSystemService(Context.CAMERA_SERVICE);
        try {
          cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    try {

                        cameraManager.setTorchMode(cameraId,true);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                    light=false;}
                    else {

                    try {

                      cameraManager.setTorchMode(cameraId,false);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }


                    light=true;
                    }


            }
        });
    }
}

trace a particular IP and port

You can use the default traceroute command for this purpose, then there will be nothing to install.

traceroute -T -p 9100 <IP address/hostname>

The -T argument is required so that the TCP protocol is used instead of UDP.

In the rare case when traceroute isn't available, you can also use ncat.

nc -Czvw 5 <IP address/hostname> 9100

How to replace specific values in a oracle database column?

Use REPLACE:

SELECT REPLACE(t.column, 'est1', 'rest1')
  FROM MY_TABLE t

If you want to update the values in the table, use:

UPDATE MY_TABLE t
   SET column = REPLACE(t.column, 'est1', 'rest1')

Why am I getting "void value not ignored as it ought to be"?

    int a = srand(time(NULL))
        arr[i] = a;

Should be

        arr[i] = rand();

And put srand(time(NULL)) somewhere at the very beginning of your program.

MVC DateTime binding with incorrect date format

It going to be slightly different in MVC 3.

Suppose we have a controller and a view with Get method

public ActionResult DoSomething(DateTime dateTime)
{
    return View();
}

We should add ModelBinder

public class DateTimeBinder : IModelBinder
{
    #region IModelBinder Members
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        DateTime dateTime;
        if (DateTime.TryParse(controllerContext.HttpContext.Request.QueryString["dateTime"], CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dateTime))
            return dateTime;
        //else
        return new DateTime();//or another appropriate default ;
    }
    #endregion
}

and the command in Application_Start() of Global.asax

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());

Laravel 4: how to run a raw SQL?

You can also use DB::unprepared for ALTER TABLE queries.

DB::unprepared is meant to be used for queries like CREATE TRIGGER. But essentially it executes raw sql queries directly. (without using PDO prepared statements)

https://github.com/laravel/framework/pull/54

Difference between rake db:migrate db:reset and db:schema:load

As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb file. That is why you need to make sure that your schema.rb file is always up to date and under version control.

Install IPA with iTunes 12

Tested on iTunes 12.5.3.17

1.Open the iTunes select the “Apps” section with in that select the “Library”

enter image description here

2.Now drag and drop the file AppName.ipa in this Library section (Before connecting your iOS device to your computer machine)

enter image description here

3.Now connect your iOS device to your computer machine, we are able to see our device in iTunes…

enter image description here

4.Select your device go to “Apps” section of your device and search your App in the list of apps with "Install" button infront of it.

enter image description here

5.Now hit the “Install” button and then press the “Done” button in bottom right corner, The “Install” button will turn in to “Will Install” one alert will be shown to you with two options “Don’t Apply”, “Apply”, hit on option “Apply”.

enter image description here

6.The “App installation” will start on your device with progress….

enter image description here

7.Finally the app will be installed on your iOS device and you will be able to use it…

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

What do \t and \b do?

The C standard (actually C99, I'm not up to date) says:

Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:

\b (backspace) Moves the active position to the previous position on the current line. [...]

\t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. [...]

Both just move the active position, neither are supposed to write any character on or over another character. To overwrite with a space you could try: puts("foo\b \tbar"); but note that on some display devices - say a daisy wheel printer - the o will show the transparent space.

How to achieve pagination/table layout with Angular.js?

The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:
HTML

<table>
  <thead>
     ...
  </thead>
  <tbody>
     <tr *ngFor="let row of rowData | slice:startIndex:endIndex">
        ...
     </tr>
  </tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item">
            <a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
            <a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>

        <li class="page-item">
            <a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    </ul>
</nav>


TypeScript

...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
        if (length % this.paginationRowCount === 0) {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
        } else {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
        }
        return this.pageNumberArray;
    }

    updateIndex(pageIndex) {
        this.startIndex = pageIndex * this.paginationRowCount;
        if (this.rowData.length > this.startIndex + this.paginationRowCount) {
            this.endIndex = this.startIndex + this.paginationRowCount;
        } else {
            this.endIndex = this.rowData.length;
        }
    }

Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

How can I use pointers in Java?

Technically, all Java objects are pointers. All primitive types are values though. There is no way to take manual control of those pointers. Java just internally uses pass-by-reference.

Form onSubmit determine which submit button was pressed

Bare bones, but confirmed working, example:

<script type="text/javascript">
var clicked;
function mysubmit() {
    alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
    <input type="submit" onclick="clicked='Save'" value="Save" />
    <input type="submit" onclick="clicked='Add'" value="Add" />
</form>

Getting distance between two points based on latitude/longitude

import numpy as np


def Haversine(lat1,lon1,lat2,lon2, **kwarg):
    """
    This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, 
    the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points 
    (ignoring any hills they fly over, of course!).
    Haversine
    formula:    a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
    c = 2 · atan2( va, v(1-a) )
    d = R · c
    where   f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
    note that angles need to be in radians to pass to trig functions!
    """
    R = 6371.0088
    lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
    c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
    d = R * c
    return round(d,4)

How can I put a database under git (version control)?

I would recommend neXtep for version controlling the database it has got a good set of documentation and forums that explains how to install and the errors encountered. I have tested it for postgreSQL 9.1 and 9.3, i was able to get it working for 9.1 but for 9.3 it doesn't seems to work.

How to exclude rows that don't join with another table?

SELECT
   *
FROM
   primarytable P
WHERE
   NOT EXISTS (SELECT * FROM secondarytable S
     WHERE
         P.PKCol = S.FKCol)

Generally, (NOT) EXISTS is a better choice then (NOT) IN or (LEFT) JOIN

Click outside menu to close in jquery

The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :

$('a#menu-link').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    $('#menu').toggleClass('open');

    $(document).one('click', function closeMenu (e){
        if($('#menu').has(e.target).length === 0){
            $('#menu').removeClass('open');
        } else {
            $(document).one('click', closeMenu);
        }
    });
});

Edit: if you want to avoid the stopPropagation() on the initial button you can use this

var $menu = $('#menu');

$('a#menu-link').on('click', function(e) {
    e.preventDefault();

    if (!$menu.hasClass('active')) {
        $menu.addClass('active');

        $(document).one('click', function closeTooltip(e) {
            if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
                $menu.removeClass('active');
            } else if ($menu.hasClass('active')) {
                $(document).one('click', closeTooltip);
            }
        });
    } else {
        $menu.removeClass('active');
    }
});

Can someone explain how to implement the jQuery File Upload plugin?

I was looking for a similar functionality some days back and came across a good tutorial on tutorialzine. Here is an working example. Complete tutorial can be found here.

Simple form to hold the file upload dialogue:

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="uploadctl" multiple />
  <ul id="fileList">
    <!-- The file list will be shown here -->
  </ul>
</form>

And here is the jQuery code to upload the files:

$('#upload').fileupload({

  // This function is called when a file is added to the queue
  add: function (e, data) {
    //This area will contain file list and progress information.
    var tpl = $('<li class="working">'+
                '<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
                '<p></p><span></span></li>' );

    // Append the file name and file size
    tpl.find('p').text(data.files[0].name)
                 .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

    // Add the HTML to the UL element
    data.context = tpl.appendTo(ul);

    // Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
    tpl.find('input').knob();

    // Listen for clicks on the cancel icon
    tpl.find('span').click(function(){
      if(tpl.hasClass('working')){
              jqXHR.abort();
      }
      tpl.fadeOut(function(){
              tpl.remove();
      });
    });

    // Automatically upload the file once it is added to the queue
    var jqXHR = data.submit();
  },
  progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    }
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }

    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2) + ' GB';
    }

    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
    }
    return (bytes / 1000).toFixed(2) + ' KB';
}

And here is the PHP code sample to process the data:

if($_POST) {
    $allowed = array('jpg', 'jpeg');

    if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){

        $extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);

        if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
        }

        if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
            echo '{"status":"success"}';
            exit;
        }
        echo '{"status":"error"}';
    }
    exit();
}

The above code can be added to any existing form. This program automatically uploads images, once they are added. This functionality can be changed and you can submit the image, while you are submitting your existing form.

Updated my answer with actual code. All credits to original author of the code.

Source: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

How do I disable the resizable property of a textarea?

In CSS ...

textarea {
    resize: none;
}

PivotTable's Report Filter using "greater than"

After some research I finally got a VBA code to show the filter value in another cell:

Dim bRepresentAsRange As Boolean, bRangeBroken As Boolean
Dim sSelection As String
Dim tbl As Variant
bRepresentAsRange = False
bRangeBroker = False

With Worksheets("Forecast").PivotTables("ForecastbyDivision")
            ReDim tbl(.PageFields("Probability").PivotItems.Count)
            For Each fld In .PivotFields("Probability").PivotItems

                If fld.Visible Then
                    tbl(n) = fld.Name
                    sSelection = sSelection & fld.Name & ","
                    n = n + 1
                    bRepresentAsRange = True
                Else
                    If bRepresentAsRange Then
                        bRepresentAsRange = False
                        bRangeBroken = True
                    End If
                End If

            Next fld

            If Not bRangeBroken Then
                Worksheets("Forecast").Range("ProbSelection") = " >= " & tbl(0)
            Else
                Worksheets("Forecast").Range("ProbSelection") = Left(sSelection, Len(sSelection) - 1)
            End If

        End With

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

It's included because your minimum SDK version is set to 10. The ActionBar was introduced in API 11. Eclipse adds it automatically so your app can look more consistent throughout the spectrum of all android versions you are supporting.

How to center HTML5 Videos?

I was having the same problem, until I realized that <video> elements are inline elements, not block elements. You need only set the container element to have text-align: center; in order to center the video horizontally on the page.

Checking during array iteration, if the current element is the last element

My solution, also quite simple..

$array = [...];
$last = count($array) - 1;

foreach($array as $index => $value) 
{
     if($index == $last)
        // this is last array
     else
        // this is not last array
}

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Node.js on multi-core machines

Future version of node will allow you to fork a process and pass messages to it and Ryan has stated he wants to find some way to also share file handlers, so it won't be a straight forward Web Worker implementation.

At this time there is not an easy solution for this but it's still very early and node is one of the fastest moving open source projects I've ever seen so expect something awesome in the near future.

Good Patterns For VBA Error Handling

Also relevant to the discussion is the relatively unknown Erl function. If you have numeric labels within your code procedure, e.g.,

Sub AAA()
On Error Goto ErrorHandler

1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
   Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
      "Last Successful Line: " + CStr(Erl)
End If   
End Sub 

The Erl function returns the most recently encountered numberic line label. In the example above, if a run-time error occurs after label 1200: but before 1300:, the Erl function will return 1200, since that is most recenlty sucessfully encountered line label. I find it to be a good practice to put a line label immediately above your error handling block. I typcially use 9999 to indicate that the main part of the procuedure ran to its expected conculsion.

NOTES:

  • Line labels MUST be positive integers -- a label like MadeItHere: isn't recogonized by Erl.

  • Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000. There is no relationship between editor line numbers and line label numbers used with Erl.

  • Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl is greatly diminished, but Erl will still report the correct number.

  • Line labels are specific to the procedure in which they appear. If procedure ProcA calls procedure ProcB and an error occurs in ProcB that passes control back to ProcA, Erl (in ProcA) will return the most recently encounterd line label number in ProcA before it calls ProcB. From within ProcA, you cannot get the line label numbers that might appear in ProcB.

Use care when putting line number labels within a loop. For example,

For X = 1 To 100
500:
' some code that causes an error
600:
Next X

If the code following line label 500 but before 600 causes an error, and that error arises on the 20th iteration of the loop, Erl will return 500, even though 600 has been encounterd successfully in the previous 19 interations of the loop.

Proper placement of line labels within the procedure is critical to using the Erl function to get truly meaningful information.

There are any number of free utilies on the net that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.

If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl in that information can make finding and fixing the problem VASTLY simpler than if value of Erl is not reported.

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

How does database indexing work?

Simple Description!

The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.

Example: We have a database table called User with three columns – Name, Age and Address. Assume that the User table has thousands of rows.

Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:

SELECT * FROM User 
WHERE Name = 'John'

The database software would literally have to look at every single row in the User table to see if the Name for that row is ‘John’. This will take a long time.

This is where index helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.

How to create an index:

CREATE INDEX name_index
ON User (Name)

An index consists of column values(Eg: John) from one table, and those values are stored in a data structure.

So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!

Searching in a ArrayList with custom objects for certain strings

String string;
for (Datapoint d : dataPointList) {    
   Field[] fields = d.getFields();
   for (Field f : fields) {
      String value = (String) g.get(d);
      if (value.equals(string)) {
         //Do your stuff
      }    
   }
}

Last segment of URL in jquery

The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.

Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:

Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);

Output: 'boo'

This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).

Format an Excel column (or cell) as Text in C#?

//where [1] - column number which you want to make text

ExcelWorksheet.Columns[1].NumberFormat = "@";


//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.

  //path were excel file is kept


     string ResultsFilePath = @"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";

            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
            ExcelApp.Visible = true;

            //Looping through all available sheets
            foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
            {                
                //Selecting the worksheet where we want to perform action
                ExcelWorksheet.Select(Type.Missing);
                ExcelWorksheet.Columns[1].NumberFormat = "@";
            }

            //saving excel file using Interop
            ExcelWorkbook.Save();

            //closing file and releasing resources
            ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(ExcelWorkbook);
            ExcelApp.Quit();
            Marshal.FinalReleaseComObject(ExcelApp);

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Our issue was simply the port number on the endpoint was incorrectly set to 8080. Changed it to 8443 and it worked.

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Is there a simple, elegant way to define singletons?

See this implementation from PEP318, implementing the singleton pattern with a decorator:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

Using both Python 2.x and Python 3.x in IPython Notebook

With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.

The Details

  1. Create this directory: mkdir -p ~/.ipython/kernels/python3
  2. Create this file ~/.ipython/kernels/python3/kernel.json with this content:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
    
  3. Restart the notebook server.

  4. Select „Python 3“ from the dropdown menu „New“
  5. Work with a Python 3 Notebook
  6. Select „Python 2“ from the dropdown menu „New“
  7. Work with a Python 2 Notebook

Change priorityQueue to max priorityqueue

Here is a sample Max-Heap in Java :

PriorityQueue<Integer> pq1= new PriorityQueue<Integer>(10, new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
if (x < y) return 1;
if (x > y) return -1;
return 0;
}
});
pq1.add(5);
pq1.add(10);
pq1.add(-1);
System.out.println("Peek: "+pq1.peek());

The output will be 10

How to remove \n from a list element?

From Python3 onwards

map no longer returns a list but a mapObject, thus the answer will look something like

>>> map(lambda x:x.strip(),l)
<map object at 0x7f00b1839fd0>

You can read more about it on What’s New In Python 3.0.

map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...))

So now what are the ways of getting trough this?


Case 1 - The list call over map with a lambda

map returns an iterator. list is a function that can convert an iterator to a list. Hence you will need to wrap a list call around map. So the answer now becomes,

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> list(map(lambda x:x.strip(),l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Very good, we get the output. Now we check the amount of time it takes for this piece of code to execute.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(lambda x:x.strip(),l))"
100000 loops, best of 3: 2.22 usec per loop

2.22 microseconds. That is not so bad. But are there more efficient ways?


Case 2 - The list call over map withOUT a lambda

lambda is frowned upon by many in the Python community (including Guido). Apart from that it will greatly reduce the speed of the program. Hence we need to avoid that as much as possible. The toplevel function str.strip. Comes to our aid here.

The map can be re-written without using lambda using str.strip as

>>> list(map(str.strip,l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

And now for the times.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(str.strip,l))"
1000000 loops, best of 3: 1.38 usec per loop

Fantastic. You can see the efficiency differences between the two ways. It is nearly 60% faster. Thus the approach without using a lambda is a better choice here.


Case 3 - Following Guidelines, The Regular way

Another important point from What’s New In Python 3.0 is that it advices us to avoid map where possible.

Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

So we can solve this problem without a map by using a regular for loop.

The trivial way of solving (the brute-force) would be:-

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> final_list = []
>>> for i in l:
...     final_list.append(i.strip())
... 
>>> final_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing setup

def f():
    l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
    final_list = []
    for i in l:
         final_list.append(i.strip())
import timeit
print(min(timeit.repeat("f()","from __main__ import f")))

And the result.

1.5322505849981098

As you can see the brute-force is a bit slower here. But it is definitely more readable to a common programmer than a map clause.


Case 4 - List Comprehensions

A list comprehension here is also possible and is the same as in Python2.

>>> [i.strip() for i in l]
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Now for the timings:

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];[i.strip() for i in l]"
1000000 loops, best of 3: 1.28 usec per loop

As you can see the list-comprehension is more effective than map (even that without a lambda). Hence the thumb rule in Python3 is to use a list comprehension instead of map


Case 5 - In-Place mechanisms and Space Efficiency (T-M-T)

A final way is to make the changes in-place within the list itself. This will save a lot of memory space. This can be done using enumerate.

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> for i,s in enumerate(l):
...     l[i] = s.strip()
... 
>>> l
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing result would be 1.4806894720022683. But however this way is space effective.


Conclusion

A comparitive list of timings (Both Python 3.4.3 and Python 3.5.0)

----------------------------------------------------
|Case| method          | Py3.4 |Place| Py3.5 |Place|
|----|-----------------|-------|-----|-------|-----|
| 1  | map with lambda | 2.22u | 5   | 2.85u | 5   |
| 2  | map w/o lambda  | 1.38u | 2   | 2.00u | 2   |
| 3  | brute-force     | 1.53u | 4   | 2.22u | 4   |
| 4  | list comp       | 1.28u | 1   | 1.25u | 1   |
| 5  | in-place        | 1.48u | 3   | 2.14u | 3   |
----------------------------------------------------

Finally note that the list-comprehension is the best way and the map using lambda is the worst. But again --- ONLY IN PYTHON3

Easiest way to ignore blank lines when reading a file in Python

You can use not:

for line in lines:
    if not line:
        continue

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

How to make a radio button look like a toggle button

I know this is an old question, but since I was just looking to do this, I thought I would post what I ended up with. Because I am using Bootstrap, I went with a Bootstrap option.

HTML

<div class="col-xs-12">
    <div class="form-group">
        <asp:HiddenField ID="hidType" runat="server" />
        <div class="btn-group" role="group" aria-label="Selection type" id="divType">
            <button type="button" class="btn btn-default BtnType" data-value="1">Food</button>                        
            <button type="button" class="btn btn-default BtnType" data-value="2">Drink</button>
        </div>
    </div>
</div>

jQuery

$(document).ready(function () {
    $('#divType button').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        $('#<%= hidType.ClientID%>').val($(this).data('value'));
        //alert($(this).data('value'));             
    });
});

I chose to store the value in a hidden field so that it would be easy for me to get the value server-side.

error TS2339: Property 'x' does not exist on type 'Y'

If you want to be able to access images.main then you must define it explicitly:

interface Images {
    main: string;
    [key:string]: string;
}

function getMainImageUrl(images: Images): string {
    return images.main;
}

You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.


Edit

You can have a helper class for map instances, something like:

class Map<T> {
    private items: { [key: string]: T };

    public constructor() {
        this.items = Object.create(null);
    }

    public set(key: string, value: T): void {
        this.items[key] = value;
    }

    public get(key: string): T {
        return this.items[key];
    }

    public remove(key: string): T {
        let value = this.get(key);
        delete this.items[key];
        return value;
    }
}

function getMainImageUrl(images: Map<string>): string {
    return images.get("main");
}

I have something like that implemented, and I find it very useful.

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

XDocument or XmlDocument

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName" syntax makes for pleasurable reading when dealing with namespaces.

One thing worth mentioning for xsl and xpath die hards to note is that it IS possible to still execute arbitrary xpath 1.0 expressions on Linq 2 Xml XNodes by including:

using System.Xml.XPath;

and then we can navigate and project data using xpath via these extension methods:

For instance, given the Xml document:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

How can I Remove .DS_Store files from a Git repository?

I'm a bit late to the party, but I have a good answer. To remove the .DS_Store files, use the following commands from a terminal window, but be very careful deleting files with 'find'. Using a specific name with the -name option is one of the safer ways to use it:

cd directory/above/affected/workareas
find . -name .DS_Store -delete

You can leave off the "-delete" if you want to simply list them before and after. That will reassure you that they're gone.

With regard to the ~/.gitignore_global advice: be careful here. You want to place that nice file into .gitignore within the top level of each workarea and commit it, so that anyone who clones your repo will gain the benefit of its use.

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Best Way to Refresh Adapter/ListView on Android

Perhaps their problem is the moment when the search is made in the database. In his Fragment Override cycles of its Fragment.java to figure out just: try testing with the methods:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_x, container, false); //Your query and ListView code probably will be here
    Log.i("FragmentX", "Step OnCreateView");// Try with it
    return rootView; 
}

Try it similarly put Log.i ... "onStart" and "onResume".

Finally cut the code in "onCreate" e put it in "onStart" for example:

@Override
public void onStart(){
    super.onStart();
    Log.i("FragmentX","Step OnStart");
    dbManager = new DBManager(getContext());
    Cursor cursor = dbManager.getAllNames();
    listView = (ListView)getView().findViewById(R.id.lvNames);
    adapter = new CustomCursorAdapter(getContext(),cursor,0);// your adapter
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
}

How to use QueryPerformanceCounter?

Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks() method to it, in particular, to do exactly what you require).

On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).

Why do we usually use || over |? What is the difference?

|| is the logical or operator while | is the bitwise or operator.

boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;

Jquery UI Datepicker not displaying

I had the same problem using JQuery-UI 1.8.21, and JQuery-UI 1.8.22.

Problem was because I had two DatePicker script, one embedded with jquery-ui-1.8.22.custom.min.js and another one in jquery.ui.datepicker.js (an old version before I upgrade to 1.8.21).

Deleting the duplicate jquery.ui.datepicker.js, resolve problem for both 1.8.21 and 1.8.22.

Omitting the first line from any Linux command output

This is a quick hacky way: ls -lart | grep -v ^total.

Basically, remove any lines that start with "total", which in ls output should only be the first line.

A more general way (for anything):

ls -lart | sed "1 d"

sed "1 d" means only print everything but first line.

How do you declare an interface in C++?

Here is the definition of abstract class in c++ standard

n4687

13.4.2

An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function.

What happened to Lodash _.pluck?

Use _.map instead of _.pluck. In the latest version the _.pluck has been removed.

How schedule build in Jenkins?

In Jenkins , we have the format is as:

Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

read input separated by whitespace(s) or newline...?

#include <iostream>

using namespace std;

string getWord(istream& in) 
{
    int c;

    string word;

    // TODO: remove whitespace from begining of stream ?

    while( !in.eof() ) 
    {

        c = in.get();

        if( c == ' ' || c == '\t' || c == '\n' ) break;

        word += c;
    }

    return word;
}

int main()
{
    string word;

    do {

        word = getWord(cin);

        cout << "[" << word << "]";

    } while( word != "#");

    return 0;
}

What's the right way to pass form element state to sibling/parent elements?

With React >= 16.3 you can use ref and forwardRef, to gain access to child's DOM from its parent. Don't use old way of refs anymore.
Here is the example using your case :

import React, { Component } from 'react';

export default class P extends React.Component {
   constructor (props) {
      super(props)
      this.state = {data: 'test' }
      this.onUpdate = this.onUpdate.bind(this)
      this.ref = React.createRef();
   }

   onUpdate(data) {
      this.setState({data : this.ref.current.value}) 
   }

   render () {
      return (
        <div>
           <C1 ref={this.ref} onUpdate={this.onUpdate}/>
           <C2 data={this.state.data}/>
        </div>
      )
   }
}

const C1 = React.forwardRef((props, ref) => (
    <div>
        <input type='text' ref={ref} onChange={props.onUpdate} />
    </div>
));

class C2 extends React.Component {
    render () {
       return <div>C2 reacts : {this.props.data}</div>
    }
}

See Refs and ForwardRef for detailed info about refs and forwardRef.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

I was successfully available to get Application User By Following Piece of Code

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = manager.FindById(User.Identity.GetUserId());
            ApplicationUser EmpUser = user;

java.util.regex - importance of Pattern.compile()?

The compile() method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int) to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher() method, and the only way to get ahold of the Pattern object is through the compile() method. Then there's the find() method which, unlike matches(), is not duplicated in the String or Pattern classes.

The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches() method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:

for (String s : myStringList) {
    if ( s.matches("\\d+") ) {
        doSomething();
    }
}

...is exactly equivalent to this:

for (String s : myStringList) {
    if ( Pattern.compile("\\d+").matcher(s).matches() ) {
        doSomething();
    }
}

Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
    if ( m.reset(s).matches() ) {
        doSomething();
    }
}

If you're familiar with .NET regexes, you may be wondering if Java's compile() method is related to .NET's RegexOptions.Compiled modifier; the answer is no. Java's Pattern.compile() method is merely equivalent to .NET's Regex constructor. When you specify the Compiled option:

Regex r = new Regex(@"\d+", RegexOptions.Compiled); 

...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String) and one you create explicitly with Pattern#compile(String).

(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches(), not when you call a Regex constructor directly. ref)

sudo: npm: command not found

The npm file should be in /usr/local/bin/npm. If it's not there, install node.js again with the package on their website. This worked in my case.

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );

Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

Listview Scroll to the end of the list after updating the list

To get this in a ListFragment:

getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL); 
getListView().setStackFromBottom(true);`

Added this answer because if someone do a google search for same problem with ListFragment he just finds this..

Regards

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

Convert a string representation of a hex dump to a byte array using Java?

Here is a method that actually works (based on several previous semi-correct answers):

private static byte[] fromHexString(final String encoded) {
    if ((encoded.length() % 2) != 0)
        throw new IllegalArgumentException("Input string must contain an even number of characters");

    final byte result[] = new byte[encoded.length()/2];
    final char enc[] = encoded.toCharArray();
    for (int i = 0; i < enc.length; i += 2) {
        StringBuilder curr = new StringBuilder(2);
        curr.append(enc[i]).append(enc[i + 1]);
        result[i/2] = (byte) Integer.parseInt(curr.toString(), 16);
    }
    return result;
}

The only possible issue that I can see is if the input string is extremely long; calling toCharArray() makes a copy of the string's internal array.

EDIT: Oh, and by the way, bytes are signed in Java, so your input string converts to [0, -96, -65] instead of [0, 160, 191]. But you probably knew that already.

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

What's the difference between lists and tuples?

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.

So if you're going to need to change the values use a List.

Benefits to tuples:

  1. Slight performance improvement.
  2. As a tuple is immutable it can be used as a key in a dictionary.
  3. If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.

Print a list in reverse order with range()?

Readibility aside, reversed(range(n)) seems to be faster than range(n)[::-1].

$ python -m timeit "reversed(range(1000000000))"
1000000 loops, best of 3: 0.598 usec per loop
$ python -m timeit "range(1000000000)[::-1]"
1000000 loops, best of 3: 0.945 usec per loop

Just if anyone was wondering :)

How can I selectively escape percent (%) in Python strings?

You can't selectively escape %, as % always has a special meaning depending on the following character.

In the documentation of Python, at the bottem of the second table in that section, it states:

'%'        No argument is converted, results in a '%' character in the result.

Therefore you should use:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(please note the expicit change to tuple as argument to %)

Without knowing about the above, I would have done:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

with the knowledge you obviously already had.

How do I get a TextBox to only accept numeric input in WPF?

Here I have a simple solution inspired by Ray's answer. This should be sufficient to identify any form of number.

This solution can also be easily modified if you want only positive numbers, integer values or values accurate to a maximum number of decimal places, etc.


As suggested in Ray's answer, you need to first add a PreviewTextInput event:

<TextBox PreviewTextInput="TextBox_OnPreviewTextInput"/>

Then put the following in the code behind:

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    // Use SelectionStart property to find the caret position.
    // Insert the previewed text into the existing text in the textbox.
    var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

    double val;
    // If parsing is successful, set Handled to false
    e.Handled = !double.TryParse(fullText, out val);
}

To invalid whitespace, we can add NumberStyles:

using System.Globalization;

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    // Use SelectionStart property to find the caret position.
    // Insert the previewed text into the existing text in the textbox.
    var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

    double val;
    // If parsing is successful, set Handled to false
    e.Handled = !double.TryParse(fullText, 
                                 NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, 
                                 CultureInfo.InvariantCulture,
                                 out val);
}

Explode string by one or more spaces or tabs

I think you want preg_split:

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);

How to convert ASCII code (0-255) to its corresponding character?

String.valueOf(Character.toChars(int))

Assuming the integer is, as you say, between 0 and 255, you'll get an array with a single character back from Character.toChars, which will become a single-character string when passed to String.valueOf.

Using Character.toChars is preferable to methods involving a cast from int to char (i.e. (char) i) for a number of reasons, including that Character.toChars will throw an IllegalArgumentException if you fail to properly validate the integer while the cast will swallow the error (per the narrowing primitive conversions specification), potentially giving an output other than what you intended.

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

Regex to match 2 digits, optional decimal, two digits

(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])

Matches:

  • Your examples
  • 33.

Does not match:

  • 333.33
  • 33.333

How do I run a node.js app as a background service?

This might not be the accepted way, but I do it with screen, especially while in development because I can bring it back up and fool with it if necessary.

screen
node myserver.js
>>CTRL-A then hit D

The screen will detach and survive you logging off. Then you can get it back back doing screen -r. Hit up the screen manual for more details. You can name the screens and whatnot if you like.

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

Java: Reading a file into an array

import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

Vertically align text next to an image?

You probably want this:

<div>
   <img style="width:30px; height:30px;">
   <span style="vertical-align:50%; line-height:30px;">Didn't work.</span>
</div>

As others have suggested, try vertical-align on the image:

<div>
   <img style="width:30px; height:30px; vertical-align:middle;">
   <span>Didn't work.</span>
</div>

CSS isn't annoying. You just don't read the documentation. ;P

How to combine date from one field with time from another field - MS SQL Server

This is an alternative solution without any char conversions:

DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))

You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

Shortest way to check for null and assign another value if not

I use extention method SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

string a = null;
"A".SC(ref a);

How can I have a newline in a string in sh?

I wasn't really happy with any of the options here. This is what worked for me.

str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")

How do you split a list into evenly sized chunks?

def chunk(lst):
    out = []
    for x in xrange(2, len(lst) + 1):
        if not len(lst) % x:
            factor = len(lst) / x
            break
    while lst:
        out.append([lst.pop(0) for x in xrange(factor)])
    return out

Python: Continuing to next iteration in outer loop

I think one of the easiest ways to achieve this is to replace "continue" with "break" statement,i.e.

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

For example, here is the easy code to see how exactly it goes on:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

This is a sledgehammer approach to replacing raw UNICODE with HTML. I haven't seen any other place to put this solution, but I assume others have had this problem.

Apply this str_replace function to the RAW JSON, before doing anything else.

function unicode2html($str){
    $i=65535;
    while($i>0){
        $hex=dechex($i);
        $str=str_replace("\u$hex","&#$i;",$str);
        $i--;
     }
     return $str;
}

This won't take as long as you think, and this will replace ANY unicode with HTML.

Of course this can be reduced if you know the unicode types that are being returned in the JSON.

For example my code was getting lots of arrows and dingbat unicode. These are between 8448 an 11263. So my production code looks like:

$i=11263;
while($i>08448){
    ...etc...

You can look up the blocks of Unicode by type here: http://unicode-table.com/en/ If you know you're translating Arabic or Telegu or whatever, you can just replace those codes, not all 65,000.

You could apply this same sledgehammer to simple encoding:

 $str=str_replace("\u$hex",chr($i),$str);

Changing the space between each item in Bootstrap navbar

With regard to bootstrap, the correct answer is using spacing utilities as mentioned by loopasam in a previous comment. Following is an example of using padding for both left and right.

<a href="#" class="nav-item nav-link px-3">Blog</a>

Redirect all to index.php using htaccess

Silly answer but if you can't figure out why its not redirecting check that the following is enabled for the web folder ..

AllowOverride All

This will enable you to run htaccess which must be running! (there are alternatives but not on will cause problems https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride)

cannot connect to pc-name\SQLEXPRESS

Use (LocalDB)\MSSQLLocalDB as the server name

How to implement a Navbar Dropdown Hover in Bootstrap v4?

I use bootstrap 4.0.0 since we want to simulate .show to hover event, it simply easy. just add all styles in .dropdown.show .dropdown-menu to the :hover. like this:

.dropdown:hover>.dropdown-menu {
  opacity: 1;
  visibility: visible;
  transform: translate3d(0px, 0px, 0px);
}

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

Rename column SQL Server 2008

Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio. Here are a few quick ways using the GUI:

First Way

Slow double-click on the column. The column name will become an editable text box.


Second Way

Right click on column and choose Rename from the context menu.

For example:

To Rename column name


Third Way

This way is preferable for when you need to rename multiple columns in one go.

  1. Right-click on the table that contains the column that needs renaming.
  2. Click Design.
  3. In the table design panel, click and edit the textbox of the column name you want to alter.

For example: MSSMS Table Design Example

NOTE: I know OP specifically asked for SQL solution, thought this might help others :)

Submitting HTML form using Jquery AJAX

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

_x000D_
_x000D_
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>
_x000D_
_x000D_
_x000D_


Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

How to uninstall pip on OSX?

In my case I ran the following command and it worked (not that I was expecting it to):

sudo pip uninstall pip

Which resulted in:

Uninstalling pip-6.1.1:
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
  <and all the other stuff>
  ...

  /usr/local/bin/pip
  /usr/local/bin/pip2
  /usr/local/bin/pip2.7
Proceed (y/n)? y
  Successfully uninstalled pip-6.1.1

Encode a FileStream to base64 with c#

You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?

Or I think it should be also possible to use the .ToString() method and encode this.

Is there a command to undo git init?

remove the .git folder in your project root folder

if you installed submodules and want to remove their git, also remove .git from submodules folders

Route.get() requires callback functions but got a "object Undefined"

This thing also happened with my code, but somehow I solved my problem. I checked my routes folder (where my all endpoints are their). I would recommend you check your routes folder file and check whether you forgot to add your particular router link.

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Java equivalent of unsigned long long?

Depending on the operations you intend to perform, the outcome is much the same, signed or unsigned. However, unless you are using trivial operations you will end up using BigInteger.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

The best option is to use the original LESS version of bootstrap (get it from github).

Open variables.less and look for // Media queries breakpoints

Find this code and change the breakpoint value:

// Large screen / wide desktop
@screen-lg:                  1200px; // change this
@screen-lg-desktop:          @screen-lg;

Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container

How to use wait and notify in Java without IllegalMonitorStateException?

To be able to call notify() you need to synchronize on the same object.

synchronized (someObject) {
    someObject.wait();
}

/* different thread / object */
synchronized (someObject) {
    someObject.notify();
}

Enable remote connections for SQL Server Express 2012

Well, glad I asked. The solution I finally discovered was here:

How do I configure SQL Server Express to allow remote tcp/ip connections on port 1433?

  1. Run SQL Server Configuration Manager.
  2. Go to SQL Server Network Configuration > Protocols for SQLEXPRESS.
  3. Make sure TCP/IP is enabled.

So far, so good, and entirely expected. But then:

  1. Right-click on TCP/IP and select Properties.
  2. Verify that, under IP2, the IP Address is set to the computer's IP address on the local subnet.
  3. Scroll down to IPAll.
  4. Make sure that TCP Dynamic Ports is blank. (Mine was set to some 5-digit port number.)
  5. Make sure that TCP Port is set to 1433. (Mine was blank.)

(Also, if you follow these steps, it's not necessary to enable SQL Server Browser, and you only need to allow port 1433, not 1434.)

These extra five steps are something I can't remember ever having had to do in a previous version of SQL Server, Express or otherwise. They appear to have been necessary because I'm using a named instance (myservername\SQLEXPRESS) on the server instead of a default instance. See here:

Configure a Server to Listen on a Specific TCP Port (SQL Server Configuration Manager)

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

Choose newline character in Notepad++

For a new document: Settings -> Preferences -> New Document/Default Directory -> New Document -> Format -> Windows/Mac/Unix

And for an already-open document: Edit -> EOL Conversion

Increasing Google Chrome's max-connections-per-server limit to more than 6

I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.

However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.

Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).

how to add background image to activity?

Nowadays we have to use match_parent :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="@drawable/background">
</RelativeLayout>

enter image description here

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

How do I determine scrollHeight?

You can also use:

$('#test').context.scrollHeight

Copying one structure to another

  1. You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)

  2. To move (to & from) a single string field you must use strncpy and a transient string buffer '\0' terminating. Somewhere you must remember the length of the record string field.

  3. To move other fields you can use the dot notation, ex.: NodeB->one=intvar; floatvar2=(NodeA->insidebisnode_subvar).myfl;

    struct mynode {
        int one;
        int two;
        char txt3[3];
        struct{char txt2[6];}txt2fi;
        struct insidenode{
            char txt[8];
            long int myl;
            void * mypointer;
            size_t myst;
            long long myll;
             } insidenode_subvar;
        struct insidebisnode{
            float myfl;
             } insidebisnode_subvar;
    } mynode_subvar;
    
    typedef struct mynode* Node;
    
    ...(main)
    Node NodeA=malloc...
    Node NodeB=malloc...
    
  4. You can embed each string into a structs that fit it, to evade point-2 and behave like Cobol: NodeB->txt2fi=NodeA->txt2fi ...but you will still need of a transient string plus one strncpy as mentioned at point-2 for scanf, printf otherwise an operator longer input (shorter), would have not be truncated (by spaces padded).

  5. (NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer will create a pointer alias.
  6. NodeB.txt3=NodeA.txt3 causes the compiler to reject: error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
  7. point-4 works only because NodeB->txt2fi & NodeA->txt2fi belong to the same typedef !!

    A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!

jQuery multiselect drop down menu

Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)

Obligatory screenshots below.

Select2: Select2

Selectize: Selectize


Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.

Attached is a screenshot of how the multi-select functionality looks in Chosen.

Chosen library

AngularJS $location not changing the path

setTimeout(function() { $location.path("/abc"); },0);

it should solve your problem.

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

Fatal error: Call to undefined function socket_create()

Follow these steps if you're on openSuse or SUSE.

Install php7 if it's not already installed.

zypper in php7

If you have php7 installed, update it with:

zypper update php7

Install php7-sockets

zypper in php7-sockets

JQuery datepicker not working

Datepicker is not part of jQuery. You have to get jQuery UI to use the datepicker.

position fixed header in html

set #container div top to zero

#container{ 


 top: 0;



}

Excel 2013 VBA Clear All Filters macro

I usually use this code

Sub AutoFilter_Remove()
    Sheet1.AutoFilterMode = False  'Change Sheet1 to the relevant sheet
                                   'Alternatively: Worksheets("[Your Sheet Name]").AutoFilterMode = False
End Sub

How do I set adaptive multiline UILabel text?

With Graphical User Interface (GUI) in Xcode, you can do the following:

  • Go to "Attribute Inspector" and set Lines value to 0. By default, it is set to 1.
  • The Label text can be written in multi-line by hitting option + return.

enter image description here

  • Now, go to "Size Inspector" and set the width, height, X & Y position of the Label.

enter image description here

That's all.

C++: constructor initializer for arrays

You can use C++0x auto keyword together with template specialization on for example a function named boost::make_array() (similar to make_pair()). For the case of where N is either 1 or 2 arguments we can then write variant A as

namespace boost
{
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    return boost::array<T,2> ({{ a }});
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    return boost::array<T,2> ({{ a, b }});
}
}

and variant B as

namespace boost {
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    boost::array<T,1> x;
    x[0] = a;
    return x;
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    boost::array<T,2> x;
    x[0] = a;
    x[1] = b;
    return x;
}
}

GCC-4.6 with -std=gnu++0x and -O3 generates the exact same binary code for

auto x = boost::make_array(1,2);

using both A and B as it does for

boost::array<int, 2> x = {{1,2}};

For user defined types (UDT), though, variant B results in an extra copy constructor, which usually slow things down, and should therefore be avoided.

Note that boost::make_array errors when calling it with explicit char array literals as in the following case

auto x = boost::make_array("a","b");

I believe this is a good thing as const char* literals can be deceptive in their use.

Variadic templates, available in GCC since 4.5, can further be used reduce all template specialization boiler-plate code for each N into a single template definition of boost::make_array() defined as

/*! Construct Array from @p a, @p b. */
template <typename T, typename ... R>
boost::array<T,1+sizeof...(R)> make_array(T a, const R & ... b)
{
    return boost::array<T,1+sizeof...(R)>({{ a, b... }});
}

This works pretty much as we expect. The first argument determines boost::array template argument T and all other arguments gets converted into T. For some cases this may undesirable, but I'm not sure how if this is possible to specify using variadic templates.

Perhaps boost::make_array() should go into the Boost Libraries?

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

SQL query to select dates between two dates

Really all sql dates should be in yyyy-MM-dd format for the most accurate results.

Connect with SSH through a proxy

Try -o "ProxyCommand=nc --proxy HOST:PORT %h %p" for command in question. It worked on OEL6 but need to modify as mentioned for OEL7.

jQuery Validate Plugin - Trigger validation of single field

Use Validator.element():

Validates a single element, returns true if it is valid, false otherwise.

Here is the example shown in the API:

var validator = $( "#myform" ).validate();
validator.element( "#myselect" );

.valid() validates the entire form, as others have pointed out. The API says:

Checks whether the selected form is valid or whether all selected elements are valid.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

How to write an XPath query to match two attributes?

or //div[@id='id-74385'][@class='guest clearfix']

How to add image for button in android?

   <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="News Feed"
        android:icon="@drawable/newsfeed" />

newsfeed is image in the drawable folder

What is simplest way to read a file into String?

I discovered that the accepted answer actually doesn't always work, because \\Z may occur in the file. Another problem is that if you don't have the correct charset a whole bunch of unexpected things may happen which may cause the scanner to read only a part of the file.

The solution is to use a delimiter which you are certain will never occur in the file. However, this is theoretically impossible. What we CAN do, is use a delimiter that has such a small chance to occur in the file that it is negligible: such a delimiter is a UUID, which is natively supported in Java.

String content = new Scanner(file, "UTF-8")
    .useDelimiter(UUID.randomUUID().toString()).next();

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

How do I set the background color of my main screen in Flutter?

On the basic example of Flutter you can set with backgroundColor: Colors.X of Scaffold

  @override
 Widget build(BuildContext context) {
   // This method is rerun every time setState is called, for instance as done
  // by the _incrementCounter method above.
   //
  // The Flutter framework has been optimized to make rerunning build methods
   // fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
  backgroundColor: Colors.blue,
  body: Center(
    // Center is a layout widget. It takes a single child and positions it
    // in the middle of the parent.
    child: Column(
      // Column is also layout widget. It takes a list of children and
      // arranges them vertically. By default, it sizes itself to fit its
      // children horizontally, and tries to be as tall as its parent.
      //
      // Invoke "debug painting" (press "p" in the console, choose the
      // "Toggle Debug Paint" action from the Flutter Inspector in Android
      // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
      // to see the wireframe for each widget.
      //
      // Column has various properties to control how it sizes itself and
      // how it positions its children. Here we use mainAxisAlignment to
      // center the children vertically; the main axis here is the vertical
      // axis because Columns are vertical (the cross axis would be
      // horizontal).
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          'You have pushed the button this many times:',
        ),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.display1,
        ),
      ],
    ),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add_circle),
  ), // This trailing comma makes auto-formatting nicer for build methods.
);
}

exclude @Component from @ComponentScan

Another approach is to use new conditional annotations. Since plain Spring 4 you can use @Conditional annotation:

@Component("foo")
@Conditional(FooCondition.class)
class Foo {
    ...
}

and define conditional logic for registering Foo component:

public class FooCondition implements Condition{
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // return [your conditional logic]
    }     
}

Conditional logic can be based on context, because you have access to bean factory. For Example when "Bar" component is not registered as bean:

    return !context.getBeanFactory().containsBean(Bar.class.getSimpleName());

With Spring Boot (should be used for EVERY new Spring project), you can use these conditional annotations:

  • @ConditionalOnBean
  • @ConditionalOnClass
  • @ConditionalOnExpression
  • @ConditionalOnJava
  • @ConditionalOnMissingBean
  • @ConditionalOnMissingClass
  • @ConditionalOnNotWebApplication
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication

You can avoid Condition class creation this way. Refer to Spring Boot docs for more detail.

Proper way to empty a C-String

I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

Converting dictionary to JSON

json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is the code sample which might help you understand it more:

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

How to fix HTTP 404 on Github Pages?

I faced this problem (404) too and the root cause was my file was named INDEX.md. I was developing on Windows and my local Jekyll site worked (since Windows treats file names case insensitive by default). When pushed to Github, it didn't work. Once I renamed the INDEX.md to index.md, things worked well.

How to get annotations of a member variable?

Or you could try this

try {
    BeanInfo bi = Introspector.getBeanInfo(User.getClass());
    PropertyDescriptor[] properties = bi.getPropertyDescriptors();
    for(PropertyDescriptor property : properties) {
        //One way
        for(Annotation annotation : property.getAnnotations()){
            if(annotation instanceof Column) {
                String string = annotation.name();
            }
        }
        //Other way
        Annotation annotation = property.getAnnotation(Column.class);
        String string = annotation.name();
    }
}catch (IntrospectonException ie) {
    ie.printStackTrace();
}

Hope this will help.