Programs & Examples On #Erlang

Erlang is a general-purpose, garbage-collected programming language and runtime environment, with built-in support for concurrency, distribution and fault tolerance.

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

There are some problems with the Erlang implementation. As baseline for the following, my measured execution time for your unmodified Erlang program was 47.6 seconds, compared to 12.7 seconds for the C code.

The first thing you should do if you want to run computationally intensive Erlang code is to use native code. Compiling with erlc +native euler12 got the time down to 41.3 seconds. This is however a much lower speedup (just 15%) than expected from native compilation on this kind of code, and the problem is your use of -compile(export_all). This is useful for experimentation, but the fact that all functions are potentially reachable from the outside causes the native compiler to be very conservative. (The normal BEAM emulator is not that much affected.) Replacing this declaration with -export([solve/0]). gives a much better speedup: 31.5 seconds (almost 35% from the baseline).

But the code itself has a problem: for each iteration in the factorCount loop, you perform this test:

factorCount (_, Sqrt, Candidate, Count) when Candidate == Sqrt -> Count + 1;

The C code doesn't do this. In general, it can be tricky to make a fair comparison between different implementations of the same code, and in particular if the algorithm is numerical, because you need to be sure that they are actually doing the same thing. A slight rounding error in one implementation due to some typecast somewhere may cause it to do many more iterations than the other even though both eventually reach the same result.

To eliminate this possible error source (and get rid of the extra test in each iteration), I rewrote the factorCount function as follows, closely modelled on the C code:

factorCount (N) ->
    Sqrt = math:sqrt (N),
    ISqrt = trunc(Sqrt),
    if ISqrt == Sqrt -> factorCount (N, ISqrt, 1, -1);
       true          -> factorCount (N, ISqrt, 1, 0)
    end.

factorCount (_N, ISqrt, Candidate, Count) when Candidate > ISqrt -> Count;
factorCount ( N, ISqrt, Candidate, Count) ->
    case N rem Candidate of
        0 -> factorCount (N, ISqrt, Candidate + 1, Count + 2);
        _ -> factorCount (N, ISqrt, Candidate + 1, Count)
    end.

This rewrite, no export_all, and native compilation, gave me the following run time:

$ erlc +native euler12.erl
$ time erl -noshell -s euler12 solve
842161320

real    0m19.468s
user    0m19.450s
sys 0m0.010s

which is not too bad compared to the C code:

$ time ./a.out 
842161320

real    0m12.755s
user    0m12.730s
sys 0m0.020s

considering that Erlang is not at all geared towards writing numerical code, being only 50% slower than C on a program like this is pretty good.

Finally, regarding your questions:

Question 1: Do erlang, python and haskell loose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?

Yes, somewhat. In Erlang, there is no way of saying "use 32/64-bit arithmetic with wrap-around", so unless the compiler can prove some bounds on your integers (and it usually can't), it must check all computations to see if they can fit in a single tagged word or if it has to turn them into heap-allocated bignums. Even if no bignums are ever used in practice at runtime, these checks will have to be performed. On the other hand, that means you know that the algorithm will never fail because of an unexpected integer wraparound if you suddenly give it larger inputs than before.

Question 4: Do my functional implementations permit LCO and hence avoid adding unnecessary frames onto the call stack?

Yes, your Erlang code is correct with respect to last call optimization.

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

DateTime to javascript date

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

Reference - What does this error mean in PHP?

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew ?????? ?????????. which means "double colon".

This error typically happens if you inadvertently put :: in your code.

Related Questions:

Documentation:

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

If you are on a mac check if you for a hidden file, .DS_Store. After removing the file my program worked.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Is there a difference between x++ and ++x in java?

Yes.

public class IncrementTest extends TestCase {

    public void testPreIncrement() throws Exception {
        int i = 0;
        int j = i++;
        assertEquals(0, j);
        assertEquals(1, i);
    }

    public void testPostIncrement() throws Exception {
        int i = 0;
        int j = ++i;
        assertEquals(1, j);
        assertEquals(1, i);
    }
}

How may I reference the script tag that loaded the currently-executing script?

Consider this algorithm. When your script loads (if there are multiple identical scripts), look through document.scripts, find the first script with the correct "src" attribute, and save it and mark it as 'visited' with a data-attribute or unique className.

When the next script loads, scan through document.scripts again, passing over any script already marked as visited. Take the first unvisited instance of that script.

This assumes that identical scripts will likely execute in the order in which they are loaded, from head to body, from top to bottom, from synchronous to asynchronous.

(function () {
  var scripts = document.scripts;

  // Scan for this data-* attribute
  var dataAttr = 'data-your-attribute-here';

  var i = 0;
  var script;
  while (i < scripts.length) {
    script = scripts[i];
    if (/your_script_here\.js/i.test(script.src)
        && !script.hasAttribute(dataAttr)) {

        // A good match will break the loop before
        // script is set to null.
        break;
    }

    // If we exit the loop through a while condition failure,
    // a check for null will reveal there are no matches.
    script = null;
    ++i;
  }

  /**
   * This specific your_script_here.js script tag.
   * @type {Element|Node}
   */
  var yourScriptVariable = null;

  // Mark the script an pass it on.
  if (script) {
    script.setAttribute(dataAttr, '');
    yourScriptVariable = script;
  }
})();

This will scan through all the script for the first matching script that isn't marked with the special attribute.

Then mark that node, if found, with a data-attribute so subsequent scans won't choose it. This is similar to graph traversal BFS and DFS algorithms where nodes may be marked as 'visited' to prevent revisitng.

How do I increase memory on Tomcat 7 when running as a Windows Service?

The answer to my own question is, I think, to use tomcat7.exe:

cd $CATALINA_HOME
.\bin\service.bat install tomcat
.\bin\tomcat7.exe //US//tomcat7 --JvmMs=512 --JvmMx=1024 --JvmSs=1024

Also, you can launch the UI tool mentioned by BalusC without the system tray or using the installer with tomcat7w.exe

.\bin\tomcat7w.exe //ES//tomcat

An additional note to this:

Setting the --JvmXX parameters (through the UI tool or the command line) may not be enough. You may also need to specify the JVM memory values explicitly. From the command line it may look like this:

bin\tomcat7w.exe //US//tomcat7 --JavaOptions=-Xmx=1024;-Xms=512;..

Be careful not to override the other JavaOption values. You can try updating bin\service.bat or use the UI tool and append the java options (separate each value with a new line).

Visual Studio 64 bit?

No! There is no 64-bit version of Visual Studio.

How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0

As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.

How to get element value in jQuery

$("#list li").click(function() {
        var selected = $(this).html();
        alert(selected);
});

How can I find and run the keytool

Keytool is part of the Java SDK. You should be able to find it in your Java SDK directory e.g. C:\Program Files\Java\jdk1.6.0_14\bin

Find row in datatable with specific id

I could use the following code. Thanks everyone.

int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);

What is the difference between call and apply?

From the MDN docs on Function.prototype.apply() :

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

Syntax

fun.apply(thisArg, [argsArray])

From the MDN docs on Function.prototype.call() :

The call() method calls a function with a given this value and arguments provided individually.

Syntax

fun.call(thisArg[, arg1[, arg2[, ...]]])

From Function.apply and Function.call in JavaScript :

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.


Code example :

_x000D_
_x000D_
var doSomething = function() {_x000D_
    var arr = [];_x000D_
    for(i in arguments) {_x000D_
        if(typeof this[arguments[i]] !== 'undefined') {_x000D_
            arr.push(this[arguments[i]]);_x000D_
        }_x000D_
    }_x000D_
    return arr;_x000D_
}_x000D_
_x000D_
var output = function(position, obj) {_x000D_
    document.body.innerHTML += '<h3>output ' + position + '</h3>' + JSON.stringify(obj) + '\n<br>\n<br><hr>';_x000D_
}_x000D_
_x000D_
output(1, doSomething(_x000D_
    'one',_x000D_
    'two',_x000D_
    'two',_x000D_
    'one'_x000D_
));_x000D_
_x000D_
output(2, doSomething.apply({one : 'Steven', two : 'Jane'}, [_x000D_
    'one',_x000D_
    'two',_x000D_
    'two',_x000D_
    'one'_x000D_
]));_x000D_
_x000D_
output(3, doSomething.call({one : 'Steven', two : 'Jane'},_x000D_
    'one',_x000D_
    'two',_x000D_
    'two',_x000D_
    'one'_x000D_
));
_x000D_
_x000D_
_x000D_

See also this Fiddle.

HTML 5: Is it <br>, <br/>, or <br />?

I would recommend using <br /> for the following reasons:

1) Text and XML editors that highlight XML syntax in different colours will highlight properly with <br /> but this is not always the case if you use <br>

2) <br /> is backwards-compatible with XHTML and well-formed HTML (ie: XHTML) is often easier to validate for errors and debug

3) Some old parsers and some coding specs require the space before the closing slash (ie: <br /> instead of <br/>) such as the WordPress Plugin Coding spec: http://make.wordpress.org/core/handbook/coding-standards/html/

I my experience, I have never come across a case where using <br /> is problematic, however, there are many cases where <br/> or especially <br> might be problematic in older browsers and tools.

Laravel Redirect Back with() Message

I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:

Pull in the package through Composer.

"require": {
  "laracasts/flash": "~1.0"
}

Include the service provider within app/config/app.php.

'providers' => [
  'Laracasts\Flash\FlashServiceProvider'
];

Add a facade alias to this same file at the bottom:

'aliases' => [
  'Flash' => 'Laracasts\Flash\Flash'
];

Pull the HTML into the view:

@include('flash::message') 

There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.

optional changes:

If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:

@if (Session::has('flash_notification.message'))
  <div class="{{ Session::get('flash_notification.level') }}">
    {{ Session::get('flash_notification.message') }}
  </div>
@endif

