Programs & Examples On #Windowless

Max length UITextField

I do it like this:

func checkMaxLength(textField: UITextField!, maxLength: Int) {
    if (countElements(textField.text!) > maxLength) {

The code works for me. But I work with storyboard. In Storyboard I add an action for the text field in the view controller on editing changed.

phpmailer - The following SMTP Error: Data not accepted

I was experiencing this same problem. In my instance the send mail was timing out because my Exchange server was relaying email to a server on the internet. That server had exceeded it's bandwidth quota. Apparently php mailer has some built in timeout and it wasn't long enough to see the actual message.

UTF-8 problems while reading CSV file with fgetcsv

Try this:

$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        echo "</tr><tr>";

Why doesn't git recognize that my file has been changed, therefore git add not working

I had a similar issue when I created a patch file in server with vi editor. It seems the issue was with spacing. When I pushed the patch from local, deployment was proper.

How to use auto-layout to move other views when a view is hidden?

Try this,I have implemented below code ,

I have one View on ViewController in that added other three views, When any view is hidden other two view will move,Follow below steps. ,

1.ViewController.h File

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIView *viewOne;
@property (strong, nonatomic) IBOutlet UIView *viewTwo;
@property (strong, nonatomic) IBOutlet UIView *viewThree;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewOneWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewTwoWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewThreeWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewBottomWidth;


 #import "ViewController.h"
 @interface ViewController ()
  CGFloat viewOneWidthConstant;
  CGFloat viewTwoWidthConstant;
  CGFloat viewThreeWidthConstant;
  CGFloat viewBottomWidthConstant;

@implementation ViewController
@synthesize viewOne, viewTwo, viewThree;

- (void)viewDidLoad {
  [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a 

   0  0   0
   0  0   1
   0  1   0
   0  1   1
   1  0   0
   1  0   1
   1  1   0
   1  1   1

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:YES];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:YES];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:YES];
  //    [viewThree setHidden:YES];

  //    [viewOne setHidden:YES];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:YES];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:YES];

 //    [viewOne setHidden:YES];
 //    [viewTwo setHidden:YES];
 //    [viewThree setHidden:NO];

//    [viewOne setHidden:YES];
//    [viewTwo setHidden:YES];
//    [viewThree setHidden:YES];

 [self hideShowBottomBar];

- (void)hideShowBottomBar
  BOOL isOne = !viewOne.isHidden;
  BOOL isTwo = !viewTwo.isHidden;
  BOOL isThree = !viewThree.isHidden;

  viewOneWidthConstant = _viewOneWidth.constant;
  viewTwoWidthConstant = _viewTwoWidth.constant;
  viewThreeWidthConstant = _viewThreeWidth.constant;
  viewBottomWidthConstant = _viewBottomWidth.constant;

   if (isOne && isTwo && isThree) {
    // 0    0   0
    _viewOneWidth.constant = viewBottomWidthConstant / 3;
    _viewTwoWidth.constant = viewBottomWidthConstant / 3;
    _viewThreeWidth.constant = viewBottomWidthConstant / 3;
    else if (isOne && isTwo && !isThree) {
     // 0    0   1
    _viewOneWidth.constant = viewBottomWidthConstant / 2;
    _viewTwoWidth.constant = viewBottomWidthConstant / 2;
    _viewThreeWidth.constant = 0;
   else if (isOne && !isTwo && isThree) {
    // 0    1   0
    _viewOneWidth.constant = viewBottomWidthConstant / 2;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = viewBottomWidthConstant / 2;
    else if (isOne && !isTwo && !isThree) {
    // 0    1   1
    _viewOneWidth.constant = viewBottomWidthConstant;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = 0;
   else if (!isOne && isTwo && isThree) {
    // 1    0   0
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = viewBottomWidthConstant / 2;
    _viewThreeWidth.constant = viewBottomWidthConstant / 2;
   else if (!isOne && isTwo && !isThree) {
    // 1    0   1
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = viewBottomWidthConstant;
    _viewThreeWidth.constant = 0;
   else if (!isOne && !isTwo && isThree) {
    // 1    1   0
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = viewBottomWidthConstant;
   else if (isOne && isTwo && isThree) {
    // 1    1   1
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = 0;

 - (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.

enter image description here enter image description here enter image description here

Hope So this logic will help some one.

Using "margin: 0 auto;" in Internet Explorer 8

shouldn't the button be 100% width if it's "display: block"

No. That just means it's the only thing in the space vertically (assuming you aren't using another trick to force something else there as well). It doesn't mean it has to fill up the width of that space.

I think your problem in this instance is that the input is not natively a block element. Try nesting it inside another div and set the margin on that. But I don't have an IE8 browser to test this with at the moment, so it's just a guess.

bootstrap 3 navbar collapse button not working

I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.

Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.

Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.

Additional info:

Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.

If you're pretty sure your code is correct, give this a try.

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command can be used.

For example:

# Opens a new tab

# Switch to the newly opened tab

# Navigate to new URL in new tab
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab

# Close original tab

# Switch back to newly opened tab, which is now in position 0

Or close the newly opened tab

# Close current tab

# Switch back to original tab

Hope this helps.

Update values from one column in same table to another in SQL Server

Your select statement was before the update statement see Updated fiddle

Cut Java String at a number of character

String strOut = str.substring(0, 8) + "...";

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

I'm not sure why the simplest way has been ignored/omitted in the answers above:

SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02

SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08

I prefer the second one because whichever language you speak, you will understand what date it is!

Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.

How to change colors of a Drawable in Android?

view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY); 

Thanks to @sabadow

How to check if a process is in hang state (Linux)

Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.

InputStream from a URL


final InputStream is = new URL("").openStream();

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])


(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

Update cordova plugins in one command

I got tired of manually checking for plugin updates so created a tool to do it for me:

Install it globally:

$ npm install -g cordova-check-plugins

Then run from the root of your Cordova project. You can optionally update outdated plugins interactively or automatically, e.g.

$ cordova-check-plugins --update=auto

CLI screenshot

How to choose the right bean scope?


It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:

Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

What languages are Windows, Mac OS X and Linux written in?

You're right MacOSX has Objective-C in the core.

Windows C++

Linux C

About the scripting languages, no, they pretty much high level.

Passing additional variables from command line to make

If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards

example :

make unittest=*

I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run

SELECT INTO Variable in MySQL DECLARE causes syntax error?

You can also use SET instead of DECLARE

SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);

SELECT myvar;

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

Python foreach equivalent

While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:

for key, value in Dictionary.items():
    print(key, value)

Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.

How do I check for vowels in JavaScript?

I created a simplified version using Array.prototype.includes(). My technique is similar to @Kunle Babatunde.

const isVowel = (char) => ["a", "e", "i", "o", "u"].includes(char);_x000D_
console.log(isVowel("o"), isVowel("s"));

How do I extend a class with c# extension methods?

We have improved our answer with detail explanation.Now it's more easy to understand about extension method

Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.

We can extend our custom classes ,.net framework classes etc.

Extension method is actually a special kind of static method that is defined in the static class.

As DateTime class is already taken above and hence we have not taken this class for the explanation.

Below is the example

//This is a existing Calculator class which have only one method(Add)

public class Calculator 
    public double Add(double num1, double num2)
        return num1 + num2;


// Below is the extension class which have one extension method.  
public static class Extension
    // It is extension method and it's first parameter is a calculator class.It's behavior is going to extend. 
    public static double Division(this Calculator cal, double num1,double num2){
       return num1 / num2;

// We have tested the extension method below.        
class Program
    static void Main(string[] args)
        Calculator cal = new Calculator();
        double add=cal.Add(10, 10);
        // It is a extension method in Calculator class.
        double add=cal.Division(100, 10)


Error:Conflict with dependency ''

In project ':app' you can add the following to your app/build.gradle file :

android {
 configurations.all {
    resolutionStrategy.force ''

ASP.NET Web API : Correct way to return a 401/unauthorised response

In .Net Core You can use

return new ForbidResult();

instead of

return Unauthorized();

which has the advantage to redirecting to the default unauthorized page (Account/AccessDenied) rather than giving a straight 401

to change the default location modify your startup.cs

services.AddAuthentication(options =>...)
            .AddOpenIdConnect(options =>...)
            .AddCookie(options =>
                options.AccessDeniedPath = "/path/unauthorized";


Make body have 100% of the browser height

A quick update

html, body{

A better solution with today's CSS

html, body{ 
  min-height: 100vh;
  overflow: auto;

SQL query: Delete all records from the table except latest N?

If you need to delete the records based on some other column as well, then here is a solution:

FROM articles
    (SELECT id
       (SELECT id
        FROM articles
        WHERE user_id = :userId
        ORDER BY created_at DESC LIMIT 500, 10000000) abc)
  AND user_id = :userId

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).


var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\";cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
    divMapLoaded = true;

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

T-SQL: Opposite to string concatenation - how to split string into multiple records

There are a wide varieties of solutions to this problem documented here, including this little gem:

CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.


C++ catching all exceptions

Be aware

// ...
} catch (...) {
// ...

catches only language-level exceptions, other low-level exceptions/errors like Access Violation and Segmentation Fault wont be caught.

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

C# How do I click a button by hitting Enter whilst textbox has focus?

The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });

If this isn't an option, you can look at the KeyDown event etc, but that is more work...

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
    Application.Run(new Form { Controls = { tb, btn } });

How to wait for a number of threads to complete?

Consider using java.util.concurrent.CountDownLatch. Examples in javadocs

Git: "please tell me who you are" error

IMHO, the proper way to resolve this error is to configure your global git config file.

To do that run the following command: git config --global -e

An editor will appear where you can insert your default git configurations.

Here're are a few:

    name = your_username
    email = [email protected] 
    # BASIC
    st = status
    ci = commit
    br = branch
    co = checkout
    df = diff

For more details, see Customizing Git - Git Configuration

When you see a command like, git config ...

$ git config --global core.whitespace \

... you can put that into your global git config file as:

   whitespace = space-before-tab,-indent-with-non-tab,trailing-space

For one off configurations, you can use something like git config --global 'your_username'

If you don't set your git configurations globally, you'll need to do so for each and every git repo you work with locally.

The and settings tell git who you are, so subsequent git commit commands will not complain, *** Please tell me who you are.

Many times, the commands git suggests you run are not what you should run. This time, the suggested commands are not bad:

$ git commit -m 'first commit'

*** Please tell me who you are.


  git config --global "[email protected]"
  git config --global "Your Name"

Tip: Until I got very familiar with git, making a backup of my project file--before running the suggested git commands and exploring things I thought would work--saved my bacon on more than a few occasions.

How to import data from text file to mysql database

Walkthrough on using MySQL's LOAD DATA command:

  1. Create your table:

    CREATE TABLE foo(myid INT, mymessage VARCHAR(255), mydecimal DECIMAL(8,4));
  2. Create your tab delimited file (note there are tabs between the columns):

    1   Heart disease kills     1.2
    2   one out of every two    2.3
    3   people in America.      4.5
  3. Use the load data command:

    LOAD DATA LOCAL INFILE '/tmp/foo.txt' 

    If you get a warning that this command can't be run, then you have to enable the --local-infile=1 parameter described here: How can I correct MySQL Load Error

  4. The rows get inserted:

    Query OK, 3 rows affected (0.00 sec)
    Records: 3  Deleted: 0  Skipped: 0  Warnings: 0
  5. Check if it worked:

    mysql> select * from foo;
    | myid | mymessage            | mydecimal |
    |    1 | Heart disease kills  |    1.2000 |
    |    2 | one out of every two |    2.3000 |
    |    3 | people in America.   |    4.5000 |
    3 rows in set (0.00 sec)

How to specify which columns to load your text file columns into:

Like this:

(@col1,@col2,@col3) set myid=@col1,mydecimal=@col3;

The file contents get put into variables @col1, @col2, @col3. myid gets column 1, and mydecimal gets column 3. If this were run, it would omit the second row:

mysql> select * from foo;
| myid | mymessage | mydecimal |
|    1 | NULL      |    1.2000 |
|    2 | NULL      |    2.3000 |
|    3 | NULL      |    4.5000 |
3 rows in set (0.00 sec)

The Eclipse executable launcher was unable to locate its companion launcher jar windows

Edit the eclipse.ini file and remove these two lines:


Switching between GCC and Clang/LLVM using CMake

You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g

 cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..

and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

How to Batch Rename Files in a macOS Terminal?

To rename files, you can use the rename utility:

brew install rename

For example, to change a search string in all filenames in current directory:

rename -nvs searchword replaceword *

Remove the 'n' parameter to apply the changes.

More info: man rename

Parse error: Syntax error, unexpected end of file in my PHP code

Just go to php.ini then find short_open_tag= Off set to short_open_tag= On

How to activate JMX on my JVM for access with jconsole?

The relevant documentation can be found here:

Start your program with following parameters:

For instance like this:

java \ \ \ \ \
  -jar Notepad.jar is not necessarily required but without it, it doesn't work on Ubuntu. The error would be something like this:

01 Oct 2008 2:16:22 PM sun.rmi.transport. customer .TCPTransport$AcceptLoop executeAcceptLoop
WARNING: RMI TCP Accept-0: accept loop for ServerSocket[addr=,port=0,localport=37278] throws The server sockets created using the LocalRMIServerSocketFactory only accept connections from clients running on the host where the RMI remote objects have been exported.
    at sun.rmi.transport. customer .TCPTransport$AcceptLoop.executeAcceptLoop(
    at sun.rmi.transport. customer .TCPTransport$


Also be careful with which makes access available for anyone, but if you only use it to track the JVM on your local machine it doesn't matter.


In some cases I was not able to reach the server. This was then fixed if I set this parameter as well: -Djava.rmi.server.hostname=

Copy/Paste from Excel to a web page

On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.

The right way (that doesn't get tripped up by delimiter issues) is to parse the HTML. is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read


hexadecimal string to byte array in python

There is a built-in function in bytearray that does what you intend.

bytearray.fromhex("de ad be ef 00")

It returns a bytearray and it reads hex strings with or without space separator.

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

-webkit-transform: translateZ(0);

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I encountered the exact problem running on docker container (in build environment). After ssh into the container, I tried running the test manually and still encountered

(unknown error: DevToolsActivePort file doesn't exist)
     (The process started from chrome location /usr/bin/google-chrome-stable is 
      no longer running, so ChromeDriver is assuming that Chrome has crashed.)

When I tried running chrome locally /usr/bin/google-chrome-stable, error message

Running as root without --no-sandbox is not supported

I checked my ChromeOptions and it was missing --no-sandbox, which is why it couldn't spawn chrome.

capabilities =
  chromeOptions: { args: %w(headless --no-sandbox disable-gpu window-size=1920,1080) }


I would define a function:

delimiter $$
return if(@fakeId, @fakeId:=@fakeId+1, @fakeId:=1);

then I could do:

select getFakeId() as id, t.* from table t, (select @fakeId:=0) as t2;

Now you don't have a subquery, which you can't have in views.

Getting date format m-d-Y H:i:s.u from milliseconds

If you want to format a date like JavaScript's (new Date()).toISOString() for some reason, this is how you can do it in PHP:

$now = microtime(true);
gmdate('Y-m-d\TH:i:s', $now).sprintf('.%03dZ',round(($now-floor($now))*1000));

Sample output:


Just to prove that subtracting off the whole number doesn't reduce the accuracy of the decimal portion:

>>> number_format(123.01234567890123456789,25)
=> "123.0123456789012408307826263"
>>> number_format(123.01234567890123456789-123,25)
=> "0.0123456789012408307826263"

PHP did round the decimal places, but it rounded them the same way in both cases.

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

Javascript Iframe innerHTML

Don't forget that you can not cross domains because of security.

So if this is the case, you should use JSON.

Socket accept - "Too many open files"

There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.

You can check the following:

cat /proc/sys/fs/file-max

That will give you the system wide limits of file descriptors.

On the shell level, this will tell you your personal limit:

ulimit -n

This can be changed in /etc/security/limits.conf - it's the nofile param.

However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.

Print specific part of webpage

In printPageArea() function, pass the specific div ID which you want to print. I've found this JavaScript code from

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint ='', '', 'width=900,height=650');

The complete code and tutorial can be found from here - How to Print Page Area using JavaScript.

Enum ToString with user friendly strings

I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum:

private enum PublishStatusValue
    [Description("Not Completed")]

Then use this code to retrieve it:

public static string GetDescription<T>(this T enumerationValue)
    where T : struct
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
            //Pull out the description value
            return ((DescriptionAttribute)attrs[0]).Description;
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();

Jersey Exception : SEVERE: A message body reader for Java class

Q) Code was working fine in Intellj but failing in command line.

Sol) Add dependencies of jersey as a direct dependency rather than a transient one.

Reasoning: Since, it was working fine with IntelliJ, dependencies are correctly configured.

  1. Get required dependencies by one of the following:

    1. check for the IntelliJ running command. Stackoverflow-link
    2. List dependencies from maven mvn dependency:tree
  2. Now, add those problematic jersey dependencies explicitly.

When 1 px border is added to div, Div size increases, Don't want to do that

You can try a box-shadow inset

something like this: box-shadow:inset 0px -5px 0px 0px #fff

adds a white 5px border to the bottom of the element without increasing the size

Error using eclipse for Android - No resource found that matches the given name

Eclipse doesn't seem to like imported programs. What worked for me is renaming strings.xml to string.xml, save (without error) and then rename it back to strings.xml, save again and error doesn't show up again.

Eclipse would be sooo good if it wasn't for those tiny little errors all the time :(

Why does modulus division (%) only work with integers?

I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Android Min SDK Version vs. Target SDK Version

android:minSdkVersion and android:targetSdkVersion both are Integer value we need to declare in android manifest file but both are having different properties.

android:minSdkVersion: This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.

android:targetSdkVersion: Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...

How can I strip HTML tags from a string in ASP.NET?

If it is just stripping all HTML tags from a string, this works reliably with regex as well. Replace:


with the empty string, globally. Don't forget to normalize the string afterwards, replacing:


with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.


  1. There is a limitation: HTML and XML allow > in attribute values. This solution will return broken markup when encountering such values.
  2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
  3. As with all things HTML and regex:
    Use a proper parser if you must get it right under all circumstances.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

Got a similar error from CircleCi's error log.

"ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.3.0 but 3.3.3333 was found instead."

Just so you know this did not affect the Angular application, but the CircleCi error was becoming annoying. I am running Angular 7.1

I ran: $ npm i [email protected] --save-dev --save-exact to update the package-lock.json file.

Then I ran: $ npm i

After that I ran: $ npm audit fix

"This CircleCi error message" went away. So it works

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
WHERE day(Submission_date)=day(now) and 
     and year(Submission_date)=year(now)

How to hide a status bar in iOS?

To hide status bar for each individual view controller programmatically, use any of the following two procedures:

Procedure 1:

[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];

Procedure 2:

-(BOOL)prefersStatusBarHidden {

       return YES;


To hide status bar for the entire application, we should follow the given below procedure:

You should add this value to plist: "View controller-based status bar appearance" and set it to "NO".

Click here to view screenshot

In SQL Server, how to create while loop in select

You Could do something like this .....
Your Table




My Suggestion

CREATE TABLE #DestinationTable
    SELECT * INTO #Temp FROM TestTable


        SELECT TOP 1 @Data =  DATA, @ID = ID FROM  #Temp

          WHILE LEN(@Data) > 0
                SET @String = LEFT(@Data, 2)

                INSERT INTO #DestinationTable (ID, Data)
                VALUES (@ID, @String)

                SET @Data = RIGHT(@Data, LEN(@Data) -2)
        DELETE FROM #Temp WHERE ID = @ID

SELECT * FROM #DestinationTable

Result Set

ID  Data
1   AA
1   BB
1   CC
2   FF
2   DD
3   TT
3   HH
3   JJ
3   KK
3   LL

DROP Temp Tables

DROP TABLE #DestinationTable

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
    p1 <- proc.time()
    proc.time() - p1 # The cpu usage should be negligible


> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

CALL command vs. START with /WAIT option

This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.

In the end, piping the command through more did the trick.

setup.exe {arguments} | more

Best tool for inspecting PDF files?

There is also another option. Adobe Acrobat Pro is also able to display the internal tree structure of the PDF.

  1. Open Preflight
  2. Go to Options (right upper corner)
  3. Internal PDF Structure

On top Adobe Acrobat Pro can also display the internal structure of the Document Fonts in the PDF most of other "PDF tree structure viewer" don't have this otion

enter image description here

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

You can't return two (or multiple) columns in your subquery to do the comparison in the WHERE A_ID IN (subquery) clause - which column is it supposed to compare A_ID to? Your subquery must only return the one column needed for the comparison to the column on the other side of the IN. So the query needs to be of the form:

SELECT * From ThisTable WHERE ThisColumn IN (SELECT ThatColumn FROM ThatTable)

You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the ORDER clause is independent of the columns returned by the query.

Try something like this:

select count(distinct dNum) 
from myDB.dbo.AQ 
where A_ID in
    FROM myDB.dbo.AQ 
    WHERE M > 1 and B = 0

Finding the last index of an array

New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!

var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
// World!

instead of the old way:

var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
// World!

It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN

Edit: You can add this functionality to your class like so:

public class MyClass
  public object this[Index indx]
      // Do indexing here, this is just an example of the .IsFromEnd property
      if (indx.IsFromEnd)
        Console.WriteLine("Negative Index!")
        Console.WriteLine("Positive Index!")

The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator

Print a file, skipping the first X lines, in Bash

You'll need tail. Some examples:

$ tail great-big-file.log
< Last 10 lines of great-big-file.log >

If you really need to SKIP a particular number of "first" lines, use

$ tail -n +<N+1> <filename>
< filename, excluding first N lines. >

That is, if you want to skip N lines, you start printing line N+1. Example:

$ tail -n +11 /tmp/myfile
< /tmp/myfile, starting at line 11, or skipping the first 10 lines. >

If you want to just see the last so many lines, omit the "+":

$ tail -n <N> <filename>
< last N lines of file. >

What is the most efficient way to create HTML elements using jQuery?


What is the most efficient way to create HTML elements using jQuery?


Since it's about jQuery then I think it's better to use this (clean) approach (you are using)

$('<div/>', {
    'text':'Text Only',
}).on('click', function(){
    alert(; // myDiv


This way, you can even use event handlers for the specific element like

$('<div/>', {
    'html':'<span>For HTML</span>',
    'click':function(){ alert( },
    'mouseenter':function(){ $(this).css('color', 'red'); },
    'mouseleave':function(){ $(this).css('color', 'black'); }


But when you are dealing with lots of dynamic elements, you should avoid adding event handlers in particular element, instead, you should use a delegated event handler, like

$(document).on('click', '.myClass', function(){

var i=1;
    $('<div/>', {


So, if you create and append hundreds of elements with same class, i.e. (myClass) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.

Update : Since we can use following approach to create a dynamic element

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    'size': '30'

But the size attribute can't be set using this approach using jQuery-1.8.0 or later and here is an old bug report, look at this example using jQuery-1.7.2 which shows that size attribute is set to 30 using above example but using same approach we can't set size attribute using jQuery-1.8.3, here is a non-working fiddle. So, to set the size attribute, we can use following approach

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    attr: { size: "30" }

Or this one

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    prop: { size: "30" }

We can pass attr/prop as a child object but it works in jQuery-1.8.0 and later versions check this example but it won't work in jQuery-1.7.2 or earlier (not tested in all earlier versions).

BTW, taken from jQuery bug report

There are several solutions. The first is to not use it at all, since it doesn't save you any space and this improves the clarity of the code:

They advised to use following approach (works in earlier ones as well, tested in 1.6.4)

.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");

So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S) instead of 'size' then it will just work fine, even in version-2.0.2

$('<input>', {
    'type' : 'text',
    'Size' : '50', // size won't work
    'autofocus' : 'true'

Also read about prop, because there is a difference, Attributes vs. Properties, it varies through versions.

How to import spring-config.xml of one project into spring-config.xml of another project?

For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:

<import resource="classpath*:/spring-config.xml" />

What does .shape[] do in "for i in range(Y.shape[0])"?

In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data

Number of columns is given by


SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

Multiple GitHub Accounts & SSH Config

A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.

Inside the repository for which you want to use a different key, run:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'

If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.

It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).

The entity type <type> is not part of the model for the current context

I get same problem in Entity Framewrok and I solved it by under steps :

1-Open your Model.edmx 2-change a table place (for do change in cs file) 3-save it

I hope help you

Assign variable in if condition statement, good practice or not?

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

Android: Changing Background-Color of the Activity (Main View)

if you put your full code here so i can help you. if your setting the listener in XML and calling the set background color on View so it will change the background color of the view means it ur Botton so put ur listener in ur activity and then change the color of your view

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

If nested hash maps or arrays can be created, then I can simply go down the table from the beginning and add each item to the nested array. I must trace each line to the root node in order to know which level in the nested array to insert into. I can employ memoization so that I do not need to look up the same parent over and over again.

Edit: I would read the entire table into an array first, so it will not query the DB repeatedly. Of course this won't be practical if your table is very large.

After the structure is built, I must do a depth first traverse through it and print out the HTML.

There's no better fundamental way to store this information using one table (I could be wrong though ;), and would love to see a better solution ). However, if you create a scheme to employ dynamically created db tables, then you opened up a whole new world at the sacrifice of simplicity, and the risk of SQL hell ;).

Change jsp on button click

If all you are looking for is navigation to page 2 and 3 from page one, replace the buttons with anchor elements as below:

<form name="TrainerMenu" action="TrainerMenu" method="get">

<h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
<a href="Page2.jsp" id="CreateCourse" >Creazione Nuovo Corso</a>&nbsp;
<a href="Page3.jsp" id="AuthorizationManager">Gestione Autorizzazioni</a>
<input type="button" value="" name="AuthorizationManager" />

If for some reason you need to use buttons, try this:

<form name="TrainerMenu" action="TrainerMenu" method="get">

   <h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
   <input type="button" value="Creazione Nuovo Corso" name="CreateCourse"
   <input type="button" value="Gestione Autorizzazioni" name="AuthorizationManager"
    onclick="openPage('Page3.jsp')" />

<script type="text/javascript">
 function openPage(pageURL)
 window.location.href = pageURL;

How do I specify local .gem files in my Gemfile?

This isn't strictly an answer to your question about installing .gem packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.

Specifying a :path attribute will install the gem from that path on your local machine.

gem "foreman", path: "/Users/pje/my_foreman_fork"

Alternately, specifying a :git attribute will install the gem from a remote git repository.

gem "foreman", git: "git://"

# ...or at a specific SHA-1 ref
gem "foreman", git: "git://", ref: "bf648a070c"

# ...or branch
gem "foreman", git: "git://", branch: "jruby"

# ...or tag
gem "foreman", git: "git://", tag: "v0.45.0"

(As @JHurrah mentioned in his comment.)

Split output of command by columns using Bash?


ps |&
while read -p first second third fourth etc ; do
   if [[ $first == '11383' ]]
       echo got: $fourth

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

How to store Java Date to Mysql datetime...?


As others have indicated, the suggestion of using strings may lead to issues.

What is an attribute in Java?

¦ What is an attribute?

– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members

¦ How else can it be called?

– field or instance variable

¦ How do you create one? What is the syntax?

– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following: ;

Getting execute permission to xp_cmdshell

Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):

use YourDatabase
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
alter role [db_datareader] add member [YourDomain\YourUser]

How to check if the given string is palindrome?

There isn't a single solution on here which takes into account that a palindrome can also be based on word units, not just character units.

Which means that none of the given solutions return true for palindromes like "Girl, bathing on Bikini, eyeing boy, sees boy eyeing bikini on bathing girl".

Here's a hacked together version in C#. I'm sure it doesn't need the regexes, but it does work just as well with the above bikini palindrome as it does with "A man, a plan, a canal-Panama!".

    static bool IsPalindrome(string text)
        bool isPalindrome = IsCharacterPalindrome(text);
        if (!isPalindrome)
            isPalindrome = IsPhrasePalindrome(text);
        return isPalindrome;

    static bool IsCharacterPalindrome(string text)
        String clean = Regex.Replace(text.ToLower(), "[^A-z0-9]", String.Empty, RegexOptions.Compiled);
        bool isPalindrome = false;
        if (!String.IsNullOrEmpty(clean) && clean.Length > 1)
            isPalindrome = true;
            for (int i = 0, count = clean.Length / 2 + 1; i < count; i++)
                if (clean[i] != clean[clean.Length - 1 - i])
                    isPalindrome = false; break;
        return isPalindrome;

    static bool IsPhrasePalindrome(string text)
        bool isPalindrome = false;
        String clean = Regex.Replace(text.ToLower(), @"[^A-z0-9\s]", " ", RegexOptions.Compiled).Trim();
        String[] words = Regex.Split(clean, @"\s+");
        if (words.Length > 1)
            isPalindrome = true;
            for (int i = 0, count = words.Length / 2 + 1; i < count; i++)
                if (words[i] != words[words.Length - 1 - i])
                    isPalindrome = false; break;
        return isPalindrome;

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
>>> d

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
        @Nrows int = 1000

if 1=1 /* testing the inner select */
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date

if 1=1 /* delete or update or select */
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca

How to scroll UITableView to specific position

[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This will take your tableview to the first row.

To draw an Underline below the TextView in Android

A simple and sustainable solution is to create a layer-list and make it as the background of your TextView:

<layer-list xmlns:android="">
                android:color="@color/colorAccent" />

Java - What does "\n" mean?

(as per

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and { matches a left brace.

Other examples of usage :

\\ The backslash character<br>
\t The tab character ('\u0009')<br>
\n The newline (line feed) character ('\u000A')<br>
\r The carriage-return character ('\u000D')<br>
\f The form-feed character ('\u000C')<br>
\a The alert (bell) character ('\u0007')<br>
\e The escape character ('\u001B')<br>
\cx The control character corresponding to x <br>

Eclipse shows errors but I can't find them

If you see the error in problem panel it will say : Description Resource Path Location Type Project configuration is not up-to-date with pom.xml. Select: Maven->Update Project... from the project context menu or use Quick Fix.

Solution : Right click on project > select : Maven->Update Project

Error gone.

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

Simple if else onclick then do?

you call function on page load time but not call on button event, you will need to call function onclick event, you may add event inline element style or event bining

 function Choice(elem) {_x000D_
   var box = document.getElementById("box");_x000D_
   if ( == "no") {_x000D_ = "red";_x000D_
   } else if ( == "yes") {_x000D_ = "green";_x000D_
   } else {_x000D_ = "purple";_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>

or event binding,

window.onload = function() {_x000D_
  var box = document.getElementById("box");_x000D_
  document.getElementById("yes").onclick = function() {_x000D_ = "red";_x000D_
  document.getElementById("no").onclick = function() {_x000D_ = "green";_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

Generate the access token from Github and save it, as it will not appear again.

git -c http.sslVerify=false clone https://<username>:<token>


git config --global http.sslVerify false
git clone

How to create an empty array in PHP with predefined size?

PHP Arrays don't need to be declared with a size.

An array in PHP is actually an ordered map

You also shouldn't get a warning/notice using code like the example you have shown. The common Notice people get is "Undefined offset" when reading from an array.

A way to counter this is to check with isset or array_key_exists, or to use a function such as:

function isset_or($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;

So that you can avoid the repeated code.

Note: isset returns false if the element in the array is NULL, but has a performance gain over array_key_exists.

If you want to specify an array with a size for performance reasons, look at:

SplFixedArray in the Standard PHP Library.

Width equal to content

Adding display: inline-block; to the p styling should take of it:

#container p{
    background-color: green;
    display: inline-block;

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
   // something

Getting All Variables In Scope

Although everyone answer "No" and I know that "No" is the right answer but if you really need to get local variables of a function there is a restricted way.

Consider this function:

var f = function() {
    var x = 0;

You can convert your function to a string:

var s = f + '';

You will get source of function as a string

'function () {\nvar x = 0;\nconsole.log(x);\n}'

Now you can use a parser like esprima to parse function code and find local variable declarations.

var s = 'function () {\nvar x = 0;\nconsole.log(x);\n}';
s = s.slice(12); // to remove "function () "
var esprima = require('esprima');
var result = esprima.parse(s);

and find objects with:

obj.type == "VariableDeclaration"

in the result (I have removed console.log(x) below):

    "type": "Program",
    "body": [
            "type": "VariableDeclaration",
            "declarations": [
                    "type": "VariableDeclarator",
                    "id": {
                        "type": "Identifier",
                        "name": "x"
                    "init": {
                        "type": "Literal",
                        "value": 0,
                        "raw": "0"
            "kind": "var"

I have tested this in Chrome, Firefox and Node.

But the problem with this method is that you just have the variables defined in the function itself. For example for this one:

var g = function() {
    var y = 0;
    var f = function() {
        var x = 0;

you just have access to the x and not y. But still you can use chains of caller (arguments.callee.caller.caller.caller) in a loop to find local variables of caller functions. If you have all local variable names so you have scope variables. With the variable names you have access to values with a simple eval.

Detect if HTML5 Video element is playing

My answer at How to tell if a <video> element is currently playing?:

MediaElement does not have a property that tells about if its playing or not. But you could define a custom property for it.

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);

Now you can use it on video or audio elements like this:

    // Do anything you want to

How do I connect to a specific Wi-Fi network in Android programmatically?

In API level 29, WifiManager.enableNetwork() method is deprecated. As per Android API documentation(check here):

  1. See WifiNetworkSpecifier.Builder#build() for new mechanism to trigger connection to a Wi-Fi network.
  2. See addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List) for new API to add Wi-Fi networks for consideration when auto-connecting to wifi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false.

From API level 29, to connect to WiFi network, you will need to use WifiNetworkSpecifier. You can find example code at

How to format a float in javascript?

var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

How to change python version in anaconda spyder

  1. Set python3 as a main version in the terminal: ln -sf python3 /usr/bin/python

  2. Install pip3: apt-get install python3-pip

  3. Update spyder: pip install -U spyder


Sorting int array in descending order

If it's not a big/long array just mirror it:

for( int i = 0; i < arr.length/2; ++i ) 
  temp = arr[i]; 
  arr[i] = arr[arr.length - i - 1]; 
  arr[arr.length - i - 1] = temp; 

How to create a self-signed certificate with OpenSSL

openssl allows to generate self-signed certificate by a single command (-newkey instructs to generate a private key and -x509 instructs to issue a self-signed certificate instead of a signing request)::

openssl req -x509 -newkey rsa:4096 \
-keyout my.key -passout pass:123456 -out my.crt \
-days 365 \
-subj /CN=localhost/O=home/C=US/[email protected] \
-addext "subjectAltName = DNS:localhost,DNS:web.internal,email:[email protected]" \
-addext keyUsage=digitalSignature -addext extendedKeyUsage=serverAuth

You can generate a private key and construct a self-signing certificate in separate steps::

openssl genrsa -out my.key -passout pass:123456 2048

openssl req -x509 \
-key my.key -passin pass:123456 -out my.csr \
-days 3650 \
-subj /CN=localhost/O=home/C=US/[email protected] \
-addext "subjectAltName = DNS:localhost,DNS:web.internal,email:[email protected]" \
-addext keyUsage=digitalSignature -addext extendedKeyUsage=serverAuth

Review the resulting certificate::

openssl x509 -text -noout -in my.crt

Java keytool creates PKCS#12 store::

keytool -genkeypair -keystore my.p12 -alias master \
-storetype pkcs12 -keyalg RSA -keysize 2048 -validity 3650 \
-storepass 123456 \
-dname "CN=localhost,O=home,C=US" \
-ext 'san=dns:localhost,dns:web.internal,email:[email protected]'

To export the self-signed certificate::

keytool -exportcert -keystore my.p12 -file my.crt \
-alias master -rfc -storepass 123456

Review the resulting certificate::

keytool -printcert -file my.crt

certtool from GnuTLS doesn't allow passing different attributes from CLI. I don't like to mess with config files ((

How to delete/remove nodes on Firebase

In case you are using axios and trying via a service call.

Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE

axios.delete(``). then();

can help.

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

Angular 2: import external js file into component

The following approach worked in Angular 5 CLI.

For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.

So first, I simply created a new folder named externalJS on same level as the assets folder. I then copied the 2 following .js files.

  • d3.v3.min.js
  • d3gauge.js

I then made sure to declare both linked directives in main index.html

<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>

I then added a similar code in a gauge.component.ts component as followed:

import { Component, OnInit } from '@angular/core';

declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!

  selector: 'app-gauge',
  templateUrl: './gauge.component.html'

export class GaugeComponent implements OnInit {
   constructor() { }

   ngOnInit() {

   createD3Gauge() { 
      let gauges = []
      document.addEventListener("DOMContentLoaded", function (event) {      
      let opt = {
         gaugeRadius: 160,
         minVal: 0,
         maxVal: 100,
         needleVal: Math.round(30),
         tickSpaceMinVal: 1,
         tickSpaceMajVal: 10,
         divID: "gaugeBox",
         gaugeUnits: "%"

    gauges[0] = new drawGauge(opt);


and finally, I simply added a div in corresponding gauge.component.html

<div id="gaugeBox"></div>

et voilà ! :)

enter image description here

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

You can find the source images by extracting them from Other.artwork in UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork. The modding community has some tools for extracting them, here. Once you extract the image you can write some code to recolor it as necessary and set it as the button image. Whether or not you can actually ship such a thing (since you are embedding derived artwork) might be a little dicey, so maybe you want to talk to a lawyer.

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','','-i', 'test.txt'])

To demonstrate, here are my two programs:

import sys
print sys.argv

import subprocess
py2output = subprocess.check_output(['python', '', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3
py2 said: b"['', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python '),'-i', 'test.txt'])

First, str('python') is exactly the same thing as 'python'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ Which you're not; you're trying to run, say, /usr/bin/python with first argument So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".


-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Making LaTeX tables smaller?

You could add \singlespacing near the beginning of your table. See the setspace instructions for more options.

What is the meaning of the term "thread-safe"?

Thread-safe-code works as specified, even when entered simultaneously by different threads. This often means, that internal data-structures or operations that should run uninterrupted are protected against different modifications at the same time.

Mouseover or hover vue.js

Though I would give an update using the new composition api.


  <div @mouseenter="hovering = true" @mouseleave="hovering = false">
    {{ hovering }}

  import { ref } from '@vue/compsosition-api'

  export default {
    setup() {
      const hovering = ref(false)
      return { hovering }

Reusable Composition Function

Creating a useHover function will allow you to reuse in any components.

export function useHover(target: Ref<HTMLElement | null>) {
  const hovering = ref(false)

  const enterHandler = () => (hovering.value = true)
  const leaveHandler = () => (hovering.value = false)

  onMounted(() => {
    if (!target.value) return
    target.value.addEventListener('mouseenter', enterHandler)
    target.value.addEventListener('mouseleave', leaveHandler)

  onUnmounted(() => {
    if (!target.value) return
    target.value.removeEventListener('mouseenter', enterHandler)
    target.value.removeEventListener('mouseleave', leaveHandler)

  return hovering

Here's a quick example calling the function inside a Vue component.

  <div ref="hoverRef">
    {{ hovering }}

<script lang="ts">
  import { ref } from '@vue/compsosition-api'
  import { useHover } from './useHover'

  export default {
    setup() {
      const hoverRef = ref(null)
      const hovering = useHover(hoverRef)
      return { hovering, hoverRef }

You can also use a library such as @vuehooks/core which comes with many useful functions including useHover.

disable viewport zooming iOS 10+ safari?

Found this simple work around which appears to prevent double click to zoom:

    // Convert touchend events to click events to work around an IOS 10 feature which prevents
    // developers from using disabling double click touch zoom (which we don't want).
    document.addEventListener('touchend', function (event) {
    }, false);

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
<script src=""></script>

How to get video duration, dimension and size in PHP? download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);


        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Change Bootstrap input focus blue glow

To disable the blue glow (but you can modify the code to change color, size, etc), add this to your css:

.search-form input[type="search"] {  
    -webkit-box-shadow: none;
    outline: -webkit-focus-ring-color auto 0px;

Here's a screencapture showing the effect: before and after: enter image description here enter image description here

Bootstrap $('#myModal').modal('show') is not working

I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'), `

    <button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
    $('#btnPurchaseClose').trigger('click');// for close popup

     $('#btnOpenPurchase').trigger('click');`// for open popup

WebView and Cookies on Android

From the Android documentation:

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

To use the CookieSyncManager, the host application has to call the following when the application starts:


To set up for sync, the host application has to call


in Activity.onResume(), and call


in Activity.onPause().

To get instant sync instead of waiting for the timer to trigger, the host can call


The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.

Finally something like this should work:

// use cookies to remember a logged in status   
WebView webview = new WebView(this);
webview.loadUrl([MY URL]);

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here:

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
        <script src="main.js" type="text/javascript"></script>


var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

Node.js Generate html

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

There are a few methods you can choose from to do what you want.

Method 1: Serving the file directly via HTTP

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

There are plenty frameworks out there for that :

The most basic way you could do what you want is this :

var http = require('http');

http.createServer(function (req, res) {
  var html = buildHtml(req);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': html.length,
    'Expires': new Date().toUTCString()

function buildHtml(req) {
  var header = '';
  var body = '';

  // concatenate header string
  // concatenate body string

  return '<!DOCTYPE html>'
       + '<html><head>' + header + '</head><body>' + body + '</body></html>';

And access this HTML with http://localhost:8080 from your browser.

(Edit: you could also serve them with a small HTTP server.)

Method 2: Generating the file only

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');

var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);

stream.once('open', function(fd) {
  var html = buildHtml();


Note: The buildHtml function is exactly the same as in Method 1.

Method 3: Dumping the file directly into stdout

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();


Note: The buildHtml function is exactly the same as in Method 1 (again)

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file


Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');

var html = htmlBuilder(options);

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

Extra reading, learn about npm. Hope this helps.

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

Firefox setting to enable cross domain Ajax request

Here is the thing, there is no way to "temporarily" disable cross-domain XMLHttpRequest, if you can disable it temporarily then it can be disabled permanently. This is a rather common problem in the modern-day of AJAX programming and is most often solved using the technique known as cross-domain scripting.

The idea here being is that if you call out to a cross-domain script it returns JavaScript (JSON) results that are then passed on to a function on your end.

Here is some sample code to illustrate how it may look from a JavaScript code perspective:

  function request_some_data() {
    var s = "";

      try {
          document.write("<scr"+"ipt type='text/javascript' src='"+s+"'></scr"+"ipt>");
          var x = document.createElement("script");
          x.src = s;
      catch (e) {

You will then define a function in your code that receives the data and in the server you "handle" the callback case, here is the client-side JavaScript:

function myfunc(data) {

And on the server side, here i'm giving a PHP example but this can be done just as easily in Java or what-ever your server-side technology is:

   if($_GET["callback"]) {
     print($_GET["callback"] . "(");
   /* place your JSON object code/logic here */
   if($_GET["callback"]) {

Note that what you are generating on the server side winds up being some JavaScript that gets executed on the client side.

Limit text length to n lines using CSS

I really like line-clamp, but no support for firefox yet.. so i go with a math calc and just hide the overflow

.body-content.body-overflow-hidden h5 {
    max-height: 62px;/* font-size * line-height * lines-to-show(4 in this case) 63px if you go with jquery */
    overflow: hidden;
.body-content h5 {
    font-size: 14px; /* need to know this*/
    line-height:1,1; /*and this*/

now lets say you want to remove and add this class via jQuery with a link, you will need to have an extra pixel so the max-height it will be 63 px, this is because you need to check every time if the height greather than 62px, but in the case of 4 lines you will get a false true, so an extra pixel will fix this and it will no create any extra problems

i will paste a coffeescript for this just to be an example, uses a couple of links that are hidden by default, with classes read-more and read-less, it will remove the ones that the overflow is not need it and remove the body-overflow classes

jQuery ->

    $('.read-more').each ->
        if $(this).parent().find("h5").height() < 63

    $('.read-more').click (event) ->

    $('.read-less').click (event) ->

Listing files in a specific "folder" of a AWS S3 bucket

While everybody say that there are no directories and files in s3, but only objects (and buckets), which is absolutely true, I would suggest to take advantage of CommonPrefixes, described in this answer. So, you can do following to get list of "folders" (commonPrefixes) and "files" (objectSummaries):

ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket.getName()).withPrefix(prefix).withDelimiter(DELIMITER);
ListObjectsV2Result listing = s3Client.listObjectsV2(req);
for (String commonPrefix : listing.getCommonPrefixes()) {
for (S3ObjectSummary summary: listing.getObjectSummaries()) {

In your case, for objectSummaries (files) it should return (in case of correct prefix):

for commonPrefixes:


How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options


From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Datatables on-the-fly resizing

The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)

  $(window).resize( function() {

This was the approach that worked in my case.

Checking if a file is a directory or just a file

Yes, there is better. Check the stat or the fstat function

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])

enter image description here

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

How to capture a list of specific type with mockito

The nested generics-problem can be avoided with the @Captor annotation:

public class Test{

    private Service service;

    private ArgumentCaptor<ArrayList<SomeType>> captor;

    public void init(){

    public void shouldDoStuffWithListValues() {

How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
         return (ServiceCollection)base["Services"];

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

python how to pad numpy array with zeros

I understand that your main problem is that you need to calculate d=b-a but your arrays have different sizes. There is no need for an intermediate padded c

You can solve this without padding:

import numpy as np

a = np.array([[ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.]])

b = np.array([[ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.]])

d = b.copy()
d[:a.shape[0],:a.shape[1]] -=  a

print d


[[ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 3.  3.  3.  3.  3.  3.]]

Remove all whitespace in a string

Be careful:

strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).

If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to compare type of an object in Python?

Use str instead of string

type ( obj ) == str


>>> a = "Hello"
>>> type(a)==str
>>> type(a)
<type 'str'>

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
where TABLE_NAME = 'Foobar'

Reading and writing value from a textfile by using vbscript code

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")

' read file
data = inFile.ReadAll

' write file
outFile.write (data)

import error: 'No module named' *does* exist

I got this when I didn't type things right. I had


instead of

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data =;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
            else {
        }, function (error) {

        alert("Failed Login");

The above snipit works for a login page.

.Contains() on a list of custom class objects

It checks to see whether the specific object is contained in the list.

You might be better using the Find method on the list.

Here's an example

List<CartProduct> lst = new List<CartProduct>();

CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));

Hope that helps

You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...

Selenium using Python - Geckodriver executable needs to be in PATH

  1. Ensure you have the correct version of the driver (geckodriver), x86 or 64.
  2. Ensure you are checking the right environment. For example, the job is running in a Docker container, whereas the environment is checked on the host OS.

Cannot GET / Nodejs Error

Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:


For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.

Hope that helps!

Ruby on Rails generates model field:type - what are the options for field:type?

There are lots of data types you can mention while creating model, some examples are:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references



Can you recommend a free light-weight MySQL GUI for Linux?

Here are few solutions -

  • MySql Gui tools is official ui from Mysql.
  • You can also try Mysql Workbench which is going to replace Gui Tools.
  • Mysql Yog can be run on Linux using wine (I think they officially recommend this method).
  • HeidiSql is also good option, I use it most of the time. It also run using wine on Linux. It lightest of all.
  • If you are looking for web based solution than phpmyadmin is the solution.

Since you are already using sqlyog, I suggest you to use same on Linux as well.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

After looking around a little longer I came across this. Apparently, there isn't a solution to this issue yet, but there is a workaround - going back to the legacy workflow.

The legacy workflow did work for me, and the only additional thing I had to do was to go to the platform-tools folder from android SDK download, open a command window here and run command "adb devices". This caused the computer RSA key fingerprint panel to pop on my mobile screen, and after granting permission, the device showed up under Chrome's Inspect page.

Turns out that it was not an issue caused by mobile OS upgrade but by Chrome (I was thrown off by the fact that it worked on my Nexus4 somehow). In the older versions of Chrome there was't a need to download the 500 odd mb Android SDK, as it supported an ADB plugin. But with latest version of Chrome, I guess, going legacy is the only way to go.

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)

Angular 4 checkbox change value

Another approach is to use ngModelChange:


<input type="checkbox" ngModel (ngModelChange)="onChecked(obj, $event)" />


onChecked(obj: any, isChecked: boolean){
  console.log(obj, isChecked); // {}, true || false

I prefer this method because here you get the relevant object and true/false values of a checkbox.

Get first line of a shell command's output

I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt


But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
==> file_n.csv <==

val() doesn't trigger change() in jQuery

As of feb 2019 .addEventListener() is not currently work with jQuery .trigger() or .change(), you can test it below using Chrome or Firefox.

txt.addEventListener('input', function() {_x000D_
  console.log('not called?');_x000D_
<script src=""></script>_x000D_
<input type="text" id="txt">

you have to use .dispatchEvent() instead.

txt.addEventListener('input', function() {_x000D_
  console.log('it works!');_x000D_
txt.dispatchEvent(new Event('input'));
<script src=""></script>_x000D_
<input type="text" id="txt">

Convert string (without any separator) to list

Instead of converting to a list, you could just iterate over the first string and create a second string by adding each of the digit characters you find to that new string.

Create or write/append in text file

Use the a mode. It stands for append.

$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);

Query for documents where array size is greater than 1

None of the above worked for me. This one did so I'm sharing it:

db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    string json = new JavaScriptSerializer().Serialize(new
                Username = "myusername",
                Password = "pass"

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    var result = streamReader.ReadToEnd();

Maven dependency for Servlet 3.0 API?

This seems to be added recently:


Python find elements in one list that are not in the other

If the number of occurences should be taken into account you probably need to use something like collections.Counter:

list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 
from collections import Counter
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['f', 'm']

As promised this can also handle differing number of occurences as "difference":

list_1=["a", "b", "c", "d", "e", 'a']
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['a', 'f', 'm']

window.onload vs document.onload

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

Java - Best way to print 2D array?

@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per normal CS convention. If however you would prefer to use normal mathematical convention and put (0,0) in the lower left hand corner, you could use this:

LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
while (!printList.isEmpty())

This used LIFO (Last In First Out) to reverse the order at print time.

Reference jars inside a jar

You can't. From the official tutorial:

By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run the your application.

Note: The Class-Path header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar contains another JAR file called MyUtils.jar, you cannot use the Class-Path header in MyJar.jar's manifest to load classes in MyUtils.jar into the class path.

Python 2,3 Convert Integer to "bytes" Cleanly

In Python 3.x, you can convert an integer value (including large ones, which the other answers don't allow for) into a series of bytes like this:

import math

x = 0x1234
number_of_bytes = int(math.ceil(x.bit_length() / 8))

x_bytes = x.to_bytes(number_of_bytes, byteorder='big')

x_int = int.from_bytes(x_bytes, byteorder='big')
x == x_int

equivalent of vbCrLf in c#

"FirstLine" + "<br/>" "SecondLine"

iPhone hide Navigation Bar only on first page

The currently accepted answer does not match the intended behavior described in the question. The question asks for the navigation bar to be hidden on the root view controller, but visible everywhere else, but the accepted answer hides the navigation bar on a particular view controller. What happens when another instance of the first view controller is pushed onto the stack? It will hide the navigation bar even though we are not looking at the root view controller.

Instead, @Chad M.'s strategy of using the UINavigationControllerDelegate is a good one, and here is a more complete solution. Steps:

  1. Subclass UINavigationController
  2. Implement the -navigationController:willShowViewController:animated method to show or hide the navigation bar based on whether it is showing the root view controller
  3. Override the initialization methods to set the UINavigationController subclass as its own delegate

Complete code for this solution can be found in this Gist. Here's the navigationController:willShowViewController:animated implementation:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
    /* Hide navigation bar if root controller */
    if ([viewController isEqual:[self.viewControllers firstObject]]) {
        [self setNavigationBarHidden:YES animated:animated];
    } else {
        [self setNavigationBarHidden:NO animated:animated];

How do I POST JSON data with cURL?

This worked for me for on Windows10

curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X  PUT http://localhost:8080/api/changeowner/CAR4

Checking if a number is a prime number in Python

def prime(x):
    # check that number is greater that 1
    if x > 1:
        for i in range(2, x + 1):
            # check that only x and 1 can evenly divide x
            if x % i == 0 and i != x and i != 1:
                return False
            return True
        return False # if number is negative

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));


I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:


I assigned this shortcut to my F5 key for maximum laziness.

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.


For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here:

Finding element in XDocument?

You can do it this way:

xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

Html.DropdownListFor selected value not being set

Your code has some conceptual issues:


@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId as part of your model or something like that, in order to use it in this way:

@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")


Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.

Some code I would use if I were you to avoid this issues and write better MVC code:


public class MyViewModel{
   public int SelectedOrderId {get; set;}
   public SelectList OrderTemplates {get; set;}

   // Other properties you need in your view


public ActionResult MyAction(){
   var model = new MyViewModel();
   model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
   //Other initialization code

   return View(model);

In your View:

@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")

Disable text input history

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

Convert an image to grayscale

Bitmap d = new Bitmap(c.Width, c.Height);

for (int i = 0; i < c.Width; i++)
    for (int x = 0; x < c.Height; x++)
        Color oc = c.GetPixel(i, x);
        int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
        Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
        d.SetPixel(i, x, nc);

This way it also keeps the alpha channel.

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like that will convert a screenshot to a color code.

How do I measure separate CPU core usage for a process?

I had just this problem and I found a similar answer here.

The method is to set top the way you want it and then press W (capital W). This saves top's current layout to a configuration file in $HOME/.toprc

Although this might not work if you want to run multiple top's with different configurations.

So via what I consider a work around you can write to different config files / use different config files by doing one of the following...

1) Rename the binary

  ln -s /usr/bin/top top2

Now .top2rc is going to be written to your $HOME

2) Set $HOME to some alternative path, since it will write its config file to the $HOME/.binary-name.rc file


Now .toprc is going to be written to the current folder.

Via use of other peoples comments to add the various usage accounting in top you can create a batch output for that information and latter coalesces the information via a script. Maybe not quite as simple as you script but I found top to provide me ALL processes so that later I can recap and capture a state during a long run that I might have missed otherwise (unexplained sudden CPU usage due to stray processes)

Why doesn't Dijkstra's algorithm work for negative weight edges?

Try Dijkstra's algorithm on the following graph, assuming A is the source node and D is the destination, to see what is happening:


Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).

The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.

Add column in dataframe from list

First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.

df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})

And the mapping that you desire:

mapping = dict(enumerate([2,5,6,8,12,16,26,32]))

df['D'] = df['A'].map(mapping)


print df


   A   D
0  0   2
1  4  12
2  5  16
3  6  26
4  7  32
5  7  32
6  6  26
7  5  16

Strip double quotes from a string in .NET

s = s.Replace( """", "" )

Two quotes next to each other will function as the intended " character when inside a string.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.


$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle

if ($proc.ExitCode -ne 0) {
    Write-Warning "$_ exited with status code $($proc.ExitCode)"

How to keep footer at bottom of screen

use this style


"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];


Determine direct shared object dependencies of a Linux binary?

You can use readelf to explore the ELF headers. readelf -d will list the direct dependencies as NEEDED sections.

 $ readelf -d elfbin

Dynamic section at offset 0xe30 contains 22 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: []
 0x0000000000000001 (NEEDED)             Shared library: []
 0x000000000000000c (INIT)               0x400520
 0x000000000000000d (FINI)               0x400758

I want to delete all bin and obj folders to force all projects to rebuild everything

To delete bin and obj before build add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />

Here is article: How to remove bin and/or obj folder before the build or deploy

Set value of textbox using JQuery

You're targeting the wrong item with that jQuery selector. The name of your search bar is searchBar, not the id. What you want to use is $('#main_search').val('hi').

Nginx not running with no error message

Check the daemon option in nginx.conf file. It has to be ON. Or you can simply rip out this line from config file. This option is fully described here

Can a main() method of class be invoked from another class in java

Sure. Here's a completely silly program that demonstrates calling main recursively.

public class main
    public static void main(String[] args)
        for (int i = 0; i < args.length; ++i)
            if (args[i] != "")
                args[i] = "";
                System.out.println((args.length - i) + " left");