Programs & Examples On #Google street view

Google Street View is a technology featured in Google Maps and Google Earth that provides panoramic views from positions along many streets in the world. It was launched on May 25, 2007, in several cities in the United States, and has since expanded to include cities and rural areas worldwide.

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

JSON library for C#

To answer your first question, Microsoft does ship a DataContractJsonSerializer: see msdn How to: Serialize and Deserialize JSON Data

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

How to SSH to a VirtualBox guest externally through a host?

You can also use a Bridged Network (or "Bridge Adapter", in newer versions) in network settings. This will put your VM in a VLAN with your machine. So you can just ssh into the VM like this.

ssh user@IP_OF_VM

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {

You have to use the table structure for correct results.

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:


And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    this.checkout = function() { ... };

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    checkout()    { ... }

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    static checkout()    { ... }

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:


Static member functions are called using the class name:


The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 

Where is HttpContent.ReadAsAsync?

It looks like it is an extension method (in System.Net.Http.Formatting):

HttpContentExtensions Class


PM> install-package Microsoft.AspNet.WebApi.Client

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;

    public String getFullName() {
        return full;

    public String getAbbreviatedName() {
        return abbr;

    public boolean isOriginalColony(){
        return originalColony;

How to write log file in c#?

Very convenient tool for logging is

You can also make something of themselves less (more) powerful. You can use (v = vs.110). Aspx

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');

var base64String = base64Encode('test.jpg');

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Doesn't look like you got an answer but this problem can also creep up if you're passing null ID's into your JPA Predicate.

For instance.

If I did a query on Cats to get back a list. Which returns 3 results.

List catList;

I then iterate over that List of cats and store a foriegn key of cat perhaps leashTypeId in another list.

List<Integer> leashTypeIds= new ArrayList<>();

for(Cats c : catList){


If any of the Cats in catList have a null leashTypeId it will throw this error when you try to query your DB.

(Just realized I am posting on a 5 year old thread, perhaps someone will find this useful)

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to ensure your use cases are sufficiently robust to represent usage requirements for the system you're building.

They involve:

  1. Actors
  2. Use Cases
  3. Entities
  4. Boundaries
  5. Controls

Whereas the Model-View-Controller pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:

UML notation

Entities (model)
Objects representing system data, often from the domain model.

Boundaries (view/service collaborator)
Objects that interface with system actors (e.g. a user or external service). Windows, screens and menus are examples of boundaries that interface with users.

Controls (controller)
Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.

Four rules apply to their communication:

  1. Actors can only talk to boundary objects.
  2. Boundary objects can only talk to controllers and actors.
  3. Entity objects can only talk to controllers.
  4. Controllers can talk to boundary objects and entity objects, and to other controllers, but not to actors

Communication allowed:

         Entity    Boundary   Control
Entity     X                     X
Boundary                         X
Control    X          X          X

"Integer number too large" error message for 600851475143

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

WCF on IIS8; *.svc handler mapping doesn't work

For Windows 8 machines there is no "Server Manager" application (at least I was not able to find it).

Though I was able to resolve the problem. I'm not sure in which sequence I did the following operations but looks like one/few of following actions help:

  1. Turn ON the following on 'Turn Windows Features on or off' a) .Net Framework 3.5 - WCF HTTP Activation and Non-Http Activation b) all under WCF Services (as specified in one of the answers to this question)

  2. executed "ServiceModelReg.exe –i" in "%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\" folder

  3. Registered ASP.NET 2.0 via two commands ( in folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727):

    aspnet_regiis -ga "NT AUTHORITY\NETWORK SERVICE" aspnet_regiis -iru

  4. Restarted PC... it looks like as a result as actions ## 3 and 4 something got broken in my ASP.NET configuration

  5. Repeat action #2

  6. Install two other options from the "Programs and Features": .Net Framework 4.5 Advanced Services. I checked both sub options: ASP.NET 4.5 and WCF services

  7. Restart App Pool.

Sequence is kind of crazy, but that helped to me and probably will help to other

SOAP PHP fault parsing WSDL: failed to load external entity?

The problem may lie in you don't have enabled openssl extention in your php.ini file

go to your php.ini file end remove ; in line where extension=openssl is

Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

You have to disable all triggers and constraints first.


EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"

After that you can generate the scripts for deleting the objects as

SELECT 'Drop Table '+name FROM sys.tables WHERE type='U';

SELECT 'Drop Procedure '+name FROM  sys.procedures WHERE type='P';

Execute the statements generated.

how to empty recyclebin through command prompt?

Create cmd file with line:

for %%p in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist "%%p:\$Recycle.Bin" rundll32.exe advpack.dll,DelNodeRunDLL32 "%%p:\$Recycle.Bin"

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

Get element of JS object with an index

If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

For example, using an array, you could do this:

var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];

Then, you can use myobj[0] to get the first object in the array.

Or, depending upon what you're trying to do:

var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
var firstKey = myobj[0].key;   // "A"
var firstValue = myobj[0].val; // "["B"]

Days between two dates?



I tried with b and a of type

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}



This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this


Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  object(stdClass)#20 (22) {
    string(1) "123"

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4

2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to add an UIViewController's view as subview

You must set the bounds properties to fit that frame. frame its superview properties, and bounds limit the frame in the view itself coordinate system.

How to install OpenJDK 11 on Windows?

  1. Extract the zip file into a folder, e.g. C:\Program Files\Java\ and it will create a jdk-11 folder (where the bin folder is a direct sub-folder). You may need Administrator privileges to extract the zip file to this location.

  2. Set a PATH:

    • Select Control Panel and then System.
    • Click Advanced and then Environment Variables.
    • Add the location of the bin folder of the JDK installation to the PATH variable in System Variables.
    • The following is a typical value for the PATH variable: C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-11\bin"
  3. Set JAVA_HOME:

    • Under System Variables, click New.
    • Enter the variable name as JAVA_HOME.
    • Enter the variable value as the installation path of the JDK (without the bin sub-folder).
    • Click OK.
    • Click Apply Changes.
  4. Configure the JDK in your IDE (e.g. IntelliJ or Eclipse).

You are set.

To see if it worked, open up the Command Prompt and type java -version and see if it prints your newly installed JDK.

If you want to uninstall - just undo the above steps.

Note: You can also point JAVA_HOME to the folder of your JDK installations and then set the PATH variable to %JAVA_HOME%\bin. So when you want to change the JDK you change only the JAVA_HOME variable and leave PATH as it is.

Truncating long strings with CSS: feasible yet?

Update: text-overflow: ellipsis is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the innerHTML property in Firefox. See the end of this post for a workaround.


.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');

ellipsis.xml file contents

<?xml version="1.0"?>
    <binding id="ellipsis">
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>

Updating node content

To update the content of a node in a way that works in Firefox use the following:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if ( {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);

See Matt Snider's post for an explanation of how this works.

Removing path and extension from filename in PowerShell

you can use basename property

PS II> ls *.ps1 | select basename

auto create database in Entity Framework Core

My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using function that I'm not even sure how exactly it works on a lower level.

So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:

public Startup(IHostingEnvironment env)
    using (var client = new TargetsContext())

This pretty much means that within the DbContext that you created (in this case, mine is called TargetsContext), you can use an instance of the DbContext to ensure that the tables defined with in the class are created when Startup.cs is run in your application.

How can I submit a POST form using the <a href="..."> tag?

You have to use Javascript submit function on your form object. Take a look in other functions.

<form action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>

Android - Best and safe way to stop thread

Currently and unfortunately we can't do anything to stop the thread....

Adding something to Matt's answer we can call interrupt() but that doesn't stop thread... Just tells the system to stop the thread when system wants to kill some threads. Rest is done by system, and we can check it by calling interrupted().

[p.s. : If you are really going with interrupt() I would ask you to do some experiments with a short sleep after calling interrupt()]

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

You need to add a reference to the .NET assembly System.Data.Entity.dll.

How do you use https / SSL on localhost?

It is easy to create a self-signed certificate, import it, and bind it to your website.

1.) Create a self-signed certificate:

Run the following 4 commands, one at a time, from an elevated Command Prompt:

cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64

makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku -sv localhost.pvk localhost.cer

cert2spc localhost.cer localhost.spc

pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx

2.) Import certificate to Trusted Root Certification Authorities store:

start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates

Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\

3.) Bind certificate to website:

start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings

Add or edit a binding for https and select the SSL certificate called "localhost".