If you would like to view the HTML pulled in by @include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.

If you need to modify the partials do:

php artisan view:publish laracasts/flash

The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.

Input text dialog Android

If you want some space at left and right of input view, you can add some padding like

private fun showAlertWithTextInputLayout(context: Context) {
    val textInputLayout = TextInputLayout(context)
    textInputLayout.setPadding(
        resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
        0,
        resources.getDimensionPixelOffset(R.dimen.dp_19),
        0
    )
    val input = EditText(context)
    textInputLayout.hint = "Email"
    textInputLayout.addView(input)

    val alert = AlertDialog.Builder(context)
        .setTitle("Reset Password")
        .setView(textInputLayout)
        .setMessage("Please enter your email address")
        .setPositiveButton("Submit") { dialog, _ ->
            // do some thing with input.text
            dialog.cancel()
        }
        .setNegativeButton("Cancel") { dialog, _ ->
            dialog.cancel()
        }.create()

    alert.show()
}

dimens.xml

<dimen name="dp_19">19dp</dimen>

Hope it help

Change the selected value of a drop-down list with jQuery

How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.

If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.

This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.

Read Excel File in Python

Although I almost always just use pandas for this, my current little tool is being packaged into an executable and including pandas is overkill. So I created a version of poida's solution that resulted in a list of named tuples. His code with this change would look like this:

from xlrd import open_workbook
from collections import namedtuple
from pprint import pprint

wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
OneRow = namedtuple('OneRow', ' '.join(FORMAT))
all_rows = []

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == headerRow[x].value]

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        all_rows.append(OneRow(*currentRowValues))

pprint(all_rows)

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

Unresolved Import Issues with PyDev and Eclipse

I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.

I right clicked the project->Pydev->Remove error markers and it got rid of that problem. Don't worry, if your code contains actual errors they will be re-marked.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

You can use x.astype('uint8') where x is your Boolean array.

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

cleanest way to skip a foreach if array is empty

i've got the following function in my "standard library"

/// Convert argument to an array.
function a($a = null) {
    if(is_null($a))
        return array();
    if(is_array($a))
        return $a;
    if(is_object($a))
        return (array) $a;
    return $_ = func_get_args();
}

Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions

  foreach(a($whatever) as $item)....

  $foo = array_map(a($array_or_string)....

  etc

How to enable CORS in flask

I've just faced the same issue and I came to believe that the other answers are a bit more complicated than they need to be, so here's my approach for those who don't want to rely on more libraries or decorators:

A CORS request actually consists of two HTTP requests. A preflight request and then an actual request that is only made if the preflight passes successfully.

The preflight request

Before the actual cross domain POST request, the browser will issue an OPTIONS request. This response should not return any body, but only some reassuring headers telling the browser that it's alright to do this cross-domain request and it's not part of some cross site scripting attack.

I wrote a Python function to build this response using the make_response function from the flask module.

def _build_cors_prelight_response():
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "*")
    response.headers.add("Access-Control-Allow-Methods", "*")
    return response

This response is a wildcard one that works for all requests. If you want the additional security gained by CORS, you have to provide a whitelist of origins, headers and methods.

This response will convince your (Chrome) browser to go ahead and do the actual request.

The actual request

When serving the actual request you have to add one CORS header - otherwise the browser won't return the response to the invoking JavaScript code. Instead the request will fail on the client-side. Example with jsonify

response = jsonify({"order_id": 123, "status": "shipped"}
response.headers.add("Access-Control-Allow-Origin", "*")
return response

I also wrote a function for that.

def _corsify_actual_response(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

allowing you to return a one-liner.

Final code

from flask import Flask, request, jsonify, make_response
from models import OrderModel

flask_app = Flask(__name__)

@flask_app.route("/api/orders", methods=["POST", "OPTIONS"])
def api_create_order():
    if request.method == "OPTIONS": # CORS preflight
        return _build_cors_prelight_response()
    elif request.method == "POST": # The actual request following the preflight
        order = OrderModel.create(...) # Whatever.
        return _corsify_actual_response(jsonify(order.to_dict()))
    else
        raise RuntimeError("Weird - don't know how to handle method {}".format(request.method))

def _build_cors_prelight_response():
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add('Access-Control-Allow-Headers', "*")
    response.headers.add('Access-Control-Allow-Methods', "*")
    return response

def _corsify_actual_response(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

How can I select all options of multi-select select box on click?

Try this:

$('#select_all').click(function() {
    $('#countries option').prop('selected', true);
});

And here's a live demo.

Angular - POST uploaded file

your http service file:

import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router, 
  private http: Http, 
  private constants: Constants, 
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

call your function (Component file):

onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

your html code:

<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

Is there a CSS selector by class prefix?

It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):

div[class^="status-"], div[class*=" status-"]

Notice the space character in the second attribute selector. This picks up div elements whose class attribute meets either of these conditions:

  • [class^="status-"] — starts with "status-"

  • [class*=" status-"] — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class attributes dynamically).

Naturally, this also works in jQuery, as demonstrated here.

The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"] will match the following element, which may be undesirable:

<div id='D' class='foo-class foo-status-bar bar-class'></div>

If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.

If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status- prefix its own status class instead as Gumbo suggests.

current/duration time of html5 video?

HTML:

<video
    id="video-active"
    class="video-active"
    width="640"
    height="390"
    controls="controls">
    <source src="myvideo.mp4" type="video/mp4">
</video>
<div id="current">0:00</div>
<div id="duration">0:00</div>

JavaScript:

$(document).ready(function(){
  $("#video-active").on(
    "timeupdate", 
    function(event){
      onTrackedVideoFrame(this.currentTime, this.duration);
    });
});

function onTrackedVideoFrame(currentTime, duration){
    $("#current").text(currentTime); //Change #current to currentTime
    $("#duration").text(duration)
}

Notes:

Every 15 to 250ms, or whenever the MediaController's media controller position changes, whichever happens least often, the user agent must queue a task to fire a simple event named timeupdate at the MediaController.

http://www.w3.org/TR/html5/embedded-content-0.html#media-controller-position

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

The request failed or the service did not respond in a timely fashion?

Just disable the VIA protocol in sql server configuration manager

How can I escape white space in a bash loop list?

This is exceedingly tricky in standard Unix, and most solutions run foul of newlines or some other character. However, if you are using the GNU tool set, then you can exploit the find option -print0 and use xargs with the corresponding option -0 (minus-zero). There are two characters that cannot appear in a simple filename; those are slash and NUL '\0'. Obviously, slash appears in pathnames, so the GNU solution of using a NUL '\0' to mark the end of the name is ingenious and fool-proof.

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

Difference between jQuery parent(), parents() and closest() functions

closest() selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.

parent() selects one element up (single level up) the DOM tree.

parents() method is similar to parent() but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.

curl : (1) Protocol https not supported or disabled in libcurl

This is specifically mentioned in the libcurl FAQ entry "Protocol xxx not supported or disabled in libcurl".

For your pleasure I'm embedding the explanation here too:

When passing on a URL to curl to use, it may respond that the particular protocol is not supported or disabled. The particular way this error message is phrased is because curl doesn't make a distinction internally of whether a particular protocol is not supported (ie never got any code added that knows how to speak that protocol) or if it was explicitly disabled. curl can be built to only support a given set of protocols, and the rest would then be disabled or not supported.

Note that this error will also occur if you pass a wrongly spelled protocol part as in "htpt://example.com" or as in the less evident case if you prefix the protocol part with a space as in " http://example.com/".

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.

Swift - Integer conversion to Hours/Minutes/Seconds

NSTimeInterval is Double do do it with extension. Example:

extension Double {

    var formattedTime: String {

        var formattedTime = "0:00"

        if self > 0 {

            let hours = Int(self / 3600)
            let minutes = Int(truncatingRemainder(dividingBy: 3600) / 60)

            formattedTime = String(hours) + ":" + (minutes < 10 ? "0" + String(minutes) : String(minutes))
        }

        return formattedTime
    }
}

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Wrapping text inside input type="text" element HTML/CSS

That is the textarea's job - for multiline text input. The input won't do it; it wasn't designed to do it.

So use a textarea. Besides their visual differences, they are accessed via JavaScript the same way (use value property).

You can prevent newlines being entered via the input event and simply using a replace(/\n/g, '').

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

How to change the cursor into a hand when a user hovers over a list item?

CSS:

.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }
.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

You can also have the cursor be an image:

.img-cur {
   cursor: url(images/cursor.png), auto;
}

SQL "select where not in subquery" returns no results

Just off the top of my head...

select c.commonID, t1.commonID, t2.commonID
from Common c
     left outer join Table1 t1 on t1.commonID = c.commonID
     left outer join Table2 t2 on t2.commonID = c.commonID
where t1.commonID is null 
     and t2.commonID is null

I ran a few tests and here were my results w.r.t. @patmortech's answer and @rexem's comments.

If either Table1 or Table2 is not indexed on commonID, you get a table scan but @patmortech's query is still twice as fast (for a 100K row master table).

If neither are indexed on commonID, you get two table scans and the difference is negligible.

If both are indexed on commonID, the "not exists" query runs in 1/3 the time.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Working for me, I am using PHP 5.6. openssl extension should be enabled and while calling google map api verify_peer make false Below code is working for me.

<?php
$arrContextOptions=array(
    "ssl"=>array(
         "verify_peer"=>false,
         "verify_peer_name"=>false,
    ),
);  
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
      . $latitude
      . ","
      . $longitude
      . "&sensor=false&key="
      . Yii::$app->params['GOOGLE_API_KEY'];

$data = file_get_contents($url, false, stream_context_create($arrContextOptions));

echo $data;
?>

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

What does Ruby have that Python doesn't, and vice versa?