4.) Import Certificate to Chrome:

Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder

Test Certificate by opening Chrome and navigating to https://localhost/

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
--2. Free Space

--3. Both Free & Used

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

is there any alternative for ng-disabled in angular2?

Here is a solution am using with anular 6.

[readonly]="DateRelatedObject.bool_DatesEdit ? true : false"

plus above given answer

[attr.disabled]="valid == true ? true : null"

did't work for me plus be aware of using null cause it's expecting bool.

Best way to define private methods for a class in Objective-C

If you wanted to avoid the @interface block at the top you could always put the private declarations in another file MyClassPrivate.h not ideal but its not cluttering up the implementation.


interface MyClass : NSObject {
  BOOL publicIvar_;
  BOOL privateIvar_;

@property (nonatomic, assign) BOOL publicIvar;
//any other public methods. etc


@interface MyClass ()

@property (nonatomic, assign) BOOL privateIvar;
//any other private methods etc.


#import "MyClass.h"
#import "MyClassPrivate.h"
@implementation MyClass

@synthesize privateIvar = privateIvar_;
@synthesize publicIvar = publicIvar_;


Understanding unique keys for array children in React.js

I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.

What's the difference between Visual Studio Community and other, paid versions?

Check the following: Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

How to see docker image contents

You can just run an interactive shell container using that image and explore whatever content that image has.

For instance:

docker run -it image_name sh

Or following for images with an entrypoint

docker run -it --entrypoint sh image_name

Or, if you want to see how the image was build, meaning the steps in its Dockerfile, you can:

docker image history --no-trunc image_name > image_history

The steps will be logged into the image_history file.

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

Android Studio: Default project directory

I found an easy way:

  1. Open a new project;
  2. Change the project location name by typing and not the Browse... button;
  3. The Next button will appear now.

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

Set font-weight using Bootstrap classes

EDIT 2 (final) : According to the bootstrap 4 documentation, class="font-weight-bold" is what you are looking for.

EDIT : You can use class="font-weight-bold" as shown here (Bootstrap 4 alpha).

I kept the original answer below for clarity purposes.

I am posting this answer because this thread seems to have a lot of visitors, yet it had no proper solution to solve this issue. But there will be soon now a way with Bootstrap 4 :

As this GitHub pull request shows, you will just have to use the text-weight-normal, text-weight-bold and text-weight-italic classes.

This can maybe change until the official stable release. At this date of writing, this pull request is not merged yet in the alpha branch.

I will update this post once Bootstrap v4 has been released.

Set the maximum character length of a UITextField

Swift 4

import UIKit

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                return length
            } else {
                return Int.max
        set {
            objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
            addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
    @objc func checkMaxLength(textField: UITextField) {
        guard let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
        let selection = selectedTextRange
        let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        let substring = prospectiveText[..<indexEndOfText]
        text = String(substring)
        selectedTextRange = selection

Edit: memory leak issue fixed.

enter image description here

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:

My class looks like this :

public class NodeDate
    public string nodedate { get; set; }
public class NodeList1
    public List<NodeDate> nodedatelist { get; set; }

and my c# code as follows :

        public string getTradeContribs(string Id, string nodedates)
        //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}";  // sample Json format
        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
        string thisDate = "";
        foreach (var date in nodes.nodedatelist)
        {  // iterate through if needed...
            thisDate = date.nodedate;

and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.

I hope this helps.... Bob

What is this property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the configuration file, you have the following entry:

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

Code from the same link

<script type="text/javascript" src=""></script>
<script src="" type="text/javascript"></script>
<link href=""
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        $("#btnShow").click(function () {
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.

%Like% Query in spring JpaRepository

The spring data JPA query needs the "%" chars as well as a space char following like in your query, as in

@Query("Select c from Registration c where like %:place%").


You may want to get rid of the @Queryannotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line

List<Registration> findByPlaceContaining(String place);

is sufficient.

SSL peer shut down incorrectly in Java

please close the android studio and remove the file




file form your project .Hope so it is helpful

Location:Go to Android studio projects->your project ->see both file remove (.gradle & .idea)

How do I Validate the File Type of a File Upload?

I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:

1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers

2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded

hope it helps :)

urlencoded Forward slash is breaking URL

I solved this by using 2 custom functions like so:

function slash_replace($query){

    return str_replace('/','_', $query);

function slash_unreplace($query){

    return str_replace('_','/', $query);

So to encode I could call:


and to decode I could call



How to make circular background using css?

It can be done using the border-radius property. basically, you need to set the border-radius to exactly half of the height and width to get a circle.



<div id="container">
    <div id="inner">


    border:1px black solid;

    -moz-border-radius: 100px;
    -webkit-border-radius: 100px;
    border-radius: 100px;

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:


position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

MySQL 'create schema' and 'create database' - Is there any difference

Strictly speaking, the difference between Database and Schema is inexisting in MySql.

However, this is not the case in other database engines such as SQL Server. In SQL server:,

Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)

By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:

FROM your_table

which is equivalent to:

FROM dbo.your_table

Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.

For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).

The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).

There are special schemas in SQL Server. To quote the same book:

There are several built-in database schemas, and they can't be dropped or altered:

1) dbo, the default schema.

2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.

3) INFORMATION_SCHEMA, used by the Information Schema Views

4) sys, reserved for SQL Server internal use exclusively

Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.

Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts (just an example, you get the idea).

Finally, and quoting the same book again:

It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition

Iterator invalidation rules

C++11 (Source: Iterator Invalidation Rules (C++0x))


Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) []
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) []
  • list: all iterators and references unaffected []
  • forward_list: all iterators and references unaffected (applies to insert_after) []
  • array: (n/a)

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.2.4/9]

Unsorted associative containers

  • unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container


Sequence containers

  • vector: every iterator and reference at or after the point of erase is invalidated []
  • deque: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) []
  • list: only the iterators and references to the erased element is invalidated []
  • forward_list: only the iterators and references to the erased element is invalidated (applies to erase_after) []
  • array: (n/a)

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.4/9]

Unordered associative containers

  • unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.5/13]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container


  • vector: as per insert/erase []
  • deque: as per insert/erase []
  • list: as per insert/erase []
  • forward_list: as per insert/erase []
  • array: (n/a)

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]

Note 2

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]

Note 3

Other than the above caveat regarding swap(), it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.

Note 4

vector and all unordered associative containers support reserve(n) which guarantees that no automatic resizing will occur at least until the size of the container grows to n. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert after enough erase operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase.

Convert a JSON string to object in Java ME?

JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object

String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

There are 3 things you need.

  1. You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)

  2. You need the access token (which you get returned in the URL box after the oAuth is done.)

  3. When those are complete you can then access the photos like so

You can find all of the information in more detail here:

How do I display the current value of an Android Preference in the Preference summary?

After several hours I've been spent to solve such problem I've implemented this code:

[UPDATE: the final version listing]

public class MyPreferencesActivity extends PreferenceActivity {
    ListPreference m_updateList;
    protected void onCreate(Bundle savedInstanceState) {

        m_updateList = (ListPreference) findPreference(getString(R.string.pref_update_interval_key));
        String currentValue = m_updateList.getValue();
        if (currentValue == null) {
            currentValue = m_updateList.getValue();

        m_updateList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                return true;

    private void updateListSummary(String newValue) {
        int index = m_updateList.findIndexOfValue(newValue);
        CharSequence entry = m_updateList.getEntries()[index];

That was the only solution that worked for me fine. Before I've tried to subclass from ListPreferences and to implement android:summary="bla bla bla %s". Neither worked.

Change image onmouseover

Try something like this:


<img src='/folder/image1.jpg' id='imageid'/>

jQuery: ?

$('#imageid').hover(function() {
  $(this).attr('src', '/folder/image2.jpg');
}, function() {
  $(this).attr('src', '/folder/image1.jpg');

EDIT: (After OP HTML posted)


<a href="#" id="name">
    <img title="Hello" src="/ico/view.png"/>


$('#name img').hover(function() {
  $(this).attr('src', '/ico/view1.png');
}, function() {
  $(this).attr('src', '/ico/view.png');

Inserting a blank table row with a smaller height

I know this question already has an answer, but I found out an even simpler way of doing this.

Just add

<tr height = 20px></tr>

Into the table where you want to have an empty row. It works fine in my program and it's probably the quickest solution possible.

AJAX reload page with POST

If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page

Javascript to be used (always in myForm.php):

function submitform()

Suppose your form is on myForm.php: Method 1:

<form action="./myForm.php" method="post" id="myForm">

Method 2:


<form action="./myFormActor.php" method="post" id="myForm">


    //all code here, no output
    header("Location: ./myForm.php");

MySQL remove all whitespaces from the entire column

To replace all spaces :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')

To remove all tabs characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )

To remove all new line characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')

To remove first and last space(s) of column :

UPDATE `table` SET `col_name` = TRIM(`col_name`)

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x); is not a function

You can always do the following:

const SomeCall = request.get(res => { 

const Store = []; 

Store.forEach(item => { DoSomethingNeat 

How to get list of dates between two dates in mysql select query


select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Eclipse not recognizing JVM 1.8

OK, so I don't really know what the problem was, but I simply fixed it by navigating to here and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!

edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)

Java optional parameters

There are no optional parameters in Java. What you can do is overloading the functions and then passing default values.

void SomeMethod(int age, String name) {

// Overload
void SomeMethod(int age) {
    SomeMethod(age, "John Doe");

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

How to make overlay control above all other controls?

This is a common function of Adorners in WPF. Adorners typically appear above all other controls, but the other answers that mention z-order may fit your case better.

Highlight the difference between two strings in PHP

You were able to use the PHP Horde_Text_Diff package.

However this package is no longer available.

Converting NumPy array into Python List structure?

c = np.array([[1,2,3],[4,5,6]])


How do you find the sum of all the numbers in an array in Java?

I like this method personally. My code style is a little weird.

public static int sumOf(int... integers) {
    int total = 0;
    for (int i = 0; i < integers.length; total += integers[i++]);
    return total;

Pretty easy to use in code:

int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1, 2, 3);

How to make HTML input tag only accept numerical values?

The accepted answer:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;

It's good but not perfect. It works out for me, but i get a warning that the if-statement can be simplified.

Then it looks like this, which is way prettier:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));

Would comment the original post, but my reputation is too low to do so (just created this account).

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt


tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt


sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

How to advance to the next form input when the current input has a value?

I couldn't find an answer that could do what I wanted. I had a problem where there were some link elements that I didn't want users tabbing to. This is what I came up with:

(Note that in my own code I used a:not(.dropdown-item) instead of a on the allElements line, in order to prevent users tabbing to a.dropdown-item.)

        //Note that this doesn't honour tab-indexes


        //Isolate the node that we're after
        const currentNode =;

        //find all tab-able elements
        const allElements = document.querySelectorAll('input, button, a, area, object, select, textarea, [contenteditable]');

        //Find the current tab index.
        const currentIndex = [...allElements].findIndex(el => currentNode.isEqualNode(el))

        //focus the following element
        const targetIndex = (currentIndex + 1) % allElements.length;

Ranges of floating point datatype in C?

A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:

(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) = 
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) = 
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38

How to change port for jenkins window service when 8080 is being used

On Windows (with Windows Service).

Edit the file C:\Program Files (x86)\Jenkins\jenkins.xml with 8083 if you want 8083 port.

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>

Angular 2 optional route parameter

Angular 4 - Solution to address the ordering of the optional parameter:


const appRoutes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'products', component: ProductsComponent},
  {path: 'products/:id', component: ProductsComponent}

Note that the products and products/:id routes are named exactly the same. Angular 4 will correctly follow products for routes with no parameter, and if a parameter it will follow products/:id.

However, the path for the non-parameter route products must not have a trailing slash, otherwise angular will incorrectly treat it as a parameter-path. So in my case, I had the trailing slash for products and it wasn't working.


{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},

Matplotlib 2 Subplots, 1 Colorbar

This solution does not require manual tweaking of axes locations or colorbar size, works with multi-row and single-row layouts, and works with tight_layout(). It is adapted from a gallery example, using ImageGrid from matplotlib's AxesGrid Toolbox.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

# Set up figure and image grid
fig = plt.figure(figsize=(9.75, 3))

grid = ImageGrid(fig, 111,          # as in plt.subplot(111)

# Add data to image grid
for ax in grid:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

# Colorbar

#plt.tight_layout()    # Works, but may still require rect paramater to keep colorbar labels visible

image grid

CSS Equivalent of the "if" statement

css files do not support conditional statements.

If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg

<div class="oh-yes"></div>
<div class="hell-no"></div>

How to change the type of a field?

I use this script in mongodb console for string to float conversions...

db.documents.find({ 'fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.fwtweaeeba = parseFloat( obj.fwtweaeeba );; } );    

db.documents.find({ 'versions.0.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[0].content.fwtweaeeba = parseFloat( obj.versions[0].content.fwtweaeeba );; } );

db.documents.find({ 'versions.1.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[1].content.fwtweaeeba = parseFloat( obj.versions[1].content.fwtweaeeba ); ; } );

db.documents.find({ 'versions.2.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[2].content.fwtweaeeba = parseFloat( obj.versions[2].content.fwtweaeeba ); ; } );

And this one in php)))

foreach($db->documents->find(array("type" => "chair")) as $document){
        array('_id' => $document[_id]),
            '$set' => array(
                'versions.0.content.axdducvoxb' => (float)$document['versions'][0]['content']['axdducvoxb'],
                'versions.1.content.axdducvoxb' => (float)$document['versions'][1]['content']['axdducvoxb'],
                'versions.2.content.axdducvoxb' => (float)$document['versions'][2]['content']['axdducvoxb'],
                'axdducvoxb' => (float)$document['axdducvoxb']
        array('$multi' => true)


How to change ViewPager's page?

for switch to another page, try with this code:

viewPager.postDelayed(new Runnable()
    public void run()
        viewPager.setCurrentItem(num, true);
}, 100);

TypeError: 'module' object is not callable

I know this thread is a year old, but the real problem is in your working directory.

I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named in this directory. Once you find it, rename or move it. When you import socket, from the current directory is used instead of the from Python's directory. Hope this helped. :)

Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).

Get user location by IP address

IPInfoDB has an API that you can call in order to find a location based on an IP address.

For "City Precision", you call it like this (you'll need to register to get a free API key):<your_api_key>&ip=

Here's an example in both VB and C# that shows how to call the API.

CSS: styled a checkbox to look like a button, is there a hover?

Do this for a cool border and font effect:

#ck-button:hover {             /*ADD :hover */
    border:1px solid red;      /*change border color*/ 
    color:red;                 /*add font color*/


htaccess "order" Deny, Allow, Deny

Update : for the new apache 2.4 jump directly to the end.

The Order keyword and its relation with Deny and Allow Directives is a real nightmare. It would be quite interesting to understand how we ended up with such solution, a non-intuitive one to say the least.

  • The first important point is that the Order keyword will have a big impact on how Allow and Deny directives are used.
  • Secondly, Deny and Allow directives are not applied in the order they are written, they must be seen as two distinct blocks (one the for Deny directives, one for Allow).
  • Thirdly, they are drastically not like firewall rules: all rules are applied, the process is not stopping at the first match.

You have two main modes:

The Order-Deny-Allow-mode, or Allow-anyone-except-this-list-or-maybe-not

Order Deny,Allow
  • This is an allow by default mode. You optionally specify Deny rules.
  • Firstly, the Deny rules reject some requests.
  • If someone gets rejected you can get them back with an Allow.

I would rephrase it as:

Rule Deny
     list of Deny rules
     list of Allow rules
Policy Allow (when no rule fired)

The Order-Allow-Deny-mode, or Reject-everyone-except-this-list-or-maybe-not

Order Allow,Deny
  • This is a deny by default mode. So you usually specify Allow rules.
  • Firstly, someone's request must match at least one Allow rule.
  • If someone matched an Allow, you can still reject them with a Deny.

In the simplified form:

Rule Allow
     list of Allow rules
     list of Deny rules
Policy Deny (when no rule fired)

Back to your case

You need to allow a list of networks which are the country networks. And in this country you want to exclude some proxies' IP addresses.

You have taken the allow-anyone-except-this-list-or-maybe-not mode, so by default anyone can access your server, except proxies' IPs listed in the Deny list, but if they get rejected you still allow the country networks. That's too broad. Not good.

By inverting to order allow,deny you will be in the reject-everyone-except-this-list-or-maybe-not mode. So you will reject access to everyone but allow the country networks and then you will reject the proxies. And of course you must remove the Deny from all as stated by @Gerben and @Michael Slade (this answer only explains what they wrote).

The Deny from all is usually seen with order deny,allow to remove the allow by default access and make a simple, readable configuration. For example, specify a list of allowed IPs after that. You don't need that rule and your question is a perfect case of a 3-way access mode (default policy, exceptions, exceptions to exceptions).

But the guys who designed these settings are certainly insane.

All this is deprecated with Apache 2.4

The whole authorization scheme has been refactored in Apache 2.4 with RequireAll, RequireAny and RequireNone directives. See for example this complex logic example.

So the old strange Order logic becomes a relic, and to quote the new documentation:

Controling how and in what order authorization will be applied has been a bit of a mystery in the past

Javascript/Jquery to change class onclick?

For a super succinct with jQuery approach try:

<div onclick="$(this).toggleClass('newclass')">click me</div>

Or pure JS:

<div onclick="this.classList.toggle('newclass');">click me</div>

Random number from a range in a Bash Script

Same with ruby:

echo $(ruby -e 'puts rand(20..65)') #=> 65 (inclusive ending)
echo $(ruby -e 'puts rand(20...65)') #=> 37 (exclusive ending)

Convert XmlDocument to String

Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?

return xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml.

Example on ToggleButton

Try this Toggle Buttons



public class Test extends Activity {

private ToggleButton togglebutton;

public void onCreate(Bundle savedInstanceState) {
    togglebutton = (ToggleButton) findViewById(;

public void toggleclick(View v){
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();

How do I display the value of a Django form field in a template?

I have a simple solution for you!

{{ }}

I tried this and it worked. This requires your view to populate the form class with the POST data.

Very simple example:

def your_view(request):
  if request.method == 'POST':
    form = YourForm(request.POST)
    if form.is_valid():
      # some code here
    form = YourForm()

  return render_to_response('template.html', {'form':form})

Hope that helps you. If you have any questions please let me know.

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

Counting repeated characters in a string in Python

inputString =  input("Enter a String:")
countedArray = {}

for char in inputString:
    if char in countedArray:  
        countedArray[char] += 1    
        countedArray[char] = 1

Declaring an enum within a class

Nowadays - using C++11 - you can use enum class for this:

enum class Color { RED, BLUE, WHITE };

AFAII this does exactly what you want.

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

jQuery toggle animation

            height: "150", 
            padding:"20px 0",
        }, 500);
            //otherdiv properties here
        }, 500);
            height: "0", 
            padding:"0px 0",
        }, 500);     
            //otherdiv properties here
        }, 500);

How to send a html email with the bash command "sendmail"?

The following works:

echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t

For troubleshooting msmtp, which is compatible with sendmail, see:

How to dynamically load a Python class

If you're using Django you can use this. Yes i'm aware OP did not ask for django, but i ran across this question looking for a Django solution, didn't find one, and put it here for the next boy/gal that looks for it.

# It's available for v1.7+
from django.utils.module_loading import import_string

Klass = import_string('')
func = import_string('')
var = import_string('')

Keep in mind, if you want to import something that doesn't have a ., like re or argparse use:

re = __import__('re')

Python Pandas: Get index of rows which column matches certain value

First you may check query when the target column is type bool (PS: about how to use it please check link )

10     True
40     True
50     True

After we filter the original df by the Boolean column we can pick the index .

Out[125]: Int64Index([10, 40, 50], dtype='int64')

Also pandas have nonzero, we just select the position of True row and using it slice the DataFrame or index

Out[128]: Int64Index([10, 40, 50], dtype='int64')

Difference between window.location.href and top.location.href

window.location.href returns the location of the current page.

top.location.href (which is an alias of returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window ===

top is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html with the following script:


The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href would return.

To answer your question about redirecting, go with window.location.assign(url);

Visual C++: How to disable specific linker warnings?

For the benefit of others, I though I'd include what I did.

Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.

BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.

My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.

So for the "Debug" configuraton, I edited:

Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from


to be the following value:


Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.

I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.

Java/ JUnit - AssertTrue vs AssertFalse

assertTrue will fail if the second parameter evaluates to false (in other words, it ensures that the value is true). assertFalse does the opposite.

assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);

assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);

As with many other things, the best way to become familiar with these methods is to just experiment :-).

Spring Boot access static resources missing scr/main/resources

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile() when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

Below is the code snippet for the same -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

How do I remove a single file from the staging area (undo git add)?

I think you probably got confused with the concept of index, as @CB Bailey commented:

The staging area is the index.

You can simply consider staging directory and index as the same thing.
So, just like @Tim Henigan's answer, I guess:

you simply want to "undo" the git add that was done for that file.

Here is my answer:

Commonly, there are two ways to undo a stage operation, as other answers already mentioned:

git reset HEAD <file>


git rm --cached <file>

But what is the difference?

Assume the file has been staged and exists in working directory too, use git rm --cached <file> if you want to remove it from staging directory, and keep the file in working directory. But notice that this operation will not only remove the file from staging directory but also mark the file as deleted in staging directory, if you use

git status

after this operation, you will see this :

        deleted:    <file>

It's a record of removing the file from staging directory. If you don't want to keep that record and just simply want to undo a previous stage operation of a file, use git reset HEAD <file> instead.

-------- END OF ANSWER --------

PS: I have noticed some answers mentioned:

git checkout -- <file>

This command is for the situation when the file has been staged, but the file has been modified in working directory after it was staged, use this operation to restore the file in working directory from staging directory. In other words, after this operation, changes happen in your working directory, NOT your staging directory.

Add a new item to a dictionary in Python

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

>>> class Dict(dict):
...     def __add__(self, other):
...         copy = self.copy()
...         copy.update(other)
...         return copy
...     def __radd__(self, other):
...         copy = other.copy()
...         copy.update(self)
...         return copy
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}

Note that this is more overhead then using dict[key] = value or dict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.

How do I redirect to the previous action in ASP.NET MVC?

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

Other in details example: Imagine that you have a Vehicle Controller with actions




and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
     public string ReturnUrl {get;set;}

<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
                viewModel.ReturnUrl = "Index";
            return View(viewModel);

    public IActionResult Edit(VehicleViewModel model, string previous)
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
                model.ReturnUrl = "Index";
            return RedirectToAction(model.ReturnUrl);

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The advantages of EditorFor is that your code is not tied to an <input type="text". So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.

How to split data into trainset and testset randomly?

You could also use numpy. When your data is stored in a numpy.ndarray:

import numpy as np
from random import sample
l = 100 #length of data 
f = 50  #number of elements you need
indices = sample(range(l),f)

train_data = data[indices]
test_data = np.delete(data,indices)

Deleting objects from an ArrayList in Java

With an iterator you can handle always the element which comes to order, not a specified index. So, you should not be troubled with the above matter.

Iterator itr = list.iterator();
String strElement = "";

  strElement = (String);

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

How can I get a user's media from Instagram without authenticating as a user?

I was able to get the most recent media of a user using the following API without authentication (including the description, likes, comments count).


How can I restart a Java application?


public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        StringBuilder cmd = new StringBuilder();
        cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
        for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
            cmd.append(jvmArg + " ");
        cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
        cmd.append(Main.class.getName()).append(" ");
        for (String arg : args) {
            cmd.append(arg).append(" ");

Dedicated to all those who say it is impossible.

This program collects all information available to reconstruct the original commandline. Then, it launches it and since it is the very same command, your application starts a second time. Then we exit the original program, the child program remains running (even under Linux) and does the very same thing.

WARNING: If you run this, be aware that it never ends creating new processes, similar to a fork bomb.

Sanitizing strings to make them URL and filename safe?

Depending on how you will use it, you might want to add a length limit to protect against buffer overflows.

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

Using Pipes within ngModel on INPUT Elements in Angular

I tried the solutions above yet the value that goes to the model were the formatted value then returning and giving me currencyPipe errors. So i had to

  [ngModel]="transfer.amount | currency:'USD':true"

And on the function of addToAmount -> change on blur cause the ngModelChange was giving me cursor issues.

    return formatedNumber.replace(/[$,]/g,"")

And removing the other non numeric values.

validateOnlyNumbers(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();

Reference to non-static member function must be called

You may want to have a look at, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Allowing Untrusted SSL Certificates with HttpClient

I found an example in this Kubernetes client where they were using X509VerificationFlags.AllowUnknownCertificateAuthority to trust self-signed self-signed root certificates. I slightly reworked their example to work with our own PEM encoded root certificates. Hopefully this helps someone.

namespace Utils
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net.Security;
  using System.Security.Cryptography.X509Certificates;

  /// <summary>
  /// Verifies that specific self signed root certificates are trusted.
  /// </summary>
  public class HttpClientHandler : System.Net.Http.HttpClientHandler
    /// <summary>
    /// Initializes a new instance of the <see cref="HttpClientHandler"/> class.
    /// </summary>
    /// <param name="pemRootCerts">The PEM encoded root certificates to trust.</param>
    public HttpClientHandler(IEnumerable<string> pemRootCerts)
      foreach (var pemRootCert in pemRootCerts)
        var text = pemRootCert.Trim();
        text = text.Replace("-----BEGIN CERTIFICATE-----", string.Empty);
        text = text.Replace("-----END CERTIFICATE-----", string.Empty);
        this.rootCerts.Add(new X509Certificate2(Convert.FromBase64String(text)));

      this.ServerCertificateCustomValidationCallback = this.VerifyServerCertificate;

    private bool VerifyServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
      // If the certificate is a valid, signed certificate, return true.
      if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

      // If there are errors in the certificate chain, look at each error to determine the cause.
      if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

        // add all your extra certificate chain
        foreach (var rootCert in this.rootCerts)

        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
        var isValid = chain.Build((X509Certificate2)certificate);

        var rootCertActual = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
        var rootCertExpected = this.rootCerts[this.rootCerts.Count - 1];
        isValid = isValid && rootCertActual.RawData.SequenceEqual(rootCertExpected.RawData);

        return isValid;

      // In all other cases, return false.
      return false;

    private readonly IList<X509Certificate2> rootCerts = new List<X509Certificate2>();

How to get Spinner selected item value to string?

Try this:

String text = mySpinner.getSelectedItem().toString();

Like this you can get value for different Spinners.

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
        scrollTop: $("#" + id).offset().top
    }, 'slow');

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    // Call the scroll function

Live Example

( Scroll to function taken from here )

PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

Alternative to the HTML Bold tag

A very old thread, I know. - but for completeness:

I use <span class="bold">my text</span>    

as I upload the four font styles: normal; bold; italic and bold italic into my web-site via css.

I feel the resulting output is better than simply modifying a font and is closer to the designers intention of how the boldened font should look.

The same applies for italic and bolditalic of course, which gives me additional flexibility.

Jquery, Clear / Empty all contents of tbody element?

you can use the remove() function of the example below and build table again with table head, and table body

$("#table_id  thead").remove();
$("#table_id  tbody").remove();

What is the difference between a cer, pvk, and pfx file?

Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:

  • Both PKCS12 and PEM can store entire cert chains: public keys, private keys, and root (CA) certs.
  • .pfx == .p12 == "PKCS12"
    • fully encrypted
  • .pem == .cer == .cert == "PEM" (or maybe not... could be binary... see comments...)
    • base-64 (string) encoded X509 cert (binary) with a header and footer
      • base-64 is basically just a string of "A-Za-z0-9+/" used to represent 0-63, 6 bits of binary at a time, in sequence, sometimes with 1 or 2 "=" characters at the very end when there are leftovers ("=" being "filler/junk/ignore/throw away" characters)
      • the header and footer is something like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" or "-----BEGIN ENCRYPTED PRIVATE KEY-----" and "-----END ENCRYPTED PRIVATE KEY-----"
    • Windows recognizes .cer and .cert as cert files
  • .jks == "Java Key Store"
    • just a Java-specific file format which the API uses
      • .p12 and .pfx files can also be used with the JKS API
  • "Trust Stores" contain public, trusted, root (CA) certs, whereas "Identity/Key Stores" contain private, identity certs; file-wise, however, they are the same.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.

If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Console app arguments, how arguments are passed to Main method

The runtime splits the arguments given at the console at each space.

If you call

myApp.exe arg1 arg2 arg3

The Main Method gets an array of

var args = new string[] {"arg1","arg2","arg3"}

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

i had the same problem with my jar the solution

  1. Create the MANIFEST.MF file:

Manifest-Version: 1.0

Sealed: true

Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar

Main-Class: com.MainClass

  1. Right click on project, Select Export.

select export all outpout folders for checked project

  1. select using existing manifest from workspace and select the MANIFEST.MF file

This worked for me :)

Create a SQL query to retrieve most recent records

Aggregate in a subquery derived table and then join to it.

 Select Date, User, Status, Notes 
    from [SOMETABLE]
    inner join 
        Select max(Date) as LatestDate, [User]
        from [SOMETABLE]
        Group by User
    ) SubMax 
    on [SOMETABLE].Date = SubMax.LatestDate
    and [SOMETABLE].User = SubMax.User 

HTML text input field with currency symbol

I just used :before with the input and passed $ as the content

   margin-left: 20px;
input:before {
  content: "$";
  position: absolute;

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

jQuery's is triggering a 404 (Not Found)

As it is announced in jQuery 1.11.0/2.1.0 Beta 2 Released the source map comment will be removed so the issue will not appear in newer versions of jQuery.

Here is the official announcement:

One of the changes we’ve made in this beta is to remove the sourcemap comment. Sourcemaps have proven to be a very problematic and puzzling thing to developers, generating scores of confused questions on forums like StackOverflow and causing users to think jQuery itself was broken.

Anyway, if you need to use a source map, it still be available:

We’ll still be generating and distributing sourcemaps, but you will need to add the appropriate sourcemap comment at the end of the minified file if the browser does not support manually associating map files (currently, none do). If you generate your own jQuery file using the custom build process, the sourcemap comment will be present in the minified file and the map is generated; you can either leave it in and use sourcemaps or edit it out and ignore the map file entirely.

Here you can find more details about the changes.

Here you can find confirmation that with the jQuery 1.11.0/2.1.0 Released the source-map comment in the minified file is removed.

Redirect non-www to www in .htaccess

Write in .htaccess :)

## Redirect from non-www to www (remove the two lines below to enable)
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Scanner is never closed

Try this

Scanner scanner = new Scanner(;
int amountOfPlayers;
do {
    System.out.print("Select the amount of players (1/2): ");
    while (!scanner.hasNextInt()) {
        System.out.println("That's not a number!");; // this is important!

    amountOfPlayers = scanner.nextInt();
} while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
if(scanner != null) {
System.out.println("You've selected " + amountOfPlayers+" player(s).");

What is the "hasClass" function with plain JavaScript?


Instead of $(element).hasClass('example') in jQuery, you can use element.matches('.example') in plain JavaScript:

if (element.matches('.example')) {
  // Element has example class ...

View Browser Compatibility

React Native TextInput that only accepts numeric characters

This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.

by the way, This work well on Android.

Check if a string has white space

With additions to the language it is much easier, plus you can take advantage of early return:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));

// Use character comparison
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return Array.from(s).some(char => whitespaceChars.includes(char));

const withSpace = "Hello World!";
const noSpace = "HelloWorld!";



I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

You haven't accepted an answer, so here's what worked for me in PuTTY:

enter image description here

Without allowing username changes, i got this question's subject as error on the gateway machine.

AlertDialog.Builder with custom layout and EditText; cannot access view

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

EditText editText = (EditText) alertDialog.findViewById(;


Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater is Null.

update your code like below, and try to understand the each code line

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);

EditText editText = (EditText) dialogView.findViewById(;
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();;

Update 2:

As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);


Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
    IntPtr h = p.MainWindowHandle;

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
IntPtr h = p.MainWindowHandle;

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

How to get HttpRequestMessage data

In case you want to cast to a class and not just a string:

YourClass model = await request.Content.ReadAsAsync<YourClass>();

Plot multiple boxplot in one graph

You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.

df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package. 
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame

#     Label variable      value
# 1    Good       F1 0.64778924
# 2    Good       F1 0.54608791
# 3    Good       F1 0.46134200
# 4    Good       F1 0.79421221
# 5    Good       F1 0.56919951
# 6    Good       F1 0.73568570
# 7    Good       F1 0.65094207
# 8    Good       F1 0.45749702
# 9    Good       F1 0.80861929
# 10   Good       F1 0.67310067
# 11   Good       F1 0.68781739
# 12   Good       F1 0.47009455
# 13   Good       F1 0.95859182
# 14   Good       F1 1.00000000
# 15   Good       F1 0.46908343
# 16    Bad       F1 0.57875528
# 17    Bad       F1 0.28938046
# 18    Bad       F1 0.68511766

ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))


Edit: I realise that you might need to facet. Here's an implementation of that as well:

p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
p + facet_wrap( ~ variable, scales="free")


Edit 2: How to add x-labels, y-labels, title, change legend heading, add a jitter?

p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))


Edit 3: How to align geom_point() points to the center of box-plot? It could be done using position_dodge. This should work.

p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))


How many bytes does one Unicode character take?

In Unicode the answer is not easily given. The problem, as you already pointed out, are the encodings.

Given any English sentence without diacritic characters, the answer for UTF-8 would be as many bytes as characters and for UTF-16 it would be number of characters times two.

The only encoding where (as of now) we can make the statement about the size is UTF-32. There it's always 32bit per character, even though I imagine that code points are prepared for a future UTF-64 :)

What makes it so difficult are at least two things:

  1. composed characters, where instead of using the character entity that is already accented/diacritic (À), a user decided to combine the accent and the base character (`A).
  2. code points. Code points are the method by which the UTF-encodings allow to encode more than the number of bits that gives them their name would usually allow. E.g. UTF-8 designates certain bytes which on their own are invalid, but when followed by a valid continuation byte will allow to describe a character beyond the 8-bit range of 0..255. See the Examples and Overlong Encodings below in the Wikipedia article on UTF-8.
    • The excellent example given there is that the € character (code point U+20AC can be represented either as three-byte sequence E2 82 AC or four-byte sequence F0 82 82 AC.
    • Both are valid, and this shows how complicated the answer is when talking about "Unicode" and not about a specific encoding of Unicode, such as UTF-8 or UTF-16.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

A short solution:

use Dotenv;

with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());

In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this


after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager needs to re-read config parameters.

How to remove &quot; from my Json in javascript?

The following works for me:

function decodeHtml(html) {
    let areaElement = document.createElement("textarea");
    areaElement.innerHTML = html;

    return areaElement.value;

How to use Oracle's LISTAGG function with a unique filter?

create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');

select group_id, 
       (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
  select group_id, collect(distinct name) as coll_names 
    from demotable
    group by group_id 

1   Alan,David,John
2   Charles,Julie

How do I get the command-line for an Eclipse run configuration?

You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.

You will probably also need the .classpath file in the project directory that contains the test class.

Like the run configurations, they're XML files (even if they don't have an xml extension).

Reset par to the default values at startup is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:

def.par = par()

Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:

par(def.par) #go back to default par settings

With this, you keep generated plots and reset par settings.

How do I "decompile" Java class files?

I tried several, and Procyon seemed to work the best for me. It's under active development and supports many features of the latest versions of Java.

These are the others I tried:

  • CFR
    • Promising, but often failed method decompilation. I'll be keeping my eye on this one. Also actively developed with support for the latest Java features.
  • Krakatau
    • Takes a different approach in that it tries to output equivalent Java code instead of trying to reconstruct the original source, which has the potential of making it better for obfuscated code. From my testing it was roughly on par with Procyon, but still nice to have something different. I did have to use the -skip command-line flag so it wouldn't stop on errors. Actively developed, and interestingly enough it's written in Python.
  • JD-GUI
  • JAD
    • Worked, but only supports Java 1.4 and below. Also available as an Eclipse plugin. No longer under development.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Posting this to help someone.


channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip:
   listening port 8890 for port 8890,
   connect from ::1 port 52337 to ::1 port 8890, nchannels 8

My scenario; i had to use the remote server as a bastion host to connect elsewhere. Final Destination/Target:, port 8890. Through intermediary server with public ip:

SSH local port forwarding command:

ssh -i ~/keys/dev.tst -vnNT -L :8890:
[email protected]

What the problem was: There was no service bound on port 8890 in the target host. i had forgotten to start the service.

How did i trouble shoot:

SSH into bastion host and then do curl.

Hope this helps.

How can I list ALL DNS records?

What you want is called a zone transfer. You can request a zone transfer using dig -t axfr.

A zone is a domain and all of the domains below it that are not delegated to another server.

Note that zone transfers are not always supported. They're not used in normal lookup, only in replicating DNS data between servers; but there are other protocols that can be used for that (such as rsync over ssh), there may be a security risk from exposing names, and zone transfer responses cost more to generate and send than usual DNS lookups.

A html space is showing as %2520 instead of %20

When you are trying to visit a local filename through firefox browser, you have to force the file:\\\ protocol ( or else firefox will encode your space TWICE. Change the html snippet from this:

<img src="C:\Documents and Settings\screenshots\Image01.png"/>

to this:

<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>

or this:

<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>

Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.

Helpful link:

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the following code.

File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');

if (lastSlash >= 0)
    fileName = url.toString().substring(lastSlash + 1);

if (fileName.endsWith("pdf"))
    mimeType = "application/pdf";
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension

Uri uri_path = Uri.fromFile(file);

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setDataAndType(uri_path, mimeType);


How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

Checking letter case (Upper/Lower) within a string in Java

Although this code is likely beyond the understanding of a novice, it can be done in one line using a regex with positive and negative look-aheads:

boolean ok = 

Cannot download Docker images behind a proxy

Your APT proxy settings are not related to Docker.

Docker uses the HTTP_PROXY environment variable, if present. For example:

sudo HTTP_PROXY= docker pull busybox

But instead, I suggest you have a look at your /etc/default/dockerconfiguration file: you should have a line to uncomment (and maybe adjust) to get your proxy settings applied automatically. Then restart the Docker server:

service docker restart

Storing files in SQL Server

You might read up on FILESTREAM. Here is some info from the docs that should help you decide:

If the following conditions are true, you should consider using FILESTREAM:

  • Objects that are being stored are, on average, larger than 1 MB.
  • Fast read access is important.
  • You are developing applications that use a middle tier for application logic.

For smaller objects, storing varbinary(max) BLOBs in the database often provides better streaming performance.

How to Apply Corner Radius to LinearLayout



Drawable folder rounded_edge.xml


How does a PreparedStatement avoid or prevent SQL injection?

In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement

How do I copy SQL Azure database to my local development server?

I couldn't get the SSIS import / export to work as I got the error 'Failure inserting into the read-only column "id"'. Nor could I get to work, and the links above to SQL Azure Data Sync didn't work for me.

But I found an excellent blog post about BACPAC files:

In the video in the post the blog post's author runs through six steps:

  1. Make or go to a storage account in the Azure Management Portal. You'll need the Blob URL and the Primary access key of the storage account.

  2. The blog post advises making a new container for the bacpac file and suggests using the Azure Storage Explorer for that. (N.B. you'll need the Blob URL and the Primary access key of the storage account to add it to the Azure Storage Explorer.)

  3. In the Azure Management Portal select the database you want to export and click 'Export' in the Import and Export section of the ribbon.

  4. The resulting dialogue requires your username and password for the database, the blob URL, and the access key. Don't forget to include the container in the blob URL and to include a filename (e.g.

  5. After you click Finish the database will be exported to the BACPAC file. This can take a while. You may see a zero byte file show up immediately if you check in the Azure Storage Explorer. This is the Import / Export Service checking that it has write access to the blob-store.

  6. Once that is done you can use the Azure Storage Explorer to download the BACPAC file and then in the SQL Server Management Studio right-click your local server's database folder and choose Import Data Tier Application that will start the wizard which reads in the BACPAC file to produce the copy of your Azure database. The wizard can also connect directly to the blob-store to obtain the BACPAC file if you would rather not copy it locally first.

The last step may only be available in the SQL Server 2012 edition of the SQL Server Management Studio (that's the version I am running). I do not have earlier ones on this machine to check. In the blog post the author uses the command line tool DacImportExportCli.exe for the import which I believe is available at

Use Fieldset Legend with bootstrap

In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:

<fieldset class="border p-2">
   <legend  class="w-auto">Your Legend</legend>

which looks like this: bootstrap 4 fieldset and legend

Convert list of ASCII codes to string (byte array) in Python

struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

How can I mock requests and the response?

I will add this information since I had a hard time figuring how to mock an async api call.

Here is what I did to mock an async call.

Here is the function I wanted to test

async def get_user_info(headers, payload):
    return await httpx.AsyncClient().post(URI, json=payload, headers=headers)

You still need the MockResponse class

class MockResponse:
    def __init__(self, json_data, status_code):
        self.json_data = json_data
        self.status_code = status_code

    def json(self):
        return self.json_data

You add the MockResponseAsync class

class MockResponseAsync:
    def __init__(self, json_data, status_code):
        self.response = MockResponse(json_data, status_code)

    async def getResponse(self):
        return self.response

Here is the test. The important thing here is I create the response before since init function can't be async and the call to getResponse is async so it all checked out.

async def test_get_user_info_valid(self, mock_post):
    # Given
    token_bd = "abc"
    username = "bob"
    payload = {
        'USERNAME': username,
        'DBNAME': 'TEST'
    headers = {
        'Authorization': 'Bearer ' + token_bd,
        'Content-Type': 'application/json'
    async_response = MockResponseAsync("", 200) = async_response.getResponse()

    # When
    await api_bd.get_user_info(headers, payload)

    # Then
        URI, json=payload, headers=headers)

If you have a better way of doing that tell me but I think it's pretty clean like that.

How to determine whether an object has a given property in JavaScript


There is a new feature on ES6+ that you can check it like below:

if (x?.y)

Actually, the interpretor checks the existence of x and then call the y and because of putting inside if parentheses the coercion happens and x?.y converted to boolean.

How do I remove  from the beginning of a file?

Use Total Commander to search for all BOMed files:

Elegant way to search for UTF-8 files with BOM?

  • Open these files in some proper editor (that recognizes BOM) like Eclipse.

  • Change the file's encoding to ISO (right click, properties).

  • Cut  from the beginning of the file, save

  • Change the file's encoding back to UTF-8

...and do not even think about using n...d again!

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

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

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

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

SQL Server: Invalid Column Name

I just tried. If you execute the statement to generate your local table, the tool will accept that this column name exists. Just mark the table generation statement in your editor window and click execute.

How to resolve : Can not find the tag library descriptor for ""

paste below two jar in your /WEB-INF/lib folder and then go to project properties and go to add jar and select these two jars then click Ok, Ok

standard.jar, jstl-1.0.2.jar

VMware Workstation and Device/Credential Guard are not compatible

Device/Credential Guard is a Hyper-V based Virtual Machine/Virtual Secure Mode that hosts a secure kernel to make Windows 10 much more secure.

enter image description here

...the VSM instance is segregated from the normal operating system functions and is protected by attempts to read information in that mode. The protections are hardware assisted, since the hypervisor is requesting the hardware treat those memory pages differently. This is the same way to two virtual machines on the same host cannot interact with each other; their memory is independent and hardware regulated to ensure each VM can only access it’s own data.

From here, we now have a protected mode where we can run security sensitive operations. At the time of writing, we support three capabilities that can reside here: the Local Security Authority (LSA), and Code Integrity control functions in the form of Kernel Mode Code Integrity (KMCI) and the hypervisor code integrity control itself, which is called Hypervisor Code Integrity (HVCI).

enter image description here

When these capabilities are handled by Trustlets in VSM, the Host OS simply communicates with them through standard channels and capabilities inside of the OS. While this Trustlet-specific communication is allowed, having malicious code or users in the Host OS attempt to read or manipulate the data in VSM will be significantly harder than on a system without this configured, providing the security benefit.

Running LSA in VSM, causes the LSA process itself (LSASS) to remain in the Host OS, and a special, additional instance of LSA (called LSAIso – which stands for LSA Isolated) is created. This is to allow all of the standard calls to LSA to still succeed, offering excellent legacy and backwards compatibility, even for services or capabilities that require direct communication with LSA. In this respect, you can think of the remaining LSA instance in the Host OS as a ‘proxy’ or ‘stub’ instance that simply communicates with the isolated version in prescribed ways.

And Hyper-V and VMware didn't work the same time until 2020, when VMware used Hyper-V Platform to co-exist with Hyper-V starting with Version 15.5.5.

How does VMware Workstation work before version 15.5.5?

VMware Workstation traditionally has used a Virtual Machine Monitor (VMM) which operates in privileged mode requiring direct access to the CPU as well as access to the CPU’s built in virtualization support (Intel’s VT-x and AMD’s AMD-V). When a Windows host enables Virtualization Based Security (“VBS“) features, Windows adds a hypervisor layer based on Hyper-V between the hardware and Windows. Any attempt to run VMware’s traditional VMM fails because being inside Hyper-V the VMM no longer has access to the hardware’s virtualization support.

Introducing User Level Monitor

To fix this Hyper-V/Host VBS compatibility issue, VMware’s platform team re-architected VMware’s Hypervisor to use Microsoft’s WHP APIs. This means changing our VMM to run at user level instead of in privileged mode, as well modifying it to use the WHP APIs to manage the execution of a guest instead of using the underlying hardware directly.

What does this mean to you?

VMware Workstation/Player can now run when Hyper-V is enabled. You no longer have to choose between running VMware Workstation and Windows features like WSL, Device Guard and Credential Guard. When Hyper-V is enabled, ULM mode will automatically be used so you can run VMware Workstation normally. If you don’t use Hyper-V at all, VMware Workstation is smart enough to detect this and the VMM will be used.

System Requirements

To run Workstation/Player using the Windows Hypervisor APIs, the minimum required Windows 10 version is Windows 10 20H1 build 19041.264. VMware Workstation/Player minimum version is 15.5.5.

To avoid the error, update your Windows 10 to Version 2004/Build 19041 (Mai 2020 Update) and use at least VMware 15.5.5.

UnicodeEncodeError: 'charmap' codec can't encode characters

Even I faced the same issue with the encoding that occurs when you try to print it, read/write it or open it. As others mentioned above adding .encoding="utf-8" will help if you are trying to print it.


If you are trying to open scraped data and maybe write it into a file, then open the file with (......,encoding="utf-8")

with open(filename_csv , 'w', newline='',encoding="utf-8") as csv_file:

Angular HTML binding

Just to make for a complete answer, if your html content is in a component variable, you could also use:

<div [innerHTML]=componentVariableThatHasTheHtml></div>

How to make a div 100% height of the browser window

You need to do two things, one is to set the height to 100% which you already did. Second is set the position to absolute. That should do the trick.

body {
  height: 100%;
  min-height: 100%;
  position: absolute;


How to run a Runnable thread in Android at defined intervals?

Kotlin with Coroutines

In Kotlin, using coroutines you can do the following:

CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
    ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
        tv.append("Hello World")

Try it out here!

How to convert an Stream into a byte[] in C#?

The shortest solution I know:

using(var memoryStream = new MemoryStream())
  return memoryStream.ToArray();

How to destroy Fragment?

If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:


or if you are using supportLib, then you need to call:


SQL Server datetime LIKE select?

Try this

SELECT top 10 * from record WHERE  IsActive = 1 and CONVERT(VARCHAR, register_date, 120) LIKE '2020-01%'

Sorting A ListView By Column

i would recommend you to you datagridview, for heavy stuff.. it's include a lot of auto feature listviwe does not

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1

Instead of use ths,

data = [1,2,3,4]

Initialize static variables in C++ class?

I feel it is worth adding that a static variable is not the same as a constant variable.

using a constant variable in a class

struct Foo{
    const int a;
    Foo(int b) : a(b){}

and we would declare it like like so

fooA = new Foo(5);
fooB = new Foo(10);
// fooA.a = 5;
// fooB.a = 10;

For a static variable

struct Bar{
    static int a;
    Foo(int b){
        a = b;
Bar::a = 0; // set value for a

which is used like so

barA = new Bar(5);
barB = new Bar(10);
// barA.a = 10;
// barB.a = 10;
// Bar::a = 10;

You see what happens here. The constant variable, which is instanced along with each instance of Foo, as Foo is instanced has a separate value for each instance of Foo, and it can't be changed by Foo at all.

Where as with Bar, their is only one value for Bar::a no matter how many instances of Bar are made. They all share this value, you can also access it with their being any instances of Bar. The static variable also abides rules for public/private, so you could make it that only instances of Bar can read the value of Bar::a;

How to get current url in view in core 1.0

This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions, which adds extension to HttpRequest to get full URL; GetEncodedUrl.

e.g. from razor view:

@using Microsoft.AspNetCore.Http.Extensions
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>

Since 2.0, also have relative path and query GetEncodedPathAndQuery.

MySQL - how to front pad zip code with "0"?

you should use UNSIGNED ZEROFILL in your table structure.

Singleton design pattern vs Singleton beans in Spring container

Let's take the simplest example: you have an application and you just use the default classloader. You have a class which, for whatever reason, you decide that it should not have more than one instance in the application. (Think of a scenario where several people work on pieces of the application).

If you are not using the Spring framework, the Singleton pattern ensures that there will not be more than one instance of a class in your application. That is because you cannot instantiate instances of the class by doing 'new' because the constructor is private. The only way to get an instance of the class is to call some static method of the class (usually called 'getInstance') which always returns the same instance.

Saying that you are using the Spring framework in your application, just means that in addition to the regular ways of obtaining an instance of the class (new or static methods that return an instance of the class), you can also ask Spring to get you an instance of that class and Spring will ensure that whenever you ask it for an instance of that class it will always return the same instance, even if you didn't write the class using the Singleton pattern. In other words, even if the class has a public constructor, if you always ask Spring for an instance of that class, Spring will only call that constructor once during the life of your application.

Normally if you are using Spring, you should only use Spring to create instances, and you can have a public constructor for the class. But if your constructor is not private you are not really preventing anyone from creating new instances of the class directly, by bypassing Spring.

If you truly want a single instance of the class, even if you use Spring in your application and define the class in Spring to be a singleton, the only way to ensure that is also implement the class using the Singleton pattern. That ensures that there will be a single instance, whether people use Spring to get an instance or bypass Spring.

Is it possible to set UIView border properties from interface builder?

Rich86Man's answer is correct, but you can use categories to proxy properties such as layer.borderColor. (From the ConventionalC CocoaPod)


#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer(XibConfiguration)

// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;



#import "CALayer+XibConfiguration.h"

@implementation CALayer(XibConfiguration)

    self.borderColor = color.CGColor;

    return [UIColor colorWithCGColor:self.borderColor];


Interface Builder


The result will be apparent during runtime, not in Xcode.

Edit: You also need to set layer.borderWidth to at least 1 to see the border with the chosen color.

In Swift 2.0:

extension CALayer {
    var borderUIColor: UIColor {
        set {
            self.borderColor = newValue.CGColor

        get {
            return UIColor(CGColor: self.borderColor!)

In Swift 3.0:

extension CALayer {
    var borderUIColor: UIColor {
        set {
            self.borderColor = newValue.cgColor

        get {
            return UIColor(cgColor: self.borderColor!)

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  module_function :a

  def b
    puts "beee"

def test
  UsefulThings.b # Fails!  Not a module method


How to exclude a directory from ant fileset, based on directories contents

Here's an alternative, instead of adding an incomplete.flag file to every dir you want to exclude, generate a file that contains a listing of all the directories you want to exclude and then use the excludesfile attribute. Something like this:

<fileset dir="${basedir}" excludesfile="">
  <include name="locale/"/>
  <exclude name="locale/*/incomplete.flag">

Hope it helps.

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  


  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <button (click)="submit()">Submit</button>
export class AppComponent { 
  @ViewChild(Child) child:Child;


  someOtherMethod() {

Here is the updated plunkr:

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();


How to generate a random number between a and b in Ruby?

UPDATE: Ruby 1.9.3 Kernel#rand also accepts ranges


Converting to array may be too expensive, and it's unnecessary.





Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.

But anyway, generating array need resources, and solution you already wrote is the best, you can do.

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
console.log( newStr );  // "this-is-a-test"

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

var myStr = '';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
console.log( newStr );  // "this-is-a-test"

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

var myStr = '';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
console.log( newStr );  // "this-is-a-test"

How to get Client location using Google Maps API v3?

It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:

How do I access ViewBag from JS

try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

Best way to find if an item is in a JavaScript array?

First, implement indexOf in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras (also, the associated blog post). And then you can use indexOf without worrying about browser support. Here's a slightly optimised version of his indexOf implementation:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        return -1;

It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var i = -1, j = arr.length; ++i < j;)
            if(arr[i] === obj) return true;
        return false;

I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;

// while loop

sum = 0;
int j = 1;

    sum = sum + j;


// do while loop

sum = 0;
j = 1;

    sum = sum + j;


In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

How can I print literal curly-brace characters in a string and also use .format on it?

I am ridiculously late to this party. I am having success placing the brackets in the replacement element, like this:

print('{0} {1}'.format('{hello}', '{world}'))

which prints

{hello} {world}

Strictly speaking this is not what OP is asking, as s/he wants the braces in the format string, but this may help someone.

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

How to remove a package in sublime text 2

If you installed with package control, search for "Package Control: Remove Package" in the command palette (accessed with Ctrl+Shift+P). Otherwise you can just remove the Emmet directory.

If you wish to use a custom caption to access commands, create Default.sublime-commands in your User folder. Then insert something similar to the following.

        "caption": "Package Control: Uninstall Package",
        "command": "remove_package"

Of course, you can customize the command and caption as you see fit.

How to set a header for a HTTP GET request, and trigger file download?

Pure jQuery.

  type: "GET",
  url: "",
  headers: {
    'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
  xhrFields: {
    responseType: 'blob'
  success: function (blob) {
    var windowUrl = window.URL || window.webkitURL;
    var url = windowUrl.createObjectURL(blob);
    var anchor = document.createElement('a');
    anchor.href = url; = '';;
  error: function (error) {

Can you find all classes in a package using reflection?

Here's how I do it. I scan all the subfolders (sub-packages) and I don't try to load anonymous classes:

   * Attempts to list all the classes in the specified package as determined
   * by the context class loader, recursively, avoiding anonymous classes
   * @param pckgname
   *            the package name to search
   * @return a list of classes that exist within that package
   * @throws ClassNotFoundException
   *             if something went wrong
  private static List<Class> getClassesForPackage(String pckgname) throws ClassNotFoundException {
      // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
      ArrayList<File> directories = new ArrayList<File>();
      String packageToPath = pckgname.replace('.', '/');
      try {
          ClassLoader cld = Thread.currentThread().getContextClassLoader();
          if (cld == null) {
              throw new ClassNotFoundException("Can't get class loader.");

          // Ask for all resources for the packageToPath
          Enumeration<URL> resources = cld.getResources(packageToPath);
          while (resources.hasMoreElements()) {
              directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
      } catch (NullPointerException x) {
          throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Null pointer exception)");
      } catch (UnsupportedEncodingException encex) {
          throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Unsupported encoding)");
      } catch (IOException ioex) {
          throw new ClassNotFoundException("IOException was thrown when trying to get all resources for " + pckgname);

      ArrayList<Class> classes = new ArrayList<Class>();
      // For every directoryFile identified capture all the .class files
      while (!directories.isEmpty()){
          File directoryFile  = directories.remove(0);             
          if (directoryFile.exists()) {
              // Get the list of the files contained in the package
              File[] files = directoryFile.listFiles();

              for (File file : files) {
                  // we are only interested in .class files
                  if ((file.getName().endsWith(".class")) && (!file.getName().contains("$"))) {
                      // removes the .class extension
                      int index = directoryFile.getPath().indexOf(packageToPath);
                      String packagePrefix = directoryFile.getPath().substring(index).replace('/', '.');;                          
                    try {                  
                      String className = packagePrefix + '.' + file.getName().substring(0, file.getName().length() - 6);                            
                    } catch (NoClassDefFoundError e)
                      // do nothing. this class hasn't been found by the loader, and we don't care.
                  } else if (file.isDirectory()){ // If we got to a subdirectory
                      directories.add(new File(file.getPath()));                          
          } else {
              throw new ClassNotFoundException(pckgname + " (" + directoryFile.getPath() + ") does not appear to be a valid package");
      return classes;

How to escape single quotes within single quoted strings

shell_escape () {
    printf '%s' "'${1//\'/\'\\\'\'}'"

Implementation explanation:

  • double quotes so we can easily output wrapping single quotes and use the ${...} syntax

  • bash's search and replace looks like: ${varname//search/replacement}

  • we're replacing ' with '\''

  • '\'' encodes a single ' like so:

    1. ' ends the single quoting

    2. \' encodes a ' (the backslash is needed because we're not inside quotes)

    3. ' starts up single quoting again

    4. bash automatically concatenates strings with no white space between

  • there's a \ before every \ and ' because that's the escaping rules for ${...//.../...} .

string="That's "'#@$*&^`(@#'
echo "original: $string"
echo "encoded:  $(shell_escape "$string")"
echo "expanded: $(bash -c "echo $(shell_escape "$string")")"

P.S. Always encode to single quoted strings because they are way simpler than double quoted strings.