I would like to mention Python descriptor API that allows one customize object-to-attribute "communication". It is also noteworthy that, in Python, one is free to implement an alternative protocol via overriding the default given through the default implementation of the __getattribute__ method. Let me give more details about the aforementioned. Descriptors are regular classes with __get__, __set__ and/or __delete__ methods. When interpreter encounters something like anObj.anAttr, the following is performed:

  • __getattribute__ method of anObj is invoked
  • __getattribute__ retrieves anAttr object from the class dict
  • it checks whether abAttr object has __get__, __set__ or __delete__ callable objects
  • the context (i.e., caller object or class, and value, instead of the latter, if we have setter) is passed to the callable object
  • the result is returned.

As was mentioned, this is the default behavior. One is free to change the protocol by re-implementing __getattribute__.

This technique is lot more powerful than decorators.

SSH to Vagrant box in Windows?

Either

  1. In your cmd console type the following:

    set PATH=%PATH%;C:\Program Files (x86)\Git\bin
    

OR

  1. Permanently set the path in your system's environment variables:

    C:\Program Files (x86)\Git\bin;
    

How to dockerize maven project? and how many ways to accomplish it?

As a rule of thumb, you should build a fat JAR using Maven (a JAR that contains both your code and all dependencies).

Then you can write a Dockerfile that matches your requirements (if you can build a fat JAR you would only need a base os, like CentOS, and the JVM).

This is what I use for a Scala app (which is Java-based).

FROM centos:centos7

# Prerequisites.

RUN yum -y update
RUN yum -y install wget tar

# Oracle Java 7

WORKDIR /opt

RUN wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/7u71-b14/server-jre-7u71-linux-x64.tar.gz
RUN tar xzf server-jre-7u71-linux-x64.tar.gz
RUN rm -rf server-jre-7u71-linux-x64.tar.gz
RUN alternatives --install /usr/bin/java java /opt/jdk1.7.0_71/bin/java 1

# App

USER daemon

# This copies to local fat jar inside the image
ADD /local/path/to/packaged/app/appname.jar /app/appname.jar

# What to run when the container starts
ENTRYPOINT [ "java", "-jar", "/app/appname.jar" ]

# Ports used by the app
EXPOSE 5000

This creates a CentOS-based image with Java7. When started, it will execute your app jar.

The best way to deploy it is via the Docker Registry, it's like a Github for Docker images.

You can build an image like this:

# current dir must contain the Dockerfile
docker build -t username/projectname:tagname .

You can then push an image in this way:

docker push username/projectname # this pushes all tags

Once the image is on the Docker Registry, you can pull it from anywhere in the world and run it.

See Docker User Guide for more informations.

Something to keep in mind:

You could also pull your repository inside an image and build the jar as part of the container execution, but it's not a good approach, as the code could change and you might end up using a different version of the app without notice.

Building a fat jar removes this issue.

How to install pandas from pip on windows cmd?

install pip, securely download get-pip.py

Then run the following:

python get-pip.py

On Windows, to get Pandas running,follow the step given in following link

https://github.com/svaksha/PyData-Workshop-Sprint/wiki/windows-install-pandas

Android Endless List

May be a little late but the following solution happened very useful in my case. In a way all you need to do is add to your ListView a Footer and create for it addOnLayoutChangeListener.

http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)

For example:

ListView listView1 = (ListView) v.findViewById(R.id.dialogsList); // Your listView
View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.list_load_more, null); // Getting your layout of FooterView, which will always be at the bottom of your listview. E.g. you may place on it the ProgressBar or leave it empty-layout.
listView1.addFooterView(loadMoreView); // Adding your View to your listview 

...

loadMoreView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
         Log.d("Hey!", "Your list has reached bottom");
    }
});

This event fires once when a footer becomes visible and works like a charm.

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

In android studio: reduce minSDKversion. It will work...

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "healthcare.acceliant.trianz.com.myapplication"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
}

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

Python BeautifulSoup extract text between element

You can use .contents:

>>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
...     print hit.contents[6].strip()
... 
THIS IS MY TEXT

instanceof Vs getClass( )

getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:

class ParentClass{
}
public class SubClass extends ParentClass{
    public static void main(String []args){
        ParentClass parentClassInstance = new ParentClass();
        SubClass subClassInstance = new SubClass();
        if(subClassInstance instanceof ParentClass){
            System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
        }
        if(subClassInstance.getClass() != parentClassInstance.getClass()){
            System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
        }
    }
}

Outputs:

SubClass extends ParentClass. subClassInstance is instanceof ParentClass.

Different getClass() return results with subClassInstance and parentClassInstance.

Django MEDIA_URL and MEDIA_ROOT

Here are the changes I had to make to deliver PDFs for the django-publications app, using Django 1.10.6:

Used the same definitions for media directories as you, in settings.py:

MEDIA_ROOT = '/home/user/mysite/media/'

MEDIA_URL = '/media/'

As provided by @thisisashwanipandey, in the project's main urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and a modification of the answer provided by @r-allela, in settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # ... the rest of your context_processors goes here ...
                'django.template.context_processors.media',
            ],
         },
    },
]

What is the difference between Html.Hidden and Html.HiddenFor

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

Will result in:

<input id="Name" name="Name" type="hidden" value="Value">

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

And a model like:

public class MyModel 
{
    public string Name { get; set; }
}

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

copying all contents of folder to another folder using batch file?

I have written a .bat file to copy and paste file to a temporary folder and make it zip and transfer into a smb mount point, Hope this would help,

    @echo off
    if not exist "C:\Temp Backup\" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
    if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"
    if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    xcopy /s/e/q "C:\Source" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
   Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    "C:\Program Files (x86)\WinRAR\WinRAR.exe" a  "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\TELIUM"
    "C:\Program Files (x86)\WinRAR\WinRAR.exe" a  "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_Log_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    NET USE \\IP\IPC$ /u:IP\username password
    ROBOCOPY "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"  "\\IP\Backup Folder" /z /MIR /unilog+:"C:\backup_log_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log"
    NET USE \\172.20.10.103\IPC$ /D
    RMDIR /S /Q "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"

How to add image in a TextView text?

This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.

The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.

public class TextViewWithImages extends TextView {

    private static final String DRAWABLE = "drawable";
    /**
     * Regex pattern that looks for embedded images of the format: [img src=imageName/]
     */
    public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextViewWithImages(Context context) {
        super(context);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
        super.setText(spannable, BufferType.SPANNABLE);
    }

    private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
        final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
        addImages(context, spannable, lineHeight, colour);
        return spannable;
    }

    private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
        final Pattern refImg = Pattern.compile(PATTERN);
        boolean hasChanges = false;

        final Matcher matcher = refImg.matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end()) {
                    spannable.removeSpan(span);
                } else {
                    set = false;
                    break;
                }
            }
            final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
            final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
            if (set) {
                hasChanges = true;
                spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
                        matcher.start(),
                        matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }
        return hasChanges;
    }

    /**
     * Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
     * Works best with a white, square icon because of the colouring and resizing.
     *
     * @param context       The Android Context.
     * @param drawableResId A drawable resource Id.
     * @param size          The desired size (i.e. width and height) of the image icon in pixels.
     *                      Use the lineHeight of the TextView to make the image inline with the
     *                      surrounding text.
     * @param colour        The colour (careful: NOT a resource Id) to apply to the image.
     * @return An ImageSpan, aligned with the bottom of the text.
     */
    private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
        final Drawable drawable = context.getResources().getDrawable(drawableResId);
        drawable.mutate();
        drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
        drawable.setBounds(0, 0, size, size);
        return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
    }

}

How to use:

Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource); or if it's set in xml.

To embed a drawable icon named example.png, include the following string in the text: [img src=example/].

For example, a string resource might look like this:

<string name="string_resource">This [img src=example/] is an icon.</string>

jQuery post() with serialize and extra data

Try $.param

$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));

What is the difference between Left, Right, Outer and Inner Joins?

LEFT JOIN and RIGHT JOIN are types of OUTER JOINs.

INNER JOIN is the default -- rows from both tables must match the join condition.

Firebase cloud messaging notification not received by device

When you copying your device token, it might copying the space, double check you have copied the correct token

How to read .pem file to get private and public key

To get the public key you can simply do:

public static PublicKey getPublicKeyFromCertFile(final String certfile){

     return new X509CertImpl(new FileInputStream(new File(certfile))).getPublicKey();

To get the private key is trickier, you can:

public static PrivateKey getPrivateKeyFromKeyFile(final String keyfile){
    try {
        Process p;
        p = Runtime.getRuntime().exec("openssl pkcs8 -nocrypt -topk8 -inform PEM " +
                "-in " + keyfile + " -outform DER -out " + keyfile + ".der");

        p.waitFor();
        System.out.println("Command executed" + (p.exitValue() == 0 ? " successfully" : " with error" ));
    } catch ( IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(1);
    }

    PrivateKey myPrivKey = null;
    try {
        byte[] keyArray = Files.readAllBytes(Paths.get(keyfile + ".der"));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyArray);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        myPrivKey = keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e){
        e.printStackTrace();
        System.exit(1);
    }

    return myPrivKey;
}

What does <![CDATA[]]> in XML mean?

It escapes a string that cannot be passed to XML as usual:

Example:

The string contains "&" in it.

You can not:

<FL val="Company Name">Dolce & Gabbana</FL>

Therefore, you must use CDATA:

<FL val="Company Name"> <![CDATA["Dolce & Gabbana"]]> </FL>

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

Sort divs in jQuery based on attribute 'data-sort'?

Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

What is parsing in terms that a new programmer would understand?

Parsing is the process of analyzing text made of a sequence of tokens to determine its grammatical structure with respect to a given (more or less) formal grammar.

The parser then builds a data structure based on the tokens. This data structure can then be used by a compiler, interpreter or translator to create an executable program or library.

alt text
(source: wikimedia.org)

If I gave you an english sentence, and asked you to break down the sentence into its parts of speech (nouns, verbs, etc.), you would be parsing the sentence.

That's the simplest explanation of parsing I can think of.

That said, parsing is a non-trivial computational problem. You have to start with simple examples, and work your way up to the more complex.

Check if a number has a decimal place/is a whole number

Or you could just use this to find out if it is NOT a decimal:

string.indexOf(".") == -1;

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Convert List to Pandas Dataframe Column

For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.

There are Different Ways to Perform the Above Operation.

import pandas as pd

  1. pd.DataFrame({'Column_Name':Column_Data})
  • Column_Name : String
  • Column_Data : List Form
  1. Data = pd.DataFrame(Column_Data)

    Data.columns = ['Column_Name']

So, for the above mentioned issue, the code snippet is

import pandas as pd

Content = ['Thanks You',
           'Its fine no problem',
           'Are you sure']

Data = pd.DataFrame({'Text': Content})

Server.Mappath in C# classlibrary

You should reference System.Web and call:

  HttpContext.Current.Server.MapPath(...)

Service Reference Error: Failed to generate code for the service reference

As stated above, there are a couple of different problems possible. What we found is that the .DLL for the WCF library had been added as a reference to the client project. This, in turn, created problems with resolving the objects and thus caused the files to be "emptied" by code generation steps. While unchecking the use "Reuse Types..." can seem like an answer, it creates extra definitions of object types, which are proxies to the real types, in a new name space, which then causes all kinds of "compatibility" issues with the use of those types. Only if you really want to "hide" a type should you check this option.

Hiding the type would be appropriate when you don't want a "DLL" type dependency to "leak" into a project that you are trying to keep segregated from another. If the DLL for the WCF library project creeps into the client project references, then you will have this problem with all kinds of strange side effects since the type definitions are also in the DLL.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

How I do:

# Remove python2
sudo apt purge -y python2.7-minimal

# You already have Python3 but 
# don't care about the version 
sudo ln -s /usr/bin/python3 /usr/bin/python

# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip

# Confirm the new version of Python: 3
python --version

What are all possible pos tags of NLTK?

The book has a note how to find help on tag sets, e.g.:

nltk.help.upenn_tagset()

Others are probably similar. (Note: Maybe you first have to download tagsets from the download helper's Models section for this)

Adding integers to an int array

Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.

num[i] = s;
i++;

Invalid self signed SSL cert - "Subject Alternative Name Missing"

The Issue

As others have mentioned, the NET::ERR_CERT_COMMON_NAME_INVALID error is occurring because the generated certificate does not include the SAN (subjectAltName) field.

RFC2818 has deprecated falling back to the commonName field since May of 2000. The use of the subjectAltName field has been enforced in Chrome since version 58 (see Chrome 58 deprecations).

OpenSSL accepts x509v3 configuration files to add extended configurations to certificates (see the subjectAltName field for configuration options).


Bash Script

I created a self-signed-tls bash script with straightforward options to make it easy to generate certificate authorities and sign x509 certificates with OpenSSL (valid in Chrome using the subjectAltName field).

The script will guide you through a series of questions to include the necessary information (including the subjectAltName field). You can reference the README.md for more details and options for automation.

Be sure to restart chrome after installing new certificates.

chrome://restart

Other Resources

  • The Docker documentation has a great straightforward example for creating a self-signed certificate authority and signing certificates with OpenSSL.
  • cfssl is also a very robust tool that is widely used and worth checking out.

Convert char to int in C#

I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.

For ex:-

int s;
char i= '2';
s = (int) i;

Which maven dependencies to include for spring 3.0?

There was a really nice post on the Spring Blog from Keith Donald detailing howto Obtain Spring 3 Aritfacts with Maven, with comments detailing when you'd need each of the dependencies...

<!-- Shared version number properties -->
<properties>
    <org.springframework.version>3.0.0.RELEASE</org.springframework.version>
</properties>
<!-- Core utilities used by other modules.
    Define this if you use Spring Utility APIs 
    (org.springframework.core.*/org.springframework.util.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Expression Language (depends on spring-core)
    Define this if you use Spring Expression APIs 
    (org.springframework.expression.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Bean Factory and JavaBeans utilities (depends on spring-core)
    Define this if you use Spring Bean APIs 
    (org.springframework.beans.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Aspect Oriented Programming (AOP) Framework 
    (depends on spring-core, spring-beans)
    Define this if you use Spring AOP APIs 
    (org.springframework.aop.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Application Context 
    (depends on spring-core, spring-expression, spring-aop, spring-beans)
    This is the central artifact for Spring's Dependency Injection Container
    and is generally always defined-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Various Application Context utilities, including EhCache, JavaMail, Quartz, 
    and Freemarker integration
    Define this if you need any of these integrations-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Transaction Management Abstraction 
    (depends on spring-core, spring-beans, spring-aop, spring-context)
    Define this if you use Spring Transactions or DAO Exception Hierarchy
    (org.springframework.transaction.*/org.springframework.dao.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library 
    (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you use Spring's JdbcTemplate API 
    (org.springframework.jdbc.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA and iBatis.
    (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you need ORM (org.springframework.orm.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, 
    Castor, XStream, and XML Beans.
    (depends on spring-core, spring-beans, spring-context)
    Define this if you need OXM (org.springframework.oxm.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and 
    Portlet Environments 
    (depends on spring-core, spring-beans, spring-context)
    Define this if you use Spring MVC, or wish to use Struts, JSF, or another
    web framework with Spring (org.springframework.web.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Servlet Environments 
    (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Servlet Container such as 
    Apache Tomcat (org.springframework.web.servlet.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments 
    (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Portlet Container 
    (org.springframework.web.portlet.*)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc-portlet</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and TestNG
    This artifact is generally always defined with a 'test' scope for the 
    integration testing framework and unit testing stubs-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${org.springframework.version}</version>
    <scope>test</scope>
</dependency>

Can VS Code run on Android?

The accepted answer is correct as asked, below answers the opposite question of developing Android on VS Code.

Extensions

Ultimately you can automate building and running your app on a device emulator by adding the function below to your $PATH and running runDebugApp <module> <start activity> from the integrated terminal:

# run android app
# usage runDebugApp [module] [fully qualified start activity com.package/com.package.MainActivity]
function runDebugApp(){
  ./gradlew -offline :"$1":installDebug && adb shell am start "$2" && adb logcat -d > logcat.log
}

Referencing value in a closed Excel workbook using INDIRECT?

There is definitively no way to do this with standard formulas. However, a crazy sort of answer can be found here. It still avoids VBA, and it will allow you to get your result dynamically.

  1. First, make the formula that will generate your formula, but don't add the = at the beginning!

  2. Let us pretend that you have created this formula in cell B2 of Sheet1, and you would like the formula to be evaluated in column c.

  3. Now, go to the Formulas tab, and choose "Define Name". Give it the name myResult (or whatever you choose), and under Refers To, write =evaluate(Sheet1!$B2) (note the $)

  4. Finally, go to C2, and write =myResult. Drag down, and... voila!

If/else else if in Jquery for a condition

Iam confused a lot from morning whether it should be less than or greater than`

this can accept value less than "99999"

I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:

}elseif($("#seats").val() < 99999){
  alert("Not a valid Number");
}else{

You are saying if it's less than 99999, then it's not valid. You want to do the opposite:

}elseif($("#seats").val() >= 99999){
  alert("Not a valid Number");
}else{

Also, since you have $("#seats") twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:

var seats = $("#seats").val();

var error = null;

if (seats == "") {
    error = "Number is required";
} else {
    var seatsNum = parseInt(seats);
    
    if (isNaN(seatsNum)) {
        error = "Not a valid number";
    } else if (seatsNum >= 99999) {
        error = "Number must be less than 99999";
    }
}

if (error != null) {
    alert(error);
} else {
    alert("Valid number");
}

// If you really need setflag:
var setflag = error != null;

Here's a working sample: http://jsfiddle.net/LUY8q/

How to convert an NSTimeInterval (seconds) into minutes

Swift 2 version

extension NSTimeInterval {
            func toMM_SS() -> String {
                let interval = self
                let componentFormatter = NSDateComponentsFormatter()

                componentFormatter.unitsStyle = .Positional
                componentFormatter.zeroFormattingBehavior = .Pad
                componentFormatter.allowedUnits = [.Minute, .Second]
                return componentFormatter.stringFromTimeInterval(interval) ?? ""
            }
        }
    let duration = 326.4.toMM_SS()
    print(duration)    //"5:26"

Is there a way to do repetitive tasks at intervals?

If you want to stop it in any moment ticker

ticker := time.NewTicker(500 * time.Millisecond)
go func() {
    for range ticker.C {
        fmt.Println("Tick")
    }
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()

If you do not want to stop it tick:

tick := time.Tick(500 * time.Millisecond)
for range tick {
    fmt.Println("Tick")
}

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Which characters need to be escaped when using Bash?

There are two easy and safe rules which work not only in sh but also bash.

1. Put the whole string in single quotes

This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.

'I'\''m a s@fe $tring which ends in newline
'

sed command: sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"

2. Escape every char with a backslash

This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""

\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"

sed command: sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.

2b. More readable version of 2

There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-], which can be left unescaped to keep it more readable

I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"

sed command: LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.


Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.

Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.


(You can easily validate the rules by reading the POSIX spec for sh. For bash, check the reference manual linked by @AustinPhillips)

Hibernate: best practice to pull all lazy collections

You can use the @NamedEntityGraph annotation to your entity to create a loadable query that set which collections you want to load on your query.

The main advantage of this choice is that hibernate makes one single query to retrieve the entity and its collections and only when you choose to use this graph, like this:

Entity configuration

@Entity
@NamedEntityGraph(name = "graph.myEntity.addresesAndPersons", 
attributeNodes = {
    @NamedAttributeNode(value = "addreses"),
    @NamedAttributeNode(value = "persons"
})

Usage

public MyEntity findNamedGraph(Object id, String namedGraph) {
        EntityGraph<MyEntity> graph = em.getEntityGraph(namedGraph);

        Map<String, Object> properties = new HashMap<>();
        properties.put("javax.persistence.loadgraph", graph);

        return em.find(MyEntity.class, id, properties);
    }

Android - Share on Facebook, Twitter, Mail, ecc

Use this

Facebook - "com.facebook.katana"
Twitter - "com.twitter.android"
Instagram - "com.instagram.android"
Pinterest - "com.pinterest"



SharingToSocialMedia("com.facebook.katana")


public void SharingToSocialMedia(String application) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, bmpUri);

    boolean installed = checkAppInstall(application);
    if (installed) {
        intent.setPackage(application);
        startActivity(intent);
    } else {
        Toast.makeText(getApplicationContext(),
                "Installed application first", Toast.LENGTH_LONG).show();
    }

}


 private boolean checkAppInstall(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

How to force Chrome's script debugger to reload javascript?

You can always clear a specific file by doing the following:

  1. Open Dev Tools
  2. Click on the Sources tab
  3. Find your script / image / file
  4. Check the right panel to see if your file is up to date

If not:

  1. Right click the resource in the left panel and choose 'Open Link in New Tab'
  2. Force a reload of the resource with the methods above. (See @Bishoy Hanna's example)

This is very handy if you have resources that are in frames and CTRL+F5 is not force refreshing them.

How to convert nanoseconds to seconds using the TimeUnit enum?

You should write :

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.

And then:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

fatal: git-write-tree: error building trees

maybe there are some unmerged paths in your git repository that you have to resolve before stashing.

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

Check output of console.log(req) or console.log(req.headers);

Changing the interval of SetInterval while it's running

Use setTimeout() instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.

EDIT

Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.

function setDeceleratingTimeout(callback, factor, times)
{
    var internalCallback = function(tick, counter) {
        return function() {
            if (--tick >= 0) {
                window.setTimeout(internalCallback, ++counter * factor);
                callback();
            }
        }
    }(times, 0);

    window.setTimeout(internalCallback, factor);
};

// console.log() requires firebug    
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);

Create an ArrayList of unique values

HashSet hs = new HashSet();
                hs.addAll(arrayList);
                arrayList.clear();
                arrayList.addAll(hs);

How do you enable auto-complete functionality in Visual Studio C++ express edition?

I came across over the following post: http://blogs.msdn.com/b/raulperez/archive/2010/03/19/c-intellisense-options.aspx

The issue is that the "IntelliSense" option in c++ is disabled. This link explains about the IntelliSense database configuration and options.

After enabling the database you must close and reopen visual studio for autocomplete use 'ctrl'+'space'

git ignore vim temporary files

In myy case the temporary files are already commited by previous actions, so modifying .gitignore will not affect those commited files..., you have to git rm files_to_be_ignored --cache first, then commit, then DONE.

How do I ignore all files in a folder with a Git repository in Sourcetree?

In Sourcetree: Just ignore a file in specified folder. Sourcetree will ask if you like to ignore all files in that folder. It's perfect!

How do I do an initial push to a remote repository with Git?

You need to set up the remote repository on your client:

git remote add origin ssh://myserver.com/path/to/project

Escaping ampersand character in SQL string

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

How to increase the Java stack size?

The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

public class TT {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "TT", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("true recursion level was " + level);
                    System.err.println("reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();
        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

C# Return Different Types?

It's a sample using Generic Types.

public T GetAnything<T>() where T : class, new()
    => new T();

And you'll use this method calling this way:

var hello = GetAnything<Hello>();

In this case, you can use an interface to specify a type to pass as parameter.

public T GetAnything<T>() where T : ISomeInterface, new()
    => new T();

You must have a parameterless construtor in each class to use new() constraint.

Follow the full sample:

internal sealed class Program
{
    private static void Main(string[] args)
    {
        GetAnything<Hello>().Play();
        GetAnything<Radio>().Play();
        GetAnything<Computer>().Play();
    }

    private static T GetAnything<T>() where T : ISomeInterface, new()
        => new T();
}

internal interface ISomeInterface
{
    void Play();
}

internal sealed class Hello : ISomeInterface
{
    // parameterless constructor.
    public Hello() { }
    public void Play() => Console.WriteLine("Saying hello!");
}

internal sealed class Radio : ISomeInterface
{
    // parameterless constructor.
    public Radio() { }
    public void Play() => Console.WriteLine("Playing radio!");
}

internal sealed class Computer : ISomeInterface
{
    // parameterless constructor.
    public Computer() { }
    public void Play() => Console.WriteLine("Playing from computer!");
}

Is nested function a good approach when required by only one function?

It's just a principle about exposure APIs.

Using python, It's a good idea to avoid exposure API in outer space(module or class), function is a good encapsulation place.

It could be a good idea. when you ensure

  1. inner function is ONLY used by outer function.
  2. insider function has a good name to explain its purpose because the code talks.
  3. code cannot directly understand by your colleagues(or other code-reader).

Even though, Abuse this technique may cause problems and implies a design flaw.

Just from my exp, Maybe misunderstand your question.

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

Javascript to export html table to Excel

If you add:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

in the head of the document it will start working as expected:

<script type="text/javascript">
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()
</script>

Updated Fiddle Here.

java.net.URL read stream to byte[]

The content length is just a HTTP header. You cannot trust it. Just read everything you can from the stream.

Available is definitely wrong. It's just the number of bytes that can be read without blocking.

Another issue is your resource handling. Closing the stream has to happen in any case. try/catch/finally will do that.

Reading a text file in MATLAB line by line

You cannot read text strings with csvread. Here is another solution:

fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
    line = fgets(fid1); %# read line by line
    A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
    if A(2)<4.185 %# test the values
        fprintf(fid2,'%s',line); %# write the line to the new file
    end
end
fclose(fid1);
fclose(fid2);

How to get on scroll events?

Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

window:scroll

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {

}

or

<div (window:scroll)="onWindowScroll($event)">

scroll

@HostListener('scroll', ['$event'])
onElementScroll($event) {

}

or

<div (scroll)="onElementScroll($event)">

@HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

Examples

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

Apache HttpClient Android (Gradle)

I don't know why but (for now) httpclient can be compiled only as a jar into the libs directory in your project. HttpCore works fine when it is included from mvn like that:

dependencies {
      compile 'org.apache.httpcomponents:httpcore:4.4.3'
}

Bash if statement with multiple conditions throws an error

You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

As the script shows, you can pipe them with -a, e.g.:

if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
    ...
fi

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

Catching errors in Angular HttpClient

Let me please update the acdcjunior's answer about using HttpInterceptor with the latest RxJs features(v.6).

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpErrorResponse,
  HttpHandler,
  HttpEvent,
  HttpResponse
} from '@angular/common/http';

import { Observable, EMPTY, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
        }

        // If you want to return a new response:
        //return of(new HttpResponse({body: [{name: "Default value..."}]}));

        // If you want to return the error on the upper level:
        //return throwError(error);

        // or just return nothing:
        return EMPTY;
      })
    );
  }
}

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

Unit testing private methods in C#

“There is nothing called as standard or best practice, probably they are just popular opinions”.

Same holds true for this discussion as well.

enter image description here

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.

If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.

Section vs Article HTML5

I'd use <article> for a text block that is totally unrelated to the other blocks on the page. <section>, on the other hand, would be a divider to separate a document which have are related to each other.

Now, i'm not sure what you have in your videos, newsfeed etc, but here's an example (there's no REAL right or wrong, just a guideline of how I use these tags):

<article>
    <h1>People</h1>
    <p>text about people</p>
    <section>
        <h1>fat people</h1>
        <p>text about fat people</p>
    </section>
    <section>
        <h1>skinny people</p>
        <p>text about skinny people</p>
    </section>
</article>
<article>
    <h1>Cars</h1>
    <p>text about cars</p>
    <section>
        <h1>Fast Cars</h1>
        <p>text about fast cars</p>
    </section>
</article>

As you can see, the sections are still relevant to each other, but as long as they're inside a block that groups them. Sections DONT have to be inside articles. They can be in the body of a document, but i use sections in the body, when the whole document is one article.

e.g.

<body>
    <h1>Cars</h1>
    <p>text about cars</p>
    <section>
        <h1>Fast Cars</h1>
        <p>text about fast cars</p>
    </section>
</body>

Hope this makes sense.

Setting mime type for excel document

I was setting MIME type from .NET code as below -

File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

My application generates excel using OpenXML SDK. This MIME type worked -

vnd.openxmlformats-officedocument.spreadsheetml.sheet

ValueError: setting an array element with a sequence

In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:

print([i for i,x in enumerate(list) if len(x) != 560])

In my case, the length reference was 560.

How to change node.js's console font color?

This is an approach for Windows 10 (maybe for 7) and it changes the color scheme (theme) for cmd, npm terminal itself, not only console output for a particular app.

I found the working Windows plugin - Color Tool, which is presumably developed under Windows umbrella. A description is available at the link.

I added colortool directory into system environment path variable and now it is available whenever I start terminal (NodeJs command prompt, cmd).

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

How do I iterate over the words of a string?

Using std::stringstream as you have works perfectly fine, and do exactly what you wanted. If you're just looking for different way of doing things though, you can use std::find()/std::find_first_of() and std::string::substr().

Here's an example:

#include <iostream>
#include <string>

int main()
{
    std::string s("Somewhere down the road");
    std::string::size_type prev_pos = 0, pos = 0;

    while( (pos = s.find(' ', pos)) != std::string::npos )
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        std::cout << substring << '\n';

        prev_pos = ++pos;
    }

    std::string substring( s.substr(prev_pos, pos-prev_pos) ); // Last word
    std::cout << substring << '\n';

    return 0;
}

Checking on a thread / remove from list

Better way is to use Queue class: http://docs.python.org/library/queue.html

Look at the good example code in the bottom of documentation page:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

Breaking/exit nested for in vb.net

For i As Integer = 0 To 100
    bool = False
    For j As Integer = 0 To 100
        If check condition Then
            'if condition match
            bool = True
            Exit For 'Continue For
        End If
    Next
    If bool = True Then Continue For
Next

How can I print using JQuery

Hey If you want to print selected area or div ,Try This.

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Hope it helps you

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

try putting username in double quote "username", somehow that fixed for me.

Is there a RegExp.escape function in JavaScript?

XRegExp has an escape function:

XRegExp.escape('Escaped? <.>'); // -> 'Escaped\?\ <\.>'

More on: http://xregexp.com/api/#escape

Move the mouse pointer to a specific position?

You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.

For an example you can paste this code on the current page in your browser console (and refresh afterwards)

var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
    $(this).css({
        position: 'relative',
        left: (event.pageX - upvote_position.left - 22) + 'px',
        top: (event.pageY - upvote_position.top - 35) + 'px'
    });        
});

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

tl;dr

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

Details

I have a java.util.Date in the format yyyy-mm-dd

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.

java.time

The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();

2017-01-23

If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

How to use a calculated column to calculate another column in the same view

You have to include the expression for your calculated column:

SELECT  
ColumnA,  
ColumnB,  
ColumnA + ColumnB AS calccolumn1  
(ColumnA + ColumnB) / ColumnC AS calccolumn2

Using String Format to show decimal up to 2 places or simple integer

This worked for me!

String amount= "123.0000";
String.Format("{0:0.##}", amount);      // "123.00"

Compare integer in bash, unary operator expected

Your problem arises from the fact that $i has a blank value when your statement fails. Always quote your variables when performing comparisons if there is the slightest chance that one of them may be empty, e.g.:

if [ "$i" -ge 2 ] ; then
  ...
fi

This is because of how the shell treats variables. Assume the original example,

if [ $i -ge 2 ] ; then ...

The first thing that the shell does when executing that particular line of code is substitute the value of $i, just like your favorite editor's search & replace function would. So assume that $i is empty or, even more illustrative, assume that $i is a bunch of spaces! The shell will replace $i as follows:

if [     -ge 2 ] ; then ...

Now that variable substitutions are done, the shell proceeds with the comparison and.... fails because it cannot see anything intelligible to the left of -gt. However, quoting $i:

if [ "$i" -ge 2 ] ; then ...

becomes:

if [ "    " -ge 2 ] ; then ...

The shell now sees the double-quotes, and knows that you are actually comparing four blanks to 2 and will skip the if.

You also have the option of specifying a default value for $i if $i is blank, as follows:

if [ "${i:-0}" -ge 2 ] ; then ...

This will substitute the value 0 instead of $i is $i is undefined. I still maintain the quotes because, again, if $i is a bunch of blanks then it does not count as undefined, it will not be replaced with 0, and you will run into the problem once again.

Please read this when you have the time. The shell is treated like a black box by many, but it operates with very few and very simple rules - once you are aware of what those rules are (one of them being how variables work in the shell, as explained above) the shell will have no more secrets for you.

How do I call a JavaScript function on page load?

Another way to do this is by using event listeners, here how you use them:

document.addEventListener("DOMContentLoaded", function() {
  you_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

I see you have all the settings right. You just need to end the local web server and start it again with

php artisan serve

Everytime you change your .env file, you need tor restart the server for the new options to take effect.

Or clear and cache your configuration with

php artisan config:cache

How to specify different Debug/Release output directories in QMake .pro file

I use the same method suggested by chalup,

ParentDirectory = <your directory>

RCC_DIR = "$$ParentDirectory\Build\RCCFiles"
UI_DIR = "$$ParentDirectory\Build\UICFiles"
MOC_DIR = "$$ParentDirectory\Build\MOCFiles"
OBJECTS_DIR = "$$ParentDirectory\Build\ObjFiles"

CONFIG(debug, debug|release) { 
    DESTDIR = "$$ParentDirectory\debug"
}
CONFIG(release, debug|release) { 
    DESTDIR = "$$ParentDirectory\release"
}

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Create an xml file any name (say progressBar.xml) in drawable and add <color name="silverGrey">#C0C0C0</color> in color.xml.

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="720" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="6"
        android:useLevel="false" >
        <size
            android:height="200dip"
            android:width="300dip" />

        <gradient
            android:angle="0"
            android:endColor="@color/silverGrey"
            android:startColor="@android:color/transparent"
            android:type="sweep"
            android:useLevel="false" />

    </shape>
</rotate>

Now in your xml file where you have your listView add this code:

 <ListView
            android:id="@+id/list_form_statusMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>

        <ProgressBar
            android:id="@+id/progressBar"
            style="@style/CustomAlertDialogStyle"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_centerInParent="true"
            android:layout_gravity="center_horizontal"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/circularprogress"
            android:visibility="gone"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>

In AsyncTask in the method:

@Override
protected void onPreExecute()
{
    progressbar_view.setVisibility(View.VISIBLE);

    // your code
}

And in onPostExecute:

@Override
protected void onPostExecute(String s)
{
    progressbar_view.setVisibility(View.GONE);

    //your code
}

How to disable scrolling in UITableView table when the content fits on the screen

I think you want to set

tableView.alwaysBounceVertical = NO;

What CSS selector can be used to select the first div within another div

The MOST CORRECT answer to your question is...

#content > div:first-of-type { /* css */ }

This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)

Another option:

#content > div:nth-of-type(1) { /* css */ }

Wait for page load in Selenium

I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like waitForElementByID(String id) and waitForElemetVisibleByClass(String className), etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on.

For example,

In my test class:

driverWait.until(textIsPresent("expectedText");

In my test class parent:

protected Predicate<WebDriver> textIsPresent(String text){
    final String t = text;
    return new Predicate<WebDriver>(){
        public boolean apply(WebDriver driver){
            return isTextPresent(t);
        }
    };
}

protected boolean isTextPresent(String text){
    return driver.getPageSource().contains(text);
}

Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods.

In this example, the parent class defined and initiated the WebDriver driver and the WebDriverWait driverWait.

I hope this helps.

Dropping Unique constraint from MySQL table

  1. First delete table

  2. go to SQL

Use this code:

CREATE  TABLE service( --tablename 
  `serviceid` int(11) NOT NULL,--columns
  `customerid` varchar(20) DEFAULT NULL,--columns
  `dos` varchar(30) NOT NULL,--columns
  `productname` varchar(150) NOT NULL,--columns
  `modelnumber` bigint(12) NOT NULL,--columns
  `serialnumber` bigint(20) NOT NULL,--columns
  `serviceby` varchar(20) DEFAULT NULL--columns
)
--INSERT VALUES
INSERT INTO `service` (`serviceid`, `customerid`, `dos`, `productname`, `modelnumber`, `serialnumber`, `serviceby`) VALUES
(1, '1', '12/10/2018', 'mouse', 1234555, 234234324, '9999'),
(2, '09', '12/10/2018', 'vhbgj', 79746385, 18923984, '9999'),
(3, '23', '12/10/2018', 'mouse', 123455534, 11111123, '9999'),
(4, '23', '12/10/2018', 'mouse', 12345, 84848, '9999'),
(5, '546456', '12/10/2018', 'ughg', 772882, 457283, '9999'),
(6, '23', '12/10/2018', 'keyboard', 7878787878, 22222, '1'),
(7, '23', '12/10/2018', 'java', 11, 98908, '9999'),
(8, '128', '12/10/2018', 'mouse', 9912280626, 111111, '9999'),
(9, '23', '15/10/2018', 'hg', 29829354, 4564564646, '9999'),
(10, '12', '15/10/2018', '2', 5256, 888888, '9999');
--before droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  unique`modelnumber` (`modelnumber`),
  ADD  unique`serialnumber` (`serialnumber`),
  ADD unique`modelnumber_2` (`modelnumber`);
--after droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  modelnumber` (`modelnumber`),
  ADD  serialnumber` (`serialnumber`),
  ADD modelnumber_2` (`modelnumber`);

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

How to get the difference between two arrays of objects in JavaScript

You could use Array.prototype.filter() in combination with Array.prototype.some().

Here is an example (assuming your arrays are stored in the variables result1 and result2):

//Find values that are in result1 but not in result2
var uniqueResultOne = result1.filter(function(obj) {
    return !result2.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Find values that are in result2 but not in result1
var uniqueResultTwo = result2.filter(function(obj) {
    return !result1.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);

Why doesn't JavaScript support multithreading?

Traditionally, JS was intended for short, quick-running pieces of code. If you had major calculations going on, you did it on a server - the idea of a JS+HTML app that ran in your browser for long periods of time doing non-trivial things was absurd.

Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads...

@marcio:

Why is that a reason not to implement multi-threading in Javascript? Programmers can do whatever they want with the tools they have.

So then, let's not give them tools that are so easy to misuse that every other website i open ends up crashing my browser. A naive implementation of this would bring you straight into the territory that caused MS so many headaches during IE7 development: add-on authors played fast and loose with the threading model, resulting in hidden bugs that became evident when object lifecycles changed on the primary thread. BAD. If you're writing multi-threaded ActiveX add-ons for IE, i guess it comes with the territory; doesn't mean it needs to go any further than that.

When and how should I use a ThreadLocal variable?

Two use cases where threadlocal variable can be used -
1- When we have a requirement to associate state with a thread (e.g., a user ID or Transaction ID). That usually happens with a web application that every request going to a servlet has a unique transactionID associated with it.

// This class will provide a thread local variable which
// will provide a unique ID for each thread
class ThreadId {
    // Atomic integer containing the next thread ID to be assigned
    private static final AtomicInteger nextId = new AtomicInteger(0);

    // Thread local variable containing each thread's ID
    private static final ThreadLocal<Integer> threadId =
        ThreadLocal.<Integer>withInitial(()-> {return nextId.getAndIncrement();});

    // Returns the current thread's unique ID, assigning it if necessary
    public static int get() {
        return threadId.get();
    }
}

Note that here the method withInitial is implemented using lambda expression.
2- Another use case is when we want to have a thread safe instance and we don't want to use synchronization as the performance cost with synchronization is more. One such case is when SimpleDateFormat is used. Since SimpleDateFormat is not thread safe so we have to provide mechanism to make it thread safe.

public class ThreadLocalDemo1 implements Runnable {
    // threadlocal variable is created
    private static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue(){
            System.out.println("Initializing SimpleDateFormat for - " + Thread.currentThread().getName() );
            return new SimpleDateFormat("dd/MM/yyyy");
        }
    };

    public static void main(String[] args) {
        ThreadLocalDemo1 td = new ThreadLocalDemo1();
        // Two threads are created
        Thread t1 = new Thread(td, "Thread-1");
        Thread t2 = new Thread(td, "Thread-2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        System.out.println("Thread run execution started for " + Thread.currentThread().getName());
        System.out.println("Date formatter pattern is  " + dateFormat.get().toPattern());
        System.out.println("Formatted date is " + dateFormat.get().format(new Date()));
    } 

}

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

One millionaire has N cars. You want to get all (4) wheels.

One (1) query loads all the cars, but for each (N) car a separate query is submitted for loading wheels.

Costs:

Assume indexes fit into ram.

1 + N query parsing and planing + index searching AND 1 + N + (N * 4) plate access for loading payload.

Assume indexes don't fit into ram.

Additional costs in worst case 1 + N plate accesses for loading index.

Summary

Bottle neck is plate access (ca. 70 times per second random access on hdd) An eager join select would also access the plate 1 + N + (N * 4) times for payload. So if the indexes fit into ram - no problem, its fast enough because only ram operations involved.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js

Laravel view not found exception

As @deanchiu said it may happen when you move the whole project to another path or server.

But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.

> php artisan route:clear
> php artisan config:clear

Is it possible in Java to access private fields via reflection

Yes.

  Field f = Test.class.getDeclaredField("str");
  f.setAccessible(true);//Very important, this allows the setting to work.
  String value = (String) f.get(object);

Then you use the field object to get the value on an instance of the class.

Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get method

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

How do I make WRAP_CONTENT work on a RecyclerView

UPDATE 02.07.2020
This method may prevent recycling and should not be used on large data sets.

UPDATE 05.07.2019

If you are using RecyclerView inside a ScrollView, just change ScrollView to androidx.core.widget.NestedScrollView. Inside this view there is no need to pack RecyclerView inside a RelativeLayout.

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- other views -->

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- other views -->

    </LinearLayout>

</androidx.core.widget.NestedScrollView>

Finally found the solution for this problem.

All you need to do is wrap the RecyclerView in a RelativeLayout. Maybe there are other Views which may also work.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

How to set selectedIndex of select element using display text?

Try this:

function SelectAnimal()
{
    var animals = document.getElementById('Animals');
    var animalsToFind = document.getElementById('AnimalToFind');
    // get the options length
    var len = animals.options.length;
    for(i = 0; i < len; i++)
    {
      // check the current option's text if it's the same with the input box
      if (animals.options[i].innerHTML == animalsToFind.value)
      {
         animals.selectedIndex = i;
         break;
      }     
    }
}

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

ls command: how can I get a recursive full-path listing, one line per file?

A lot of answers I see. This is mine, and I think quite useful if you are working on Mac.

I'm sure you know there are some "bundle" files (.app, .rtfd, .workflow, and so on). And looking at Finder's window they seem single files. But they are not. And $ ls or $ find see them as directories... So, unless you need list their contents as well, this works for me:

find . -not -name ".*" -not -name "." | egrep -v "\.rtfd/|\.app/|\.lpdf/|\.workflow/"

Of course this is for the working dir, and you could add other bundles' extensions (but always with a / after them). Or any other extensions if not bundle's without the /.

Rather interesting the ".lpdf/" (multilingual pdf). It has normal ".pdf" extension (!!) or none in Finder. This way you get (or it just counts 1 file) for this pdf and not a bunch of stuff…

How to sort findAll Doctrine's method?

Look at the Doctrine API source-code :

class EntityRepository{
  ...
  public function findAll(){
    return $this->findBy(array());
  }
  ...
}

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Both forms of the meta charset declaration are equivalent and should work the same across browsers. But, there are a few things you need to remember when declaring your web files character-set as UTF-8:

  1. Save your file(s) in UTF-8 encoding without the byte-order mark (BOM).
  2. Declare the encoding in your HTML files using meta charset (like above).
  3. Your web server must serve your files, declaring the UTF-8 encoding in the Content-Type HTTP header.

Apache servers are configured to serve files in ISO-8859-1 by default, so you need to add the following line to your .htaccess file:

AddDefaultCharset UTF-8

This will configure Apache to serve your files declaring UTF-8 encoding in the Content-Type response header, but your files must be saved in UTF-8 (without BOM) to begin with.

Notepad cannot save your files in UTF-8 without the BOM. A free editor that can is Notepad++. On the program menu bar, select "Encoding > Encode in UTF-8 without BOM". You can also open files and re-save them in UTF-8 using "Encoding > Convert to UTF-8 without BOM".

More on the Byte Order Mark (BOM) at Wikipedia.

How to set up file permissions for Laravel?

I had the following configuration:

  • NGINX (running user: nginx)
  • PHP-FPM

And applied permissions correctly as @bgies suggested in the accepted answer. The problem in my case was the php-fpm's configured running user and group which was originally apache.

If you're using NGINX with php-fpm, you should open php-fpm's config file:

nano /etc/php-fpm.d/www.config

And replace user and group options' value with one NGINX is configured to work with; in my case, both were nginx:

... ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user's group ; will be used. ; RPM: apache Choosed to be able to access some dir as httpd user = nginx ; RPM: Keep a group allowed to write in log dir. group = nginx ...

Save it and restart nginx and php-fpm services.

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Vs Code
  2. Go to view
  3. Click on terminal to open a terminal in VS Code
  4. Copy the link for your existing repository from your GitHub page.
  5. Type “git clone” and paste the link in addition i.e “git clone https://github.com/...”
  6. This will open the repository in your Vs Code Editor.

Method has the same erasure as another method in type

This is because Java Generics are implemented with Type Erasure.

Your methods would be translated, at compile time, to something like:

Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)

void add(Set ii);
void add(Set ss);

Both methods have the same signature without the type parameters, hence the error.

jquery json to string?

The best way I have found is to use jQuery JSON

JAVA_HOME is set to an invalid directory:

On Window 10, the problem was with the semicolon ;.

Go to edit the system environment variables and delete the semicolon at the end of JAVA_HOME value C:\Program Files\Java\jdk1.8.0_144

In other words, convert this C:\Program Files\Java\jdk1.8.0_12; to C:\Program Files\Java\jdk1.8.0_12

You might have to delete your entry in the Windows Dialog and create a new one. If you ever had multiple entries and get the bigger Form view, Windows automatically inserts a ; at the end of each entry, even if you only have one entry left.

regular expression for finding 'href' value of a <a> link

Try this :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var res = Find(html);
        }

        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }

        public struct LinkItem
        {
            public string Href;
            public string Text;

            public override string ToString()
            {
                return Href + "\n\t" + Text;
            }
        }

    }  

Input:

  string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> "; 

Result:

[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}

C# Scraping HTML Links

Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.

Edited

Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)

 public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            List<string> href = new List<string>();
            foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
            {
                href.Add(el.GetAttribute("href"));
            }
        }

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

public static final String tryClob2String(final Object value)
{
    final Clob clobValue = (Clob) value;
    String result = null;

    try
    {
        final long clobLength = clobValue.length();

        if (clobLength < Integer.MIN_VALUE || clobLength > Integer.MAX_VALUE)
        {
            log.debug("CLOB size too big for String!");
        }
        else
        {
            result = clobValue.getSubString(1, (int) clobValue.length());
        }
    }
    catch (SQLException e)
    {
        log.error("tryClob2String ERROR: {}", e);
    }
    finally
    {
        if (clobValue != null)
        {
            try
            {
                clobValue.free();
            }
            catch (SQLException e)
            {
                log.error("CLOB FREE ERROR: {}", e);
            }
        }
    }

    return result;
}

cut or awk command to print first field of first row

Specify NR if you want to capture output from selected rows:

awk 'NR==1{print $1}' /etc/*release

An alternative (ugly) way of achieving the same would be:

awk '{print $1; exit}'

An efficient way of getting the first string from a specific line, say line 42, in the output would be:

awk 'NR==42{print $1; exit}'

How to clear https proxy setting of NPM?

In my case (Linux Mint 16 based on Ubuntu), I had to:

  1. npm config delete https-proxy, and also

  2. clear the https_proxy Bash environment parameter — oddly enough, although I cannot find this behavior documented anywhere, npm fallbacks to https_proxy:

    $ http_proxy='' https_proxy='' npm config get https-proxy
    null
    $ http_proxy='' xxhttps_proxy='' npm config get https-proxy
    https://1.2.3.4:8080
    

css label width not taking effect

I believe labels are inline, and so they don't take a width. Maybe try using "display: block" and going from there.

How to write to files using utl_file in oracle

Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:

declare 
  fHandle  UTL_FILE.FILE_TYPE;
begin
  fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');

  UTL_FILE.PUT(fHandle, 'This is the first line');
  UTL_FILE.PUT(fHandle, 'This is the second line');
  UTL_FILE.PUT_LINE(fHandle, 'This is the third line');

  UTL_FILE.FCLOSE(fHandle);
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || '  SQLERRM=' || SQLERRM);
    RAISE;
end;

The output from this looks like:

This is the first lineThis is the second lineThis is the third line

Share and enjoy.

How do I clear all variables in the middle of a Python script?

The following sequence of commands does remove every name from the current module:

>>> import sys
>>> sys.modules[__name__].__dict__.clear()

I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).

Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:

>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
...   if n[0]!='_': delattr(this, n)
... 
>>>

This sequence leaves alone names that are private or magical, including the __builtins__ special name which houses all built-in names. So, built-ins still work -- for example:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>> 

As you see, name n (the control variable in that for) also happens to stick around (as it's re-bound in the for clause every time through), so it might be better to name that control variable _, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _ is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).

Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

JavaScript single line 'if' statement - best syntax, this alternative?

As has already been stated, you can use:

&& style

lemons && document.write("foo gave me a bar");  

or

bracket-less style

if (lemons) document.write("foo gave me a bar");

short-circuit return

If, however, you wish to use the one line if statement to short-circuit a function though, you'd need to go with the bracket-less version like so:

if (lemons) return "foo gave me a bar";

as

lemons && return "foo gave me a bar"; // does not work!

will give you a SyntaxError: Unexpected keyword 'return'

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

How to run Unix shell script from Java code?

for linux use

public static void runShell(String directory, String command, String[] args, Map<String, String> environment)
{
    try
    {
        if(directory.trim().equals(""))
            directory = "/";

        String[] cmd = new String[args.length + 1];
        cmd[0] = command;

        int count = 1;

        for(String s : args)
        {
            cmd[count] = s;
            count++;
        }

        ProcessBuilder pb = new ProcessBuilder(cmd);

        Map<String, String> env = pb.environment();

        for(String s : environment.keySet())
            env.put(s, environment.get(s));

        pb.directory(new File(directory));

        Process process = pb.start();

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedWriter outputReader = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        int exitValue = process.waitFor();

        if(exitValue != 0) // has errors
        {
            while(errReader.ready())
            {
                LogClass.log("ErrShell: " + errReader.readLine(), LogClass.LogMode.LogAll);
            }
        }
        else
        {
            while(inputReader.ready())
            {
                LogClass.log("Shell Result : " + inputReader.readLine(), LogClass.LogMode.LogAll);
            }
        }
    }
    catch(Exception e)
    {
        LogClass.log("Err: RunShell, " + e.toString(), LogClass.LogMode.LogAll);
    }
}

public static void runShell(String path, String command, String[] args)
{
    try
    {
        String[] cmd = new String[args.length + 1];

        if(!path.trim().isEmpty())
            cmd[0] = path + "/" + command;
        else
            cmd[0] = command;

        int count = 1;

        for(String s : args)
        {
            cmd[count] = s;
            count++;
        }

        Process process = Runtime.getRuntime().exec(cmd);

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedWriter outputReader = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        int exitValue = process.waitFor();

        if(exitValue != 0) // has errors
        {
            while(errReader.ready())
            {
                LogClass.log("ErrShell: " + errReader.readLine(), LogClass.LogMode.LogAll);
            }
        }
        else
        {
            while(inputReader.ready())
            {
                LogClass.log("Shell Result: " + inputReader.readLine(), LogClass.LogMode.LogAll);
            }
        }
    }
    catch(Exception e)
    {
        LogClass.log("Err: RunShell, " + e.toString(), LogClass.LogMode.LogAll);
    }
}

and for usage;

ShellAssistance.runShell("", "pg_dump", new String[]{"-U", "aliAdmin", "-f", "/home/Backup.sql", "StoresAssistanceDB"});

OR

ShellAssistance.runShell("", "pg_dump", new String[]{"-U", "aliAdmin", "-f", "/home/Backup.sql", "StoresAssistanceDB"}, new Hashmap<>());

How to extract file name from path?

Here's an alternative solution without code. This VBA works in the Excel Formula Bar:

To extract the file name:

=RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"\","~",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

To extract the file path:

=MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))))

move div with CSS transition

This may be the good solution for you: change the code like this very little change

.box{
    position: relative; 
}
.box:hover .hidden{
    opacity: 1;
    width:500px;
}
.box .hidden{
    background: yellow;
    height: 334px; 
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    opacity: 0;
    transition: all 1s ease;
}

See demo here

Identify duplicates in a List

I took Sebastian's answer and added a keyExtractor to it -

    private <U, T> Set<T> findDuplicates(Collection<T> collection, Function<? super T,? extends U> keyExtractor) {
        Map<U, T> uniques = new HashMap<>(); // maps unique keys to corresponding values
        return collection.stream()
            .filter(e -> uniques.put(keyExtractor.apply(e), e) != null)
            .collect(Collectors.toSet());
    }

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

How to rollback just one step using rake db:migrate

For starters

rake db:rollback will get you back one step

then

rake db:rollback STEP=n

Will roll you back n migrations where n is the number of recent migrations you want to rollback.

More references here.

How to split a line into words separated by one or more spaces in bash?

do this

while read -r line
do
  set -- $line
  echo "$1 $2"
done <"file"

$1, $2 etc will be your 1st and 2nd splitted "fields". use $@ to get all values..use $# to get length of the "fields".

Make Vim show ALL white spaces as a character

all of the answers above try to make spaces visible from within vim. If you really insist on having visible spaces as dots, there's another approach...

If it cannot be done in vim, change your font entirely. I copied the Ubuntu One Mono font and edited it using FontForge. Remember to change the font's fullname, family, preferred family, compatible full (in FontFoge it's under TTF Names in the font info), in order to have it as a separate font. Simply edit the space character to have a dot in the middle and save the font to ~/.fonts Now you can use it for your gvim or the entire terminal... I copied the "!" character, removed the line and moved the dot to the middle. It took a little more than 5 minutes...

Note: changing the space character (0x20) results in the inconvenience of having dots on the entire vim screen... (but it will separate the spaces from tabs...)

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I have written an add-in for SSMS and this problem is fixed there. You can use one of 2 ways:

you can use "Copy current cell 1:1" to copy original cell data to clipboard:

http://www.ssmsboost.com/Features/ssms-add-in-copy-results-grid-cell-contents-line-with-breaksCopy original cell contents

Or, alternatively, you can open cell contents in external text editor (notepad++ or notepad) using "Cell visualizers" feature: http://www.ssmsboost.com/Features/ssms-add-in-results-grid-visualizers

(feature allows to open contents of field in any external application, so if you know that it is text - you use text editor to open it. If contents is binary data with picture - you select view as picture. Sample below shows opening a picture):SSMS Results grid visualizers

Verify if file exists or not in C#

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.

Dynamically Add Images React Webpack

UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.

With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:

This will NOT work. :

const myImg = './cute.jpg'
<img src={require(myImg)} />

To fix this, just use template strings instead :

const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />

webpack.config.js :

var HtmlWebpackPlugin =  require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry : './src/app.js',
  output : {
    path : './dist',
    filename : 'app.bundle.js'
  },
  plugins : [
  new ExtractTextWebpackPlugin('app.bundle.css')],
  module : {
    rules : [{
      test : /\.css$/,
      use : ExtractTextWebpackPlugin.extract({
        fallback : 'style-loader',
        use: 'css-loader'
      })
    },{
      test: /\.js$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015']
      }
    },{
      test : /\.jpg$/,
      exclude: /(node_modules)/,
      loader : 'file-loader'
    }]
  }
}

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

Change Text Color of Selected Option in a Select Box

CSS
select{
  color:red;
 }

HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
 <option>Select Your Option</option>
 <option value="">INDIA</option>
 <option value="">USA</option>
</select>

The above code will change the colour of text on click of the select box.

and if you want every option different colour, give separate class or id to all options.

Submit two forms with one button

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

Mean of a column in a data frame, given the column's name

Use summarise in the dplyr package:

library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))

note: dplyr supports both summarise and summarize.

Spring JPA selecting specific columns

Using Native Query:

Query query = entityManager.createNativeQuery("SELECT projectId, projectName FROM projects");
List result = query.getResultList();

Server is already running in Rails

Probably you suspended the server by: ^Z.

The four digital number that vim C:/Sites/folder/Pids/Server.pidsoutputs is the process id.

You should kill -9 processid, replacing the process id with the 4 numbers that vim (or other editor) outputed.

How to run vi on docker container?

If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.

Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.

  1. Copy myFile.xml in your local filesystem and make necessary changes.
  2. Create a file named 'Dockerfile' with the following content-
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/

Then build your own docker image with docker build -t docker-repo:v-x.x.x .

Then use your newly build docker image.

Using Java 8's Optional with Stream::flatMap

A slightly shorter version using reduce:

things.stream()
  .map(this::resolve)
  .reduce(Optional.empty(), (a, b) -> a.isPresent() ? a : b );

You could also move the reduce function to a static utility method and then it becomes:

  .reduce(Optional.empty(), Util::firstPresent );

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

Download JAVA SE with JDK

  1. Download jdk from Oracle website: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Unzip the exe. For example: jdk-8u5-windows-x64.exe
  3. Unzip the following file: tools.zip (found under the unzipped folder) to the desired JAVA_HOME.
  4. Update the JAVA_HOME environment variable to point to your desired path.

Tested for version: jdk-7u60-windows-x64.exe, jdk-7u60-windows-x64.exe

Download JAVA EE with JDK

  1. Download jdk from Oracle website: http://www.oracle.com/technetwork/java/javaee/downloads/index.html
  2. Unzip the exe. For example: jdk-7u55-windows-x64.exe
  3. Unzip the following file: Product\Packages\jdk.zip (found under the unzipped folder) to the desired JAVA_HOME.
  4. Update the JAVA_HOME environment variable to point to your desired path.

Tested for version: jdk-7u55-windows-x64.exe