Programs & Examples On #Breakpoints

A breakpoint is an intentional stopping or pausing place in a program, put in place for debugging purposes.

Eclipse - Unable to install breakpoint due to missing line number attributes

I had this problem while attempting to start Tomcat in debugging mode from Eclipse. I had an ANT build file taking care of the compile and deploy. After setting the debug flag to true (as mentioned in other answers) and redeploying the application it worked fine:

<javac srcdir="./src/java" destdir="./bin" debug="true">

NOTE: if you've just added the debug flag and recompiled you still need to redeploy your application to the server since this is where Eclipse is debugging the class files. Very obvious but easy to spend an hour or so scratching your head and wondering why it's not working (trust me).

Can I set a breakpoint on 'memory access' in GDB?

Use watch to see when a variable is written to, rwatch when it is read and awatch when it is read/written from/to, as noted above. However, please note that to use this command, you must break the program, and the variable must be in scope when you've broken the program:

Use the watch command. The argument to the watch command is an expression that is evaluated. This implies that the variabel you want to set a watchpoint on must be in the current scope. So, to set a watchpoint on a non-global variable, you must have set a breakpoint that will stop your program when the variable is in scope. You set the watchpoint after the program breaks.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

Yet another solution for me was to post-build the project that was unable to break into the main project's bin folder.

Break when a value changes using the Visual Studio debugger

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

Bootstrap 3 breakpoints and media queries

This issue has been discussed in https://github.com/twbs/bootstrap/issues/10203 By now, there is no plan to change Grid because compatibility reasons.

You can get Bootstrap from this fork, branch hs: https://github.com/antespi/bootstrap/tree/hs

This branch give you an extra breakpoint at 480px, so yo have to:

  1. Design for mobile first (XS, less than 480px)
  2. Add HS (Horizontal Small Devices) classes in your HTML: col-hs-*, visible-hs, ... and design for horizontal mobile devices (HS, less than 768px)
  3. Design for tablet devices (SM, less than 992px)
  4. Design for desktop devices (MD, less than 1200px)
  5. Design for large devices (LG, more than 1200px)

Design mobile first is the key to understand Bootstrap 3. This is the major change from BootStrap 2.x. As a rule template you can follow this (in LESS):

.template {
    /* rules for mobile vertical (< 480) */

    @media (min-width: @screen-hs-min) {
       /* rules for mobile horizontal (480 > 768)  */
    }
    @media (min-width: @screen-sm-min) {
       /* rules for tablet (768 > 992) */
    }
    @media (min-width: @screen-md-min) {
       /* rules for desktop (992 > 1200) */
    }
    @media (min-width: @screen-lg-min) {
       /* rules for large (> 1200) */
    }
}

Why aren't Xcode breakpoints functioning?

Another reason the breakpoints can turn yellow is if the application binary you are debugging has been modified since it was first run. In my case, I added a folder to the application's Contents/Resources folder after having debugged the program once. On the debug run after adding the folder, the breakpoints turned yellow and were ignored. I modified my procedure: I did a clean, a build, added the folder, then ran, and all was well.

Perhaps Xcode (or OS X) creates and remembers its own digital signature of the application (which was not digitally signed) and then, sensing that the application was modified, refuses to try to set breakpoints. By making my mods before the first (debug) run of the application, the digital signature was made with my mods.

All this on OS X 10.6.8 using Xcode 3.2.2.

How to set a JavaScript breakpoint from code in Chrome?

You can use debugger; within your code. If the developer console is open, execution will break. It works in firebug as well.

Bootstrap 3 collapsed menu doesn't close on click

Though the solution posted earlier to change the menu item itself, like below, works when the menu is on a small device, it has a side effect when the menu is on full width and expanded, this can result in a horizontal scrollbar sliding over your menu items. The javascript solutions do not have this side-effect.

<li><a href="#one">One</a></li> to 
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#one">One</a></li>  

(sorry for answering like this, wanted to add a comment to that answer, but, seems I haven't sufficient credit to make remarks )

Limiting floats to two decimal points

To round a number to a resolution, the best way is the following one, which can work with any resolution (0.01 for two decimals or even other steps):

>>> import numpy as np
>>> value = 13.949999999999999
>>> resolution = 0.01
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
13.95

>>> resolution = 0.5
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
14.0

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

How do I set a checkbox in razor view?

You can do this with @Html.CheckBoxFor():

@Html.CheckBoxFor(m => m.AllowRating, new{@checked=true });

or you can also do this with a simple @Html.CheckBox():

@Html.CheckBox("AllowRating", true) ;

Excel Date to String conversion

In Excel 2010, marg's answer only worked for some of the data I had in my spreadsheet (it was imported). The following solution worked on all data.

Sub change()
    toText Selection
End Sub

Sub toText(target As range)
Dim cell As range
Dim txt As String
    For Each cell In target
        txt = cell.text
        cell.NumberFormat = "@"
        cell.Value2 = txt
    Next cell
End Sub

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

Could not find module "@angular-devkit/build-angular"

Solution

Execute below Command on your CLI :

  • npm install

When do I need a fb:app_id or fb:admins?

I think the documentation is reasonably helpful!

If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.

So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.

If you do use og, then set type to: blog

Finally: fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Code formatting shortcuts in Android Studio for Operation Systems

Check Keyboard Commands given in the Android Studio Tips & Trick documentation:

Enter image description here

MySQL timestamp select date range

I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.

SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'

Use LIKE and post data wild character search. Hopefully this will solve your problem.

Change header background color of modal of twitter bootstrap

You can solve this by simply adding class to modal-header

<div class="modal-header bg-primary text-white">

How can I get the index from a JSON object with value?

You can use Array.findIndex.

_x000D_
_x000D_
var data= [{
  "name": "placeHolder",
  "section": "right"
}, {
  "name": "Overview",
  "section": "left"
}, {
  "name": "ByFunction",
  "section": "left"
}, {
  "name": "Time",
  "section": "left"
}, {
  "name": "allFit",
  "section": "left"
}, {
  "name": "allbMatches",
  "section": "left"
}, {
  "name": "allOffers",
  "section": "left"
}, {
  "name": "allInterests",
  "section": "left"
}, {
  "name": "allResponses",
  "section": "left"
}, {
  "name": "divChanged",
  "section": "right"
}];
var index = data.findIndex(obj => obj.name=="allInterests");

console.log(index);
_x000D_
_x000D_
_x000D_

Swift: How to get substring from start to last index of character

Just accessing backward

The best way is to use substringToIndex combined to the endIndexproperty and the advance global function.

var string1 = "www.stackoverflow.com"

var index1 = advance(string1.endIndex, -4)

var substring1 = string1.substringToIndex(index1)

Looking for a string starting from the back

Use rangeOfString and set options to .BackwardsSearch

var string2 = "www.stackoverflow.com"

var index2 = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex

var substring2 = string2.substringToIndex(index2!)

No extensions, pure idiomatic Swift

Swift 2.0

advance is now a part of Index and is called advancedBy. You do it like:

var string1 = "www.stackoverflow.com"

var index1 = string1.endIndex.advancedBy(-4)

var substring1 = string1.substringToIndex(index1)

Swift 3.0

You can't call advancedBy on a String because it has variable size elements. You have to use index(_, offsetBy:).

var string1 = "www.stackoverflow.com"

var index1 = string1.index(string1.endIndex, offsetBy: -4)

var substring1 = string1.substring(to: index1)

A lot of things have been renamed. The cases are written in camelCase, startIndex became lowerBound.

var string2 = "www.stackoverflow.com"

var index2 = string2.range(of: ".", options: .backwards)?.lowerBound

var substring2 = string2.substring(to: index2!)

Also, I wouldn't recommend force unwrapping index2. You can use optional binding or map. Personally, I prefer using map:

var substring3 = index2.map(string2.substring(to:))

Swift 4

The Swift 3 version is still valid but now you can now use subscripts with indexes ranges:

let string1 = "www.stackoverflow.com"

let index1 = string1.index(string1.endIndex, offsetBy: -4)

let substring1 = string1[..<index1]

The second approach remains unchanged:

let string2 = "www.stackoverflow.com"

let index2 = string2.range(of: ".", options: .backwards)?.lowerBound

let substring3 = index2.map(string2.substring(to:))

How to pass an array within a query string?

Check the parse_string function http://php.net/manual/en/function.parse-str.php

It will return all the variables from a query string, including arrays.

Example from php.net:

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

Website screenshots

Well, PhantomJS is a browser that can be easily put on a server and integrate it to php. You can find the code in WDudes. They have included lot more features like specifying the image size, cache, download as a file or display in img src etc.

<img src=”screenshot.php?url=google.com” />

URL Parameters

  • Width and Height: screenshot.php?url=google.com&w=1000&h=800

  • With cropping: screenshot.php?url=google.com&w=1000&h=800&clipw=800&cliph=600

  • Disable cache and load fresh screesnhot:
    screenshot.php?url=google.com&cache=0

  • To download the image: screenshot.php?url=google.com&download=true

You can see the tutorial here: Capture Screenshot of a Website using PHP without API

Regex pattern including all special characters

Please use this.. it is simplest.

\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

    StringBuilder builder = new StringBuilder(checkstring);
    String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
    //change your all special characters to "" 
    Pattern  pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(builder.toString());
    checkstring=matcher.replaceAll("");

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

How to prevent Google Colab from disconnecting?

I was looking for a solution until I found a Python3 that randomly moves the mouse back and forth and clicks, always on the same place, but that's enough to fool Colab into thinking I'm active on the notebook and not disconnect.

import numpy as np
import time
import mouse
import threading

def move_mouse():
    while True:
        random_row = np.random.random_sample()*100
        random_col = np.random.random_sample()*10
        random_time = np.random.random_sample()*np.random.random_sample() * 100
        mouse.wheel(1000)
        mouse.wheel(-1000)
        mouse.move(random_row, random_col, absolute=False, duration=0.2)
        mouse.move(-random_row, -random_col, absolute=False, duration = 0.2)
        mouse.LEFT
        time.sleep(random_time)


x = threading.Thread(target=move_mouse)
x.start()

You need to install the needed packages: sudo -H pip3 install <package_name> You just need to run it (in your local machine) with sudo (as it takes control of the mouse) and it should work, allowing you to take full advantage of Colab's 12h sessions.

Credits: For those using Colab (Pro): Preventing Session from disconnecting due to inactivity

Background color not showing in print preview

I used purgatory101's answer but had trouble keeping all colours (icons, backgrounds, text colours etc...), especially that CSS stylesheets cannot be used with libraries which dynamically change DOM element's colours. Therefore here is a script that changes element's styles (background-colour and colour) before printing and clears styles once printing is done. It is useful to avoid writing a lot of CSS in a @media print stylesheet as it works whatever the page structure.

There is a part of the script that is specially made to keep FontAwesome icons color (or any element that uses a :before selector to insert coloured content).

JSFiddle showing the script in action

Compatibility: works in Chrome, I did not test other browsers.

function setColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var eltBackground = $(elements[i]).css('background-color');
    var eltColor = $(elements[i]).css('color');

    var elementStyle = elements[i].style;
    if (eltBackground) {
      elementStyle.oldBackgroundColor = {
        value: elementStyle.backgroundColor,
        importance: elementStyle.getPropertyPriority('background-color'),
      };
      elementStyle.setProperty('background-color', eltBackground, 'important');
    }
    if (eltColor) {
      elementStyle.oldColor = {
        value: elementStyle.color,
        importance: elementStyle.getPropertyPriority('color'),
      };
      elementStyle.setProperty('color', eltColor, 'important');
    }
  }
}

function resetColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var elementStyle = elements[i].style;

    if (elementStyle.oldBackgroundColor) {
      elementStyle.setProperty('background-color', elementStyle.oldBackgroundColor.value, elementStyle.oldBackgroundColor.importance);
      delete elementStyle.oldBackgroundColor;
    } else {
      elementStyle.setProperty('background-color', '', '');
    }
    if (elementStyle.oldColor) {
      elementStyle.setProperty('color', elementStyle.oldColor.value, elementStyle.oldColor.importance);
      delete elementStyle.oldColor;
    } else {
      elementStyle.setProperty('color', '', '');
    }
  }
}

function setIconColors(icons) {
  var css = '';
  $(icons).each(function (k, elt) {
    var selector = $(elt)
      .parents()
      .map(function () { return this.tagName; })
      .get()
      .reverse()
      .concat([this.nodeName])
      .join('>');

    var id = $(elt).attr('id');
    if (id) {
      selector += '#' + id;
    }

    var classNames = $(elt).attr('class');
    if (classNames) {
      selector += '.' + $.trim(classNames).replace(/\s/gi, '.');
    }

    css += selector + ':before { color: ' + $(elt).css('color') + ' !important; }';
  });
  $('head').append('<style id="print-icons-style">' + css + '</style>');
}

function resetIconColors() {
  $('#print-icons-style').remove();
}

And then modify the window.print function to make it set the styles before printing and resetting them after.

window._originalPrint = window.print;
window.print = function() {
  setColors('body *');
  setIconColors('body .fa');
  window._originalPrint();
  setTimeout(function () {
    resetColors('body *');
    resetIconColors();
  }, 100);
}

The part that finds icons paths to create CSS for :before elements is a copy from this SO answer

MySQL: #126 - Incorrect key file for table

Try to run a repair command for each one of the tables involved in the query.

Use MySQL administrator, go to Catalog -> Select your Catalog -> Select a table -> Click the Maintenance button -> Repair -> Use FRM.

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']
]);

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']
]);

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation


Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

    public function getShow($id)
    {
        // get request to 'users/show/{id}'
    }

    public function postStore()
    {
        // POST request to 'users/store'
    }

}

Implicit Controller documentation


It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

How to find all combinations of coins when given some dollar value

semi-hack to get around the unique combination problem - force descending order:

$denoms = [1,5,10,25]
def all_combs(sum,last) 
  return 1 if sum == 0
  return $denoms.select{|d| d &le sum && d &le last}.inject(0) {|total,denom|
           total+all_combs(sum-denom,denom)}
end

This will run slow since it won't be memoized, but you get the idea.

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

How to handle login pop up window using Selenium WebDriver?

Use the approach where you send username and password in URL Request:

http://username:[email protected]

So just to make it more clear. The username is username password is password and the rest is usual URL of your test web

Works for me without needing any tweaks.

Sample Java code:

public static final String TEST_ENVIRONMENT = "the-site.com";
private WebDriver driver;

public void login(String uname, String pwd){
  String URL = "http://" + uname + ":" + pwd + "@" + TEST_ENVIRONMENT;
  driver.get(URL);
}

@Test
public void testLogin(){
   driver = new FirefoxDriver();
   login("Pavel", "UltraSecretPassword");
   //Assert...
}

Truncate to three decimals in Python

You can also use:

import math

nValeur = format(float(input('Quelle valeur ?    ')), '.3f')

In Python 3.6 it would work.

How to implement and do OCR in a C# project?

I'm using tesseract OCR engine with TessNet2 (a C# wrapper - http://www.pixel-technology.com/freeware/tessnet2/).

Some basic code:

using tessnet2;

...

Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
            }

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

How do you render primitives as wireframes in OpenGL?

glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

to switch on,

glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

to go back to normal.

Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird.

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How to get the current location latitude and longitude in android

try this, hope it will help you to get the current location, every time the location changes.

public class MyClass implements LocationListener {
    double currentLatitude, currentLongitude;

    public void onLocationChanged(Location location) {
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
    }
}

Proxy with express.js

First install express and http-proxy-middleware

npm install express http-proxy-middleware --save

Then in your server.js

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();
app.use(express.static('client'));

// Add middleware for http proxying 
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);

// Render your site
const renderIndex = (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);

app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');
});

In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.

http://localhost:3000/api/login redirect to http://localhost:8080/api/login

what is the use of xsi:schemaLocation?

According to the spec for locating Schemas

there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy

(thanks for being unambiguous, spec!)

and

in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.

So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation attribute), depending on your "community." If you specify a specific schemaLocation, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation or noNamespaceSchemaLocation attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).

Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd" typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd (so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.

C++: How to round a double to an int?

Casting to an int truncates the value. Adding 0.5 causes it to do proper rounding.

int y = (int)(x + 0.5);

How to create directory automatically on SD card

This will make folder in sdcard with Folder name you provide.

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
        if (!file.exists()) {
            file.mkdirs();
        }

How to add to an existing hash in Ruby

If you have a hash, you can add items to it by referencing them by key:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'

Here, like [ ] creates an empty array, { } will create a empty hash.

Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.

Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.

It's important to keep in mind that the specific nature of a key of a hash often matters:

hash = { :a => 'a' }

# Fetch with Symbol :a finds the right value
hash[:a]
# => 'a'

# Fetch with the String 'a' finds nothing
hash['a']
# => nil

# Assignment with the key :b adds a new entry
hash[:b] = 'Bee'

# This is then available immediately
hash[:b]
# => "Bee"

# The hash now contains both keys
hash
# => { :a => 'a', :b => 'Bee' }

Ruby on Rails confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.

You can also index on nearly anything, including classes, numbers, or other Hashes.

hash = { Object => true, Hash => false }

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil

Hashes can be converted to Arrays and vice-versa:

# Like many things, Hash supports .to_a
{ :a => 'a' }.to_a
# => [[:a, "a"]]

# Hash also has a handy Hash[] method to create new hashes from arrays
Hash[[[:a, "a"]]]
# => {:a=>"a"} 

When it comes to "inserting" things into a Hash you may do it one at a time, or use the merge method to combine hashes:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}

Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method:

hash = { :a => 'a' }

# Returns the result of hash combined with a new hash, but does not alter
# the original hash.
hash.merge(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Nothing has been altered in the original
hash
# => {:a=>'a'}

# Combine the two hashes and store the result in the original
hash.merge!(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Hash has now been altered
hash
# => {:a=>'a',:b=>'b'}

Like many methods on String and Array, the ! indicates that it is an in-place operation.

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

LINQ Group By and select collection

you can achive it with group join

var result = (from c in Customers
          join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
          Select new { customer = c, orderItems = g});

c is Customer and g is the customers order items.

jQuery select change show/hide div event

Use following JQuery. Demo

$(function() {
    $('#row_dim').hide(); 
    $('#type').change(function(){
        if($('#type').val() == 'parcel') {
            $('#row_dim').show(); 
        } else {
            $('#row_dim').hide(); 
        } 
    });
});

Regular Expression to match only alphabetic characters

In Ruby and other languages that support POSIX character classes in bracket expressions, you can do simply:

/\A[[:alpha:]]+\z/i

That will match alpha-chars in all Unicode alphabet languages. Easy peasy.

More info: http://en.wikipedia.org/wiki/Regular_expression#Character_classes http://ruby-doc.org/core-2.0/Regexp.html

How to open mail app from Swift

You can use simple mailto: links in iOS to open the mail app.

let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
  if #available(iOS 10.0, *) {
    UIApplication.shared.open(url)
  } else {
    UIApplication.shared.openURL(url)
  }    
}

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

How to add Google Maps Autocomplete search box?

To get latitude and longitude too, you can use this simple code:

<html>
<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('city2').value = place.name;
                document.getElementById('cityLat').value = place.geometry.location.lat();
                document.getElementById('cityLng').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
    <input type="hidden" id="city2" name="city2" />
    <input type="hidden" id="cityLat" name="cityLat" />
    <input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

Git - push current branch shortcut

You should take a look to a similar question in Default behavior of "git push" without a branch specified

Basically it explains how to set the default behavior to push your current branch just executing git push. Probably what you need is:

git config --global push.default current

Other options:

  • nothing : Do not push anything
  • matching : Push all matching branches
  • upstream/tracking : Push the current branch to whatever it is tracking
  • current : Push the current branch

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

http://technologyguid.com/android-sqlite-database-app-example/

Passing structs to functions

First, the signature of your data() function:

bool data(struct *sampleData)

cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:

bool data(struct sampleData *samples)

But in C++, you don't need to use struct at all actually. So this can simply become:

bool data(sampleData *samples)

Second, the sampleData struct is not known to data() at that point. So you should declare it before that:

struct sampleData {
    int N;
    int M;
    string sample_name;
    string speaker;
};

bool data(sampleData *samples)
{
    samples->N = 10;
    samples->M = 20;
    // etc.
}

And finally, you need to create a variable of type sampleData. For example, in your main() function:

int main(int argc, char *argv[]) {
    sampleData samples;
    data(&samples);
}

Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.

However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:

// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
    samples.N = 10;
    samples.M = 20;
    // etc.
}

int main(int argc, char *argv[]) {
    sampleData samples;

    // No need to pass a pointer here, since data() takes the
    // passed argument by reference.
    data(samples);
}

What is the difference between a static and const variable?

Static variables in the context of a class are shared between all instances of a class.

In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.

When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.

Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.

class myClass {
public:
     static const int TOTAL_NUMBER = 5;
     // some public stuff
private:
     // some stuff
};

find index of an int in a list

Use the .IndexOf() method of the list. Specs for the method can be found on MSDN.

How to find the sum of an array of numbers

var total = 0;
$.each(arr,function() {
    total += this;
});

android: how to use getApplication and getApplicationContext from non activity / service class

Sending your activity context to other classes could cause memoryleaks because holding that context alive is the reason that the GC can't dispose the object

jQuery $.cookie is not a function

The old version of jQuery Cookie has been deprecated, so if you're getting the error:

$.cookie is not a function

you should upgrade to the new version.

The API for the new version is also different - rather than using

$.cookie("yourCookieName");

you should use

Cookies.get("yourCookieName");

Difference between static and shared libraries?

-------------------------------------------------------------------------
|  +-  |    Shared(dynamic)       |   Static Library (Linkages)         |
-------------------------------------------------------------------------
|Pros: | less memory use          |   an executable, using own libraries|
|      |                          |     ,coming with the program,       |
|      |                          |   doesn't need to worry about its   |
|      |                          |   compilebility subject to libraries|
-------------------------------------------------------------------------
|Cons: | implementations of       |   bigger memory uses                |
|      | libraries may be altered |                                     |
|      | subject to OS  and its   |                                     |
|      | version, which may affect|                                     |
|      | the compilebility and    |                                     |
|      | runnability of the code  |                                     |
-------------------------------------------------------------------------

Set attribute without value

The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )

Unique constraint on multiple columns

This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.

  1. Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

Click OK in each window and you're done.

How to fill Dataset with multiple tables?

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("data source=.;uid=sa;pwd=123;database=shop");
    //SqlCommand cmd = new SqlCommand("select * from tblemployees", con);
    //SqlCommand cmd1 = new SqlCommand("select * from tblproducts", con);
    //SqlDataAdapter da = new SqlDataAdapter();

    //DataSet ds = new DataSet();
    //ds.Tables.Add("emp");
    //ds.Tables.Add("products");
    //da.SelectCommand = cmd;
    //da.Fill(ds.Tables["emp"]);
    //da.SelectCommand = cmd1;

    //da.Fill(ds.Tables["products"]);
    SqlDataAdapter da = new SqlDataAdapter("select * from tblemployees", con);
    DataSet ds = new DataSet();
    da.Fill(ds, "em");
    da = new SqlDataAdapter("select * from tblproducts", con);
    da.Fill(ds, "prod");

    GridView1.DataSource = ds.Tables["em"];
    GridView1.DataBind();
    GridView2.DataSource = ds.Tables["prod"];
    GridView2.DataBind();
}

Get Element value with minidom with Python

The above answer is correct, namely:

name[0].firstChild.nodeValue

However for me, like others, my value was further down the tree:

name[0].firstChild.firstChild.nodeValue

To find this I used the following:

def scandown( elements, indent ):
    for el in elements:
        print("   " * indent + "nodeName: " + str(el.nodeName) )
        print("   " * indent + "nodeValue: " + str(el.nodeValue) )
        print("   " * indent + "childNodes: " + str(el.childNodes) )
        scandown(el.childNodes, indent + 1)

scandown( doc.getElementsByTagName('text'), 0 )

Running this for my simple SVG file created with Inkscape this gave me:

nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c6d0>]
   nodeName: tspan
   nodeValue: None
   childNodes: [<DOM Text node "'MY STRING'">]
      nodeName: #text
      nodeValue: MY STRING
      childNodes: ()
nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c800>]
   nodeName: tspan
   nodeValue: None
   childNodes: [<DOM Text node "'MY WORDS'">]
      nodeName: #text
      nodeValue: MY WORDS
      childNodes: ()

I used xml.dom.minidom, the various fields are explained on this page, MiniDom Python.

bower proxy configuration

Add the below entry to your .bowerrc:

{
  "proxy":"http://<user>:<password>@<host>:<port>",
  "https-proxy":"http://<user>:<password>@<host>:<port>"
}

Also if your password contains any special character URL-encode it Eg: replace the @ character with %40

How to select the first row of each group?

Window functions:

Something like this should do the trick:

import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window

val df = sc.parallelize(Seq(
  (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
  (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
  (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
  (3,"cat8",35.6))).toDF("Hour", "Category", "TotalValue")

val w = Window.partitionBy($"hour").orderBy($"TotalValue".desc)

val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" === 1).drop("rn")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

This method will be inefficient in case of significant data skew.

Plain SQL aggregation followed by join:

Alternatively you can join with aggregated data frame:

val dfMax = df.groupBy($"hour".as("max_hour")).agg(max($"TotalValue").as("max_value"))

val dfTopByJoin = df.join(broadcast(dfMax),
    ($"hour" === $"max_hour") && ($"TotalValue" === $"max_value"))
  .drop("max_hour")
  .drop("max_value")

dfTopByJoin.show

// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows:

dfTopByJoin
  .groupBy($"hour")
  .agg(
    first("category").alias("category"),
    first("TotalValue").alias("TotalValue"))

Using ordering over structs:

Neat, although not very well tested, trick which doesn't require joins or window functions:

val dfTop = df.select($"Hour", struct($"TotalValue", $"Category").alias("vs"))
  .groupBy($"hour")
  .agg(max("vs").alias("vs"))
  .select($"Hour", $"vs.Category", $"vs.TotalValue")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

With DataSet API (Spark 1.6+, 2.0+):

Spark 1.6:

case class Record(Hour: Integer, Category: String, TotalValue: Double)

df.as[Record]
  .groupBy($"hour")
  .reduce((x, y) => if (x.TotalValue > y.TotalValue) x else y)
  .show

// +---+--------------+
// | _1|            _2|
// +---+--------------+
// |[0]|[0,cat26,30.9]|
// |[1]|[1,cat67,28.5]|
// |[2]|[2,cat56,39.6]|
// |[3]| [3,cat8,35.6]|
// +---+--------------+

Spark 2.0 or later:

df.as[Record]
  .groupByKey(_.Hour)
  .reduceGroups((x, y) => if (x.TotalValue > y.TotalValue) x else y)

The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins. These cane be also used with Structured Streaming in completed output mode.

Don't use:

df.orderBy(...).groupBy(...).agg(first(...), ...)

It may seem to work (especially in the local mode) but it is unreliable (see SPARK-16207, credits to Tzach Zohar for linking relevant JIRA issue, and SPARK-30335).

The same note applies to

df.orderBy(...).dropDuplicates(...)

which internally uses equivalent execution plan.

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

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;


string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

How do I find out my MySQL URL, host, port and username?

If you're already logged into the command line client try this:

mysql> select user();

It will output something similar to this:

+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.41 sec)

In my example above, I was logged in as root from localhost.

To find port number and other interesting settings use this command:

mysql> show variables;

How do I turn a python datetime into a string, with readable format date?

Here is how you can accomplish the same using python's general formatting function...

>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())

The formatting characters used here are the same as those used by strftime. Don't miss the leading : in the format specifier.

Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated...

>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())

Compare the above with the following strftime() alternative...

>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))

Moreover, the following is not going to work...

>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string

And so on...

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

[Vue warn]: Cannot find element

I've solved the problem by add attribute 'defer' to the 'script' element.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Just to be complete...

For 32 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

*******OR*******

For 64 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

This entry must be a DWORD, with the name being the name of your executable, that hosts the Webbrowser control; i.e.:

myappname.exe (DON'T USE "Contoso.exe" as in the MSDN web page...it's just a placeholder name)

Then give it a DWORD value, according to the table on:

http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation

I changed to 11001 decimal or 0x2AF9 hex --- (IE 11 EMULATION) since that isn't the DEFAULT value (if you have IE 11 installed -- or whatever version).

That MSDN article contains notes on several other Registry changes that affects Internet Explorer web browser behavior.

Is there a way to make HTML5 video fullscreen?

Most of the answers here are outdated.

It's now possible to bring any element into fullscreen using the Fullscreen API, although it's still quite a mess because you can't just call div.requestFullScreen() in all browsers, but have to use browser specific prefixed methods.

I've created a simple wrapper screenfull.js that makes it easier to use the Fullscreen API.

Current browser support is:

  • Chrome 15+
  • Firefox 10+
  • Safari 5.1+

Note that many mobile browsers don't seem to support a full screen option yet.

How to get the Parent's parent directory in Powershell?

You can simply chain as many split-path as you need:

$rootPath = $scriptPath | split-path | split-path

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

How do I activate a Spring Boot profile when running from IntelliJ?

I ended up adding the following to my build.gradle:

bootRun {
  environment SPRING_PROFILES_ACTIVE: environment.SPRING_PROFILES_ACTIVE ?: "local"
}

test {
  environment SPRING_PROFILES_ACTIVE: environment.SPRING_PROFILES_ACTIVE ?: "test"
}

So now when running bootRun from IntelliJ, it defaults to the "local" profile.

On our other environments, we will simply set the 'SPRING_PROFILES_ACTIVE' environment variable in Tomcat.

I got this from a comment found here: https://github.com/spring-projects/spring-boot/pull/592

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

How to find the number of days between two dates

To find the number of days between two dates, you use:

DATEDIFF ( d, startdate , enddate )

How to check if all inputs are not empty with jQuery

$('input').each(function() {
    if ($(this).val() != '') {
        console.log('all inputs filled');
    }
    else{
        console.log('theres an empty input');
        return false
    }
});

you might want to wrap this in a keyup function

How to change context root of a dynamic web project in Eclipse?

I just wanted to add that if you don't want your application name in the root context at all, you and just put "/" (no quotes, just the forward slash) in the Eclipse --> Web Project Settings --> Context Root entry

That will deploy the webapp to just http://localhost:8080/

Of course, this will cause problems with other webapps you try to run on the server, so heads up with that.

Took me forever to piece that together... so even though this post is 8 years old, hopefully this will still help someone!

Android: How to get a custom View's height and width?

Just got a solution to get height and width of a custom view:

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);

    viewWidth = xNew;
    viewHeight = yNew;
}

Its working in my case.

How to execute a stored procedure inside a select query

You can create a temp table matching your proc output and insert into it.

CREATE TABLE #Temp (
    Col1 INT
)

INSERT INTO #Temp
    EXEC MyProc

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

After trying many solutions, seems like the one that finally did the trick was to connect by IP. No longer file sockets getting deleted randomly.

Just update your MySQL client config (e.g. /usr/local/etc/my.cnf) with:

[client]
port = 3306
host=127.0.0.1
protocol=tcp

.gitignore exclude folder but include specific subfolder

I've found only this actually works.

**/node_modules/*
!**/node_modules/keep-dir

How to compare strings in an "if" statement?

You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).

The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."

convert pfx format to p12

If you are looking for a quick and manual process with UI. I always use Mozilla Firefox to convert from PFX to P12. First import the certificate into the Firefox browser (Options > Privacy & Security > View Certificates... > Import...). Once installed, perform the export to create the P12 file by choosing the certificate name from the Certificate Manager and then click Backup... and enter the file name and then enter the password.

Apache shows PHP code instead of executing it

In my case with PHP7.3 Apache2.4 Ubuntu 18.04 I had to execute:

$ a2enmod actions fastcgi alias proxy_fcgi

How to make a GUI for bash scripts?

You could use dialog that is ncurses based or whiptail that is slang based.

I think both have GTK or Tcl/Tk bindings.

Using BigDecimal to work with currencies

Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.

Please see a short clip https://youtu.be/EXxUSz9x7BM

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

How can I set the current working directory to the directory of the script in Bash?

This script seems to work for me:

#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd

The pwd command line echoes the location of the script as the current working directory no matter where I run it from.

NULL values inside NOT IN clause

this is for Boy:

select party_code 
from abc as a
where party_code not in (select party_code 
                         from xyz 
                         where party_code = a.party_code);

this works regardless of ansi settings

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

@Autowired(required=false) By default the dependency injection for @Autowired must be fulfilled because the value of required attribute is true by default. We can change this behavior by using @Autowired(required=false). In this case if bean is not found for dependency injection, it will not through error.

Please have look at https://www.concretepage.com/spring/spring-autowired-annotation#required-false

But @Inject doesn’t need (required=false) it will not through error if dependency is not found

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

Check if multiple strings exist in another string

You can use any:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

Similarly to check if all the strings from the list are found, use all instead of any.

Timer function to provide time in nano seconds using C++

To do this correctly you can use one of two ways, either go with RDTSC or with clock_gettime(). The second is about 2 times faster and has the advantage of giving the right absolute time. Note that for RDTSC to work correctly you need to use it as indicated (other comments on this page have errors, and may yield incorrect timing values on certain processors)

inline uint64_t rdtsc()
{
    uint32_t lo, hi;
    __asm__ __volatile__ (
      "xorl %%eax, %%eax\n"
      "cpuid\n"
      "rdtsc\n"
      : "=a" (lo), "=d" (hi)
      :
      : "%ebx", "%ecx" );
    return (uint64_t)hi << 32 | lo;
}

and for clock_gettime: (I chose microsecond resolution arbitrarily)

#include <time.h>
#include <sys/timeb.h>
// needs -lrt (real-time lib)
// 1970-01-01 epoch UTC time, 1 mcs resolution (divide by 1M to get time_t)
uint64_t ClockGetTime()
{
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    return (uint64_t)ts.tv_sec * 1000000LL + (uint64_t)ts.tv_nsec / 1000LL;
}

the timing and values produced:

Absolute values:
rdtsc           = 4571567254267600
clock_gettime   = 1278605535506855

Processing time: (10000000 runs)
rdtsc           = 2292547353
clock_gettime   = 1031119636

Change background color of iframe issue

It is possible. With vanilla Javascript, you can use the function below for reference.

function updateIframeBackground(iframeId) {
    var x = document.getElementById(iframeId);
    var y = (x.contentWindow || x.contentDocument);
    if (y.document) y = y.document;
    y.body.style.backgroundColor = "#2D2D2D";
}

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_iframe_contentdocument

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I'm not familiar with SSRS, but you can get the beginning and end of the previous month in VB.Net using the DateTime constructor, like this:

Dim prevMonth As DateTime = yourDate.AddMonths(-1)

Dim prevMonthStart As New DateTime(prevMonth.Year, prevMonth.Month, 1)
Dim prevMonthEnd As New DateTime(prevMonth.Year, prevMonth.Month, DateTime.DaysInMonth(prevMonth.Year, prevMonth.Month))

(yourDate can be any DateTime object, such as DateTime.Today or #12/23/2003#)

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Get folder up one level

You can try

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

What does map(&:name) mean in Ruby?

Josh Lee's answer is almost correct except that the equivalent Ruby code should have been as follows.

class Symbol
  def to_proc
    Proc.new do |receiver|
      receiver.send self
    end
  end
end

not

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args
    end
  end
end

With this code, when print [[1,'a'],[2,'b'],[3,'c']].map(&:first) is executed, Ruby splits the first input [1,'a'] into 1 and 'a' to give obj 1 and args* 'a' to cause an error as Fixnum object 1 does not have the method self (which is :first).


When [[1,'a'],[2,'b'],[3,'c']].map(&:first) is executed;

  1. :first is a Symbol object, so when &:first is given to a map method as a parameter, Symbol#to_proc is invoked.

  2. map sends call message to :first.to_proc with parameter [1,'a'], e.g., :first.to_proc.call([1,'a']) is executed.

  3. to_proc procedure in Symbol class sends a send message to an array object ([1,'a']) with parameter (:first), e.g., [1,'a'].send(:first) is executed.

  4. iterates over the rest of the elements in [[1,'a'],[2,'b'],[3,'c']] object.

This is the same as executing [[1,'a'],[2,'b'],[3,'c']].map(|e| e.first) expression.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

symfony2 : failed to write cache directory

if symfony version less than 2.8

_x000D_
_x000D_
sudo chmod -R 777 app/cache/*
_x000D_
_x000D_
_x000D_

if symfony version great than or equal 3.0

_x000D_
_x000D_
sudo chmod -R 777 var/cache/*
_x000D_
_x000D_
_x000D_

Finding three elements in an array whose sum is closest to a given number

Is there any efficient algorithm other than brute force search to find the three integers?

Yep; we can solve this in O(n2) time! First, consider that your problem P can be phrased equivalently in a slightly different way that eliminates the need for a "target value":

original problem P: Given an array A of n integers and a target value S, does there exist a 3-tuple from A that sums to S?

modified problem P': Given an array A of n integers, does there exist a 3-tuple from A that sums to zero?

Notice that you can go from this version of the problem P' from P by subtracting your S/3 from each element in A, but now you don't need the target value anymore.

Clearly, if we simply test all possible 3-tuples, we'd solve the problem in O(n3) -- that's the brute-force baseline. Is it possible to do better? What if we pick the tuples in a somewhat smarter way?

First, we invest some time to sort the array, which costs us an initial penalty of O(n log n). Now we execute this algorithm:

for (i in 1..n-2) {
  j = i+1  // Start right after i.
  k = n    // Start at the end of the array.

  while (k >= j) {
    // We got a match! All done.
    if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])

    // We didn't match. Let's try to get a little closer:
    //   If the sum was too big, decrement k.
    //   If the sum was too small, increment j.
    (A[i] + A[j] + A[k] > 0) ? k-- : j++
  }
  // When the while-loop finishes, j and k have passed each other and there's
  // no more useful combinations that we can try with this i.
}

This algorithm works by placing three pointers, i, j, and k at various points in the array. i starts off at the beginning and slowly works its way to the end. k points to the very last element. j points to where i has started at. We iteratively try to sum the elements at their respective indices, and each time one of the following happens:

  • The sum is exactly right! We've found the answer.
  • The sum was too small. Move j closer to the end to select the next biggest number.
  • The sum was too big. Move k closer to the beginning to select the next smallest number.

For each i, the pointers of j and k will gradually get closer to each other. Eventually they will pass each other, and at that point we don't need to try anything else for that i, since we'd be summing the same elements, just in a different order. After that point, we try the next i and repeat.

Eventually, we'll either exhaust the useful possibilities, or we'll find the solution. You can see that this is O(n2) since we execute the outer loop O(n) times and we execute the inner loop O(n) times. It's possible to do this sub-quadratically if you get really fancy, by representing each integer as a bit vector and performing a fast Fourier transform, but that's beyond the scope of this answer.


Note: Because this is an interview question, I've cheated a little bit here: this algorithm allows the selection of the same element multiple times. That is, (-1, -1, 2) would be a valid solution, as would (0, 0, 0). It also finds only the exact answers, not the closest answer, as the title mentions. As an exercise to the reader, I'll let you figure out how to make it work with distinct elements only (but it's a very simple change) and exact answers (which is also a simple change).

How do I remove the blue styling of telephone numbers on iPhone/iOS?

<meta name="format-detection" content="telephone=no">. This metatag works in the default Safari browser on iOS devices and will only work for telephone numbers that are not wrapped in a telephone link so

1-800-123-4567
<a href="tel:18001234567">1-800-123-4567</a>

the first line will not be formatted as a link if you specify the metatag but the second line will because it's wrapped in a telephone anchor.


You can forego the metatag all-together and use a mixin such as

a[href^=tel]{
    color:inherit;
    text-decoration:inherit;
    font-size:inherit;
    font-style:inherit;
    font-weight:inherit;
}

to maintain intended styling of your telephone numbers, but you must make sure you wrap them in a telephone anchor.

If you want to be extra cautious and protect against the event of a telephone number which is not properly formatted with a wrapping anchor tag you can drill through the DOM and adjust with this script. Adjust the replacement pattern as desired.

$('body').html($('body').html().replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g, '<a href="tel:+1$1$2$3">($1) $2-$3</a>'));

or even better without jQuery

document.body.innerHTML = document.body.innerHTML.replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,'<a href="tel:+1$1$2$3">($1) $2-$3</a>');

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

Google Maps JavaScript API RefererNotAllowedMapError

This is another sh1tty Google product with a terrible implemenation.

The problem I have found with this is that if you restrict an API key by IP address, it wont work... BUT far be it from Google to make this point clear... It wasn't until troubleshooting and researching I found:

API keys with an IP addresses restriction can only be used with web services that are intended for use from the server side (such as the Geocoding API and other Web Service APIs). Most of these web services have equivalent services within the Maps JavaScript API (for example, see the Geocoding Service). To use the Maps JavaScript API client side services, you will need to create a separate API key which can be secured with an HTTP referrers restriction (see Restricting an API key).

https://developers.google.com/maps/documentation/javascript/error-messages

FFS Google... Pretty important piece of information that would be good to clarify on setup...

Is there a simple way to remove unused dependencies from a maven pom.xml?

I had similar kind of problem and decided to write a script that removes dependencies for me. Using that I got over half of the dependencies away rather easily.

http://samulisiivonen.blogspot.com/2012/01/cleanin-up-maven-dependencies.html

Setting the default Java character encoding

I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer String.getBytes("charsetName"). That way your application is not dependent on things beyond its control.

I personally feel that String.getBytes() should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.

ASP.Net MVC 4 Form with 2 submit buttons/actions

You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:

<form id="myForm">
    <%-- form data inputs here ---%>
    <button id="edit">Edit</button>
    <button id="validate">Validate</button>
</form>

you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):

<script type="text/javascript">
      $("#edit").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Edit","MyController")");
          form.submit();
      });

      $("#validate").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Validate","MyController")");
          form.submit();
      });
</script>

Rename a column in MySQL

Rename MySQL Column with ALTER TABLE Command

ALTER TABLE is an essential command used to change the structure of a MySQL table. You can use it to add or delete columns, change the type of data within the columns, and even rename entire databases. The function that concerns us the most is how to utilize ALTER TABLE to rename a column.

Clauses give us additional control over the renaming process. The RENAME COLUMN and CHANGE clause both allow for the names of existing columns to be altered. The difference is that the CHANGE clause can also be used to alter the data types of a column. The commands are straightforward, and you may use the clause that fits your requirements best.

How to Use the RENAME COLUMN Clause (MySQL 8.0)

The simplest way to rename a column is to use the ALTER TABLE command with the RENAME COLUMN clause. This clause is available since MySQL version 8.0.

Let’s illustrate its simple syntax. To change a column name, enter the following statement in your MySQL shell:

ALTER TABLE your_table_name RENAME COLUMN original_column_name TO new_column_name;

Exchange the your_table_name, original_column_name, and new_column_name with your table and column names. Keep in mind that you cannot rename a column to a name that already exists in the table.

Note: The word COLUMN is obligatory for the ALTER TABLE RENAME COLUMN command. ALTER TABLE RENAME is the existing syntax to rename the entire table.

The RENAME COLUMN clause can only be used to rename a column. If you need additional functions, such as changing the data definition, or position of a column, you need to use the CHANGE clause instead.

Rename MySQL Column with CHANGE Clause

The CHANGE clause offers important additions to the renaming process. It can be used to rename a column and change the data type of that column with the same command.

Enter the following command in your MySQL client shell to change the name of the column and its definition:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name data_type;

The data_type element is mandatory, even if you want to keep the existing datatype.

Use additional options to further manipulate table columns. The CHANGE also allows you to place the column in a different position in the table by using the optional FIRST | AFTER column_name clause. For example:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name y_data_type AFTER column_x;

You have successfully changed the name of the column, changed the data type to y_data_type, and positioned the column after column_x.

HashSet vs. List performance

The answer, as always, is "It depends". I assume from the tags you're talking about C#.

Your best bet is to determine

  1. A Set of data
  2. Usage requirements

and write some test cases.

It also depends on how you sort the list (if it's sorted at all), what kind of comparisons need to be made, how long the "Compare" operation takes for the particular object in the list, or even how you intend to use the collection.

Generally, the best one to choose isn't so much based on the size of data you're working with, but rather how you intend to access it. Do you have each piece of data associated with a particular string, or other data? A hash based collection would probably be best. Is the order of the data you're storing important, or are you going to need to access all of the data at the same time? A regular list may be better then.

Additional:

Of course, my above comments assume 'performance' means data access. Something else to consider: what are you looking for when you say "performance"? Is performance individual value look up? Is it management of large (10000, 100000 or more) value sets? Is it the performance of filling the data structure with data? Removing data? Accessing individual bits of data? Replacing values? Iterating over the values? Memory usage? Data copying speed? For example, If you access data by a string value, but your main performance requirement is minimal memory usage, you might have conflicting design issues.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

How can I return the sum and average of an int array?

Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:

decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();

Create a circular button in BS3

Use font-awesome stacked icons (alternative to bootstrap badges). Here are more examples: http://fontawesome.io/examples/

_x000D_
_x000D_
 .no-border {_x000D_
        border: none;_x000D_
        background-color: white;_x000D_
        outline: none;_x000D_
        cursor: pointer;_x000D_
    }_x000D_
.color-no-focus {_x000D_
        color: grey;_x000D_
    }_x000D_
  .hover:hover {_x000D_
        color: blue;_x000D_
    }_x000D_
 .white {_x000D_
        color: white;_x000D_
    }
_x000D_
<button type="button" (click)="doSomething()" _x000D_
class="hover color-no-focus no-border fa-stack fa-lg">_x000D_
<i class="color-focus fa fa-circle fa-stack-2x"></i>_x000D_
<span class="white fa-stack-1x">1</span>_x000D_
</button>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
_x000D_
_x000D_

how to set value of a input hidden field through javascript?

It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/

Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:

<form name="FormName">
    <input type="hidden" name="checkyear" id="checkyear" value="">
</form>

Have you considered using the jQuery Library? Here are the docs for .val() function.

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

Passing variables in remote ssh command

(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

You can feed data right through the standard input of the ssh command and read that from the remote location.

In the following example,

  1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
  2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
  3. In the shh command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb

# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
    FOO
    BAR
)

for name in "${VAR_NAMES[@]}"
do
    printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
    while read -rd '"''"' name value
    do
        export "$name"="$value"
    done

    # Check
    printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'

Output:

FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]

If you don’t need to export those, you should be able to use declare instead of export.

A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

$ ssh [email protected] 'read foo' <<< "$foo"

Can I restore a single table from a full mysql mysqldump file?

You can import single table using terminal line as given below. Here import single user table into specific database.

mysql -u root -p -D my_database_name < var/www/html/myproject/tbl_user.sql

Plot different DataFrames in the same figure

If you a running Jupyter/Ipython notebook and having problems using;

ax = df1.plot()

df2.plot(ax=ax)

Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    Android Studio - Emulator - eglSurfaceAttrib not implemented

    Fix: Unlock your device before running it.

    Hi Guys: Think I may have a fix for this:

    Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

    Get the value of input text when enter key pressed

    Just using the event object

    function search(e) {
        e = e || window.event;
        if(e.keyCode == 13) {
            var elem = e.srcElement || e.target;
            alert(elem.value);
        }
    }
    

    The most efficient way to remove first N elements in a list?

    You can use list slicing to archive your goal:

    n = 5
    mylist = [1,2,3,4,5,6,7,8,9]
    newlist = mylist[n:]
    print newlist
    

    Outputs:

    [6, 7, 8, 9]
    

    Or del if you only want to use one list:

    n = 5
    mylist = [1,2,3,4,5,6,7,8,9]
    del mylist[:n]
    print mylist
    

    Outputs:

    [6, 7, 8, 9]
    

    Recommended way to save uploaded files in a servlet application

    Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

    1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

    2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

    3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

    It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

    The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

    So, the path to the final storage location can be definied in either of the following ways:

    • Hardcoded:

        File uploads = new File("/path/to/uploads");
      
    • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

        File uploads = new File(System.getenv("UPLOAD_LOCATION"));
      
    • VM argument during server startup via -Dupload.location="/path/to/uploads":

        File uploads = new File(System.getProperty("upload.location"));
      
    • *.properties file entry as upload.location=/path/to/uploads:

        File uploads = new File(properties.getProperty("upload.location"));
      
    • web.xml <context-param> with name upload.location and value /path/to/uploads:

        File uploads = new File(getServletContext().getInitParameter("upload.location"));
      
    • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

        File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
      

    Either way, you can easily reference and save the file as follows:

    File file = new File(uploads, "somefilename.ext");
    
    try (InputStream input = part.getInputStream()) {
        Files.copy(input, file.toPath());
    }
    

    Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

    File file = File.createTempFile("somefilename-", ".ext", uploads);
    
    try (InputStream input = part.getInputStream()) {
        Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    

    How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

    Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

    See also:

    Create a zip file and download it

    I just ran into this problem. For me the issue was with:

    readfile("$archive_file_name");
    

    It was resulting in a out of memory error.

    Allowed memory size of 134217728 bytes exhausted (tried to allocate 292982784 bytes)
    

    I was able to correct the problem by replacing readfile() with the following:

        $handle = fopen($zipPath, "rb");
        while (!feof($handle)){
            echo fread($handle, 8192);
        }
        fclose($handle);
    

    Not sure if this is your same issue or not seeing that your file is only 1.2 MB. Maybe this will help someone else with a similar problem.

    Top 5 time-consuming SQL queries in Oracle

    It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.

    How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

    Try this:

    tar -czf my.tar.gz dir/
    

    But are you sure you are not compressing some .exe file or something? Maybe the problem is not with te compression, but with the files you are compressing?

    What does numpy.random.seed(0) do?

    I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.

    Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.

    What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.

    Find the number of employees in each department - SQL Oracle

    A request to list "Number of employees in each department" or "Display how many people work in each department" is the same as "For each department, list the number of employees", this must include departments with no employees. In the sample database, Operations has 0 employees. So a LEFT OUTER JOIN should be used.

    SELECT dept.name, COUNT(emp.empno) AS count
    FROM dept
    LEFT OUTER JOIN emp ON emp.deptno = dept.deptno
    GROUP BY dept.name;
    

    How to implement LIMIT with SQL Server?

    This is a multi step approach that will work in SQL2000.

    -- Create a temp table to hold the data
    CREATE TABLE #foo(rowID int identity(1, 1), myOtherColumns)
    
    INSERT INTO #foo (myColumns) SELECT myData order By MyCriteria
    
    Select * FROM #foo where rowID > 10
    

    Convert String to Float in Swift

    Below will give you an optional Float, stick a ! at the end if you know it to be a Float, or use if/let.

    let wageConversion = Float(wage.text)
    

    A Space between Inline-Block List Items

    Even if its not inline-block based, this solution might worth consideration (allows nearly same formatting control from upper levels).

    ul {
      display: table;
    }
    ul li {
      display: table-cell;
    }
    

    Docker expose all ports or range of ports from 7000 to 8000

    Since Docker 1.5 you can now expose a range of ports to other linked containers using:

    The Dockerfile EXPOSE command:

    EXPOSE 7000-8000

    or The Docker run command:

    docker run --expose=7000-8000

    Or instead you can publish a range of ports to the host machine via Docker run command:

    docker run -p 7000-8000:7000-8000

    rm: cannot remove: Permission denied

    The code says everything:

    max@serv$ chmod 777 .
    

    Okay, it doesn't say everything.

    In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

    Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

    Sqlite convert string to date

    Saved date as TEXT( 20/10/2013 03:26 ) To do query and to select records between dates?

    Better version is:

    SELECT TIMSTARTTIMEDATE 
    FROM TIMER 
    WHERE DATE(substr(TIMSTARTTIMEDATE,7,4)
    ||substr(TIMSTARTTIMEDATE,4,2)
    ||substr(TIMSTARTTIMEDATE,1,2)) 
    BETWEEN DATE(20131020) AND DATE(20131021);
    

    the substr from 20/10/2013 gives 20131020 date format DATE(20131021) - that makes SQL working with dates and using date and time functions.

    OR

    SELECT TIMSTARTTIMEDATE 
    FROM TIMER 
    WHERE DATE(substr(TIMSTARTTIMEDATE,7,4)
    ||'-'
    ||substr(TIMSTARTTIMEDATE,4,2)
    ||'-'
    ||substr(TIMSTARTTIMEDATE,1,2)) 
    BETWEEN DATE('2013-10-20') AND DATE('2013-10-21');
    

    and here is in one line

    SELECT TIMSTARTTIMEDATE FROM TIMER WHERE DATE(substr(TIMSTARTTIMEDATE,7,4)||'-'||substr(TIMSTARTTIMEDATE,4,2)||'-'||substr(TIMSTARTTIMEDATE,1,2)) BETWEEN DATE('2013-10-20') AND DATE('2013-10-21');
    

    React - changing an uncontrolled input

    In my case, I was missing something really trivial.

    <input value={state.myObject.inputValue} />

    My state was the following when I was getting the warning:

    state = {
       myObject: undefined
    }
    

    By alternating my state to reference the input of my value, my issue was solved:

    state = {
       myObject: {
          inputValue: ''
       }
    }
    

    Calculating Pearson correlation and significance in Python

    Rather than rely on numpy/scipy, I think my answer should be the easiest to code and understand the steps in calculating the Pearson Correlation Coefficient (PCC) .

    import math
    
    # calculates the mean
    def mean(x):
        sum = 0.0
        for i in x:
             sum += i
        return sum / len(x) 
    
    # calculates the sample standard deviation
    def sampleStandardDeviation(x):
        sumv = 0.0
        for i in x:
             sumv += (i - mean(x))**2
        return math.sqrt(sumv/(len(x)-1))
    
    # calculates the PCC using both the 2 functions above
    def pearson(x,y):
        scorex = []
        scorey = []
    
        for i in x: 
            scorex.append((i - mean(x))/sampleStandardDeviation(x)) 
    
        for j in y:
            scorey.append((j - mean(y))/sampleStandardDeviation(y))
    
    # multiplies both lists together into 1 list (hence zip) and sums the whole list   
        return (sum([i*j for i,j in zip(scorex,scorey)]))/(len(x)-1)
    

    The significance of PCC is basically to show you how strongly correlated the two variables/lists are. It is important to note that the PCC value ranges from -1 to 1. A value between 0 to 1 denotes a positive correlation. Value of 0 = highest variation (no correlation whatsoever). A value between -1 to 0 denotes a negative correlation.

    Convert date from String to Date format in Dataframes

    Use to_date with Java SimpleDateFormat.

    TO_DATE(CAST(UNIX_TIMESTAMP(date, 'MM/dd/yyyy') AS TIMESTAMP))
    

    Example:

    spark.sql("""
      SELECT TO_DATE(CAST(UNIX_TIMESTAMP('08/26/2016', 'MM/dd/yyyy') AS TIMESTAMP)) AS newdate"""
    ).show()
    
    +----------+
    |        dt|
    +----------+
    |2016-08-26|
    +----------+
    

    Open and write data to text file using Bash?

    Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation

    VAR=Test
    vi FILE.txt <<EOFXX
    i
    #This is my var in text file
    var = $VAR
    #Thats end of text file
    ^[
    ZZ
    EOFXX
    

    Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.

    #This is my var in text file
    var = Test
    #Thats end of text file
    

    Javascript (+) sign concatenates instead of giving sum of variables

    You may also use this

    divID = "question-" + (i*1+1); 
    

    to be sure that i is converted to integer.

    Rename Files and Directories (Add Prefix)

    Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::Copy;
    use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module
    
    die "Usage: $0 dir prefix" unless (@ARGV >= 2);
    my ($dir, $pre) = @ARGV;
    
    opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
    my @files = readdir($dir_handle);
    close($dir_handle);
    
    $CWD = $dir; # cd to the directory, needs File::chdir
    
    foreach my $file (@files) {
      next if ($file =~ /^\.+$/); # avoid folders . and ..
      next if ($0 =~ /$file/); # avoid moving this script if it is in the directory
    
      move($file, $pre . $file) or warn "Cannot rename file $file: $!";
    }
    

    How to assign colors to categorical variables in ggplot2 that have stable mapping?

    The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

    library(ggplot2)
    dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
        x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
    dataset$fCategory <- factor(dataset$category)
    subdata <- subset(dataset, category %in% c("A", "D", "E"))
    

    With a character variable

    ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
    ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()
    

    With a factor variable

    ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
    ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
    

    MySQL Error 1215: Cannot add foreign key constraint

    I had the same problem.
    I solved it doing this:

    I created the following line in the
    primary key: (id int(11) unsigned NOT NULL AUTO_INCREMENT)

    I found out this solution after trying to import a table in my schema builder. If it works for you, let me know!

    Good luck!

    Felipe Tércio

    Why plt.imshow() doesn't display the image?

    plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

    axios post request to send form data

    Using application/x-www-form-urlencoded format in axios

    By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

    Browser

    In a browser, you can use the URLSearchParams API as follows:

    const params = new URLSearchParams();

    params.append('param1', 'value1');

    params.append('param2', 'value2');

    axios.post('/foo', params);

    Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

    Alternatively, you can encode data using the qs library:

    const qs = require('qs');

    axios.post('/foo', qs.stringify({ 'bar': 123 }));

    Or in another way (ES6),

    import qs from 'qs';

    const data = { 'bar': 123 };

    const options = {

    method: 'POST',

    headers: { 'content-type': 'application/x-www-form-urlencoded' },

    data: qs.stringify(data),

    url, };

    axios(options);

    replace special characters in a string python

    You can replace the special characters with the desired characters as follows,

    import string
    specialCharacterText = "H#y #@w @re &*)?"
    inCharSet = "!@#$%^&*()[]{};:,./<>?\|`~-=_+\""
    outCharSet = "                               " #corresponding characters in inCharSet to be replaced
    splCharReplaceList = string.maketrans(inCharSet, outCharSet)
    splCharFreeString = specialCharacterText.translate(splCharReplaceList)
    

    Do I need to pass the full path of a file in another directory to open()?

    The examples to os.walk in the documentation show how to do this:

    for root, dirs, filenames in os.walk(indir):
        for f in filenames:
            log = open(os.path.join(root, f),'r')
    

    How did you expect the "open" function to know that the string "1" is supposed to mean "/home/des/test/1" (unless "/home/des/test" happens to be your current working directory)?

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

    looks like bad architecture all the way. also you have not specified the type of app you need to notify to (web app / console app / winforms / service etc etc)

    nevertheless, to answer your question, there are multiple ways of solving this. you could use:

    1) timestamps if you were just interested in ensuring the next set of updates from the second app dont conflict with the updates from the first app

    2) sql dependency object - see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx for more info

    3) a custom push notification service which multiple clients (web / winform / service) can subscribe to and get notified on changes

    in short, you need to use the simplest and easiest and cheapest (in terms of efforts) solution based on how complex your notification requirements are and for what purpose you need to use them. dont try to build an overly complex notification system if a simple data concurrency is your only requirement (in that case go for a simple timestamp based solution)

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

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

    See working fiddle with jQuery 3 here

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

    Here's the code:

    JS

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

    CSS

    #myList li{display:none;
    }
    #loadMore {
        color:green;
        cursor:pointer;
    }
    #loadMore:hover {
        color:black;
    }
    

    How to close a JavaFX application on window close?

    The application automatically stops when the last Stage is closed. At this moment, the stop() method of your Application class is called, so you don't need an equivalent to setDefaultCloseOperation()

    If you want to stop the application before that, you can call Platform.exit(), for example in your onCloseRequest call.

    You can have all these information on the javadoc page of Application : http://docs.oracle.com/javafx/2/api/javafx/application/Application.html

    Purpose of installing Twitter Bootstrap through npm?

    1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

    2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

    Add event handler for body.onload by javascript within <body> part

    Simply wrap the code you want to execute into the onload event of the window object:

    window.onload = function(){ 
       // your code here
    }
    

    Browser Timeouts

    It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

    Firefox is around the same value I think as well.

    Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

    You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

    Double.TryParse or Convert.ToDouble - which is faster and safer?

    Double.TryParse IMO.

    It is easier for you to handle, You'll know exactly where the error occurred.

    Then you can deal with it how you see fit if it returns false (i.e could not convert).

    iOS: Modal ViewController with transparent background

    The Login screen is a modal, meaning that it sits on top of the previous screen. So far we have Blurred Background, but it’s not blurring anything; it’s just a grey background.

    We need to set our Modal properly.

    image link target

    • First, we need to change the View Controller’s View background to Clear color. It simply means that it should be transparent. By default, that View is white.

    • Second, we need to select the Segue that leads to the Login screen, and in the Attribute Inspector, set the Presentation to Over Current Context. This option is only available with Auto Layout and Size Classes enabled.

    image link target

    How to create custom exceptions in Java?

    For a checked exception:

    public class MyCustomException extends Exception { }
    

    Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

    You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

    As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

    throw new MyCustomException()
    

    and catch via

    catch (MyCustomException e) { }
    

    Single line if statement with 2 actions

    userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
    

    should do the trick.

    iPad/iPhone hover problem causes the user to double click a link

    Simply make a CSS media query which excludes tablets and mobile devices and put the hover in there. You don't really need jQuery or JavaScript for this.

    @media screen and (min-device-width:1024px) {
        your-element:hover {
            /* Do whatever here */
        }
    }
    

    And be sure to add this to your html head to make sure that it calculates with the actual pixels and not the resolution.

    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    

    Component is part of the declaration of 2 modules

    To surpass this error , you should start by removing all the imports of app.module.ts and have something like this :

                import { BrowserModule } from '@angular/platform-browser';
                import { HttpClientModule } from '@angular/common/http';
                import { ErrorHandler, NgModule } from '@angular/core';
                import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
                import { SplashScreen } from '@ionic-native/splash-screen';
                import { StatusBar } from '@ionic-native/status-bar';
    
                import { MyApp } from './app.component';
    
    
                @NgModule({
                  declarations: [
                    MyApp
                  ],
                  imports: [
                    BrowserModule,
                    HttpClientModule,
                    IonicModule.forRoot(MyApp)
                  ],
                  bootstrap: [IonicApp],
                  entryComponents: [
                    MyApp
                  ],
                  providers: [
                    StatusBar,
                    SplashScreen,
                    {provide: ErrorHandler, useClass: IonicErrorHandler}
                  ]
                })
                export class AppModule {}
    

    Next edit your pages module , like this :

                import { NgModule } from '@angular/core';
                import { IonicPageModule } from 'ionic-angular';
                import { HomePage } from './home';
    
                @NgModule({
                  declarations: [
                    HomePage,
                  ],
                  imports: [
                    IonicPageModule.forChild(HomePage),
                  ],
                  entryComponents: [HomePage]
                })
                export class HomePageModule {}
    

    Then add annotation of IonicPage before component annotation of all the pages :

    import { IonicPage } from 'ionic-angular';
    
    @IonicPage()
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    

    Then edit your rootPage type to be string and remove the imports of pages (if there is any in your app component )

    rootPage: string = 'HomePage';
    

    Then the navigation function should be like this :

     /**
    * Allow navigation to the HomePage for creating a new entry
    *
    * @public
    * @method viewHome
    * @return {None}
    */
     viewHome() : void
     {
      this.navCtrl.push('HomePage');
     }
    

    You can find the source of this solution here : Component is part of the declaration of 2 modules

    Writing to a file in a for loop

    That is because you are opening , writing and closing the file 10 times inside your for loop

    myfile = open('xyz.txt', 'w')
    myfile.writelines(var1)
    myfile.close()
    

    You should open and close your file outside for loop.

    myfile = open('xyz.txt', 'w')
    for line in lines:
        var1, var2 = line.split(",");
        myfile.write("%s\n" % var1)
    
    myfile.close()
    text_file.close()
    

    You should also notice to use write and not writelines.

    writelines writes a list of lines to your file.

    Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

    Meaning of *& and **& in C++

    An int* is a pointer to an int, so int*& must be a reference to a pointer to an int. Similarly, int** is a pointer to a pointer to an int, so int**& must be a reference to a pointer to a pointer to an int.

    calling another method from the main method in java

    You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

    public static void main(String[] args){
      new Foo().doSomething();
    }
    
    public void doSomething(){}
    

    Alternatively, make doSomething() static as well, if that works for your design.

    I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

    If you have not ejected from CRA yet, you can't easily modify your webpack config. The config file is hidden in node_modules/react_scripts/config/webpackDevServer.config.js. You are discouraged to change that config.

    Instead, you can just set the environment variable DANGEROUSLY_DISABLE_HOST_CHECK to true to disable the host check:

    DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start  
    # or the equivalent npm command
    

    Can someone explain __all__ in Python?

    Explain __all__ in Python?

    I keep seeing the variable __all__ set in different __init__.py files.

    What does this do?

    What does __all__ do?

    It declares the semantically "public" names from a module. If there is a name in __all__, users are expected to use it, and they can have the expectation that it will not change.

    It also will have programmatic affects:

    import *

    __all__ in a module, e.g. module.py:

    __all__ = ['foo', 'Bar']
    

    means that when you import * from the module, only those names in the __all__ are imported:

    from module import *               # imports foo and Bar
    

    Documentation tools

    Documentation and code autocompletion tools may (in fact, should) also inspect the __all__ to determine what names to show as available from a module.

    __init__.py makes a directory a Python package

    From the docs:

    The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

    In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

    So the __init__.py can declare the __all__ for a package.

    Managing an API:

    A package is typically made up of modules that may import one another, but that are necessarily tied together with an __init__.py file. That file is what makes the directory an actual Python package. For example, say you have the following files in a package:

    package
    +-- __init__.py
    +-- module_1.py
    +-- module_2.py
    

    Let's create these files with Python so you can follow along - you could paste the following into a Python 3 shell:

    from pathlib import Path
    
    package = Path('package')
    package.mkdir()
    
    (package / '__init__.py').write_text("""
    from .module_1 import *
    from .module_2 import *
    """)
    
    package_module_1 = package / 'module_1.py'
    package_module_1.write_text("""
    __all__ = ['foo']
    imp_detail1 = imp_detail2 = imp_detail3 = None
    def foo(): pass
    """)
    
    package_module_2 = package / 'module_2.py'
    package_module_2.write_text("""
    __all__ = ['Bar']
    imp_detail1 = imp_detail2 = imp_detail3 = None
    class Bar: pass
    """)
    

    And now you have presented a complete api that someone else can use when they import your package, like so:

    import package
    package.foo()
    package.Bar()
    

    And the package won't have all the other implementation details you used when creating your modules cluttering up the package namespace.

    __all__ in __init__.py

    After more work, maybe you've decided that the modules are too big (like many thousands of lines?) and need to be split up. So you do the following:

    package
    +-- __init__.py
    +-- module_1
    ¦   +-- foo_implementation.py
    ¦   +-- __init__.py
    +-- module_2
        +-- Bar_implementation.py
        +-- __init__.py
    

    First make the subpackage directories with the same names as the modules:

    subpackage_1 = package / 'module_1'
    subpackage_1.mkdir()
    subpackage_2 = package / 'module_2'
    subpackage_2.mkdir()
    

    Move the implementations:

    package_module_1.rename(subpackage_1 / 'foo_implementation.py')
    package_module_2.rename(subpackage_2 / 'Bar_implementation.py')
    

    create __init__.pys for the subpackages that declare the __all__ for each:

    (subpackage_1 / '__init__.py').write_text("""
    from .foo_implementation import *
    __all__ = ['foo']
    """)
    (subpackage_2 / '__init__.py').write_text("""
    from .Bar_implementation import *
    __all__ = ['Bar']
    """)
    

    And now you still have the api provisioned at the package level:

    >>> import package
    >>> package.foo()
    >>> package.Bar()
    <package.module_2.Bar_implementation.Bar object at 0x7f0c2349d210>
    

    And you can easily add things to your API that you can manage at the subpackage level instead of the subpackage's module level. If you want to add a new name to the API, you simply update the __init__.py, e.g. in module_2:

    from .Bar_implementation import *
    from .Baz_implementation import *
    __all__ = ['Bar', 'Baz']
    

    And if you're not ready to publish Baz in the top level API, in your top level __init__.py you could have:

    from .module_1 import *       # also constrained by __all__'s
    from .module_2 import *       # in the __init__.py's
    __all__ = ['foo', 'Bar']     # further constraining the names advertised
    

    and if your users are aware of the availability of Baz, they can use it:

    import package
    package.Baz()
    

    but if they don't know about it, other tools (like pydoc) won't inform them.

    You can later change that when Baz is ready for prime time:

    from .module_1 import *
    from .module_2 import *
    __all__ = ['foo', 'Bar', 'Baz']
    

    Prefixing _ versus __all__:

    By default, Python will export all names that do not start with an _. You certainly could rely on this mechanism. Some packages in the Python standard library, in fact, do rely on this, but to do so, they alias their imports, for example, in ctypes/__init__.py:

    import os as _os, sys as _sys
    

    Using the _ convention can be more elegant because it removes the redundancy of naming the names again. But it adds the redundancy for imports (if you have a lot of them) and it is easy to forget to do this consistently - and the last thing you want is to have to indefinitely support something you intended to only be an implementation detail, just because you forgot to prefix an _ when naming a function.

    I personally write an __all__ early in my development lifecycle for modules so that others who might use my code know what they should use and not use.

    Most packages in the standard library also use __all__.

    When avoiding __all__ makes sense

    It makes sense to stick to the _ prefix convention in lieu of __all__ when:

    • You're still in early development mode and have no users, and are constantly tweaking your API.
    • Maybe you do have users, but you have unittests that cover the API, and you're still actively adding to the API and tweaking in development.

    An export decorator

    The downside of using __all__ is that you have to write the names of functions and classes being exported twice - and the information is kept separate from the definitions. We could use a decorator to solve this problem.

    I got the idea for such an export decorator from David Beazley's talk on packaging. This implementation seems to work well in CPython's traditional importer. If you have a special import hook or system, I do not guarantee it, but if you adopt it, it is fairly trivial to back out - you'll just need to manually add the names back into the __all__

    So in, for example, a utility library, you would define the decorator:

    import sys
    
    def export(fn):
        mod = sys.modules[fn.__module__]
        if hasattr(mod, '__all__'):
            mod.__all__.append(fn.__name__)
        else:
            mod.__all__ = [fn.__name__]
        return fn
    

    and then, where you would define an __all__, you do this:

    $ cat > main.py
    from lib import export
    __all__ = [] # optional - we create a list if __all__ is not there.
    
    @export
    def foo(): pass
    
    @export
    def bar():
        'bar'
    
    def main():
        print('main')
    
    if __name__ == '__main__':
        main()
    

    And this works fine whether run as main or imported by another function.

    $ cat > run.py
    import main
    main.main()
    
    $ python run.py
    main
    

    And API provisioning with import * will work too:

    $ cat > run.py
    from main import *
    foo()
    bar()
    main() # expected to error here, not exported
    
    $ python run.py
    Traceback (most recent call last):
      File "run.py", line 4, in <module>
        main() # expected to error here, not exported
    NameError: name 'main' is not defined
    

    How to split() a delimited string to a List<String>

    string[] thisArray = myString.Split('/');//<string1/string2/string3/--->     
    List<string> myList = new List<string>(); //make a new string list    
    myList.AddRange(thisArray);    
    

    Use AddRange to pass string[] and get a string list.

    In an array of objects, fastest way to find the index of an object whose attributes match a search

    Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

    var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
    var objectFound = array[elementPos];
    

    Difference between Convert.ToString() and .ToString()

    object o=null;
    string s;
    s=o.toString();
    //returns a null reference exception for string  s.
    
    string str=convert.tostring(o);
    //returns an empty string for string str and does not throw an exception.,it's 
    //better to use convert.tostring() for good coding
    

    Most efficient way to find smallest of 3 numbers Java?

    I would use min/max (and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)

    int smallest;
    if (a < b) {
      if (a > c) {
        smallest = c;
      } else { // a <= c
        smallest = a;
      }
    } else { // a >= b
      if (b > c) {
        smallest = c;
      } else { // b <= c
        smallest = b;
      }
    }
    

    Just throwing it into the mix.

    Note that this is just the side-effecting variant of Abhishek's answer.

    How to track down a "double free or corruption" error

    With modern C++ compilers you can use sanitizers to track.

    Sample example :

    My program:

    $cat d_free.cxx 
    #include<iostream>
    
    using namespace std;
    
    int main()
    
    {
       int * i = new int();
       delete i;
       //i = NULL;
       delete i;
    }
    

    Compile with address sanitizers :

    # g++-7.1 d_free.cxx -Wall -Werror -fsanitize=address -g
    

    Execute :

    # ./a.out 
    =================================================================
    ==4836==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
        #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
        #1 0x400b2c in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:11
        #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
        #3 0x400a08  (/media/sf_shared/jkr/cpp/d_free/a.out+0x400a08)
    
    0x602000000010 is located 0 bytes inside of 4-byte region [0x602000000010,0x602000000014)
    freed by thread T0 here:
        #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
        #1 0x400b1b in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:9
        #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
    
    previously allocated by thread T0 here:
        #0 0x7f35b2d7a040 in operator new(unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:80
        #1 0x400ac9 in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:8
        #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
    
    SUMMARY: AddressSanitizer: double-free /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140 in operator delete(void*, unsigned long)
    ==4836==ABORTING
    

    To learn more about sanitizers you can check this or this or any modern c++ compilers (e.g. gcc, clang etc.) documentations.

    What is /var/www/html?

    /var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

    Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

    Error: getaddrinfo ENOTFOUND in nodejs for get call

    i have same issue with Amazon server i change my code to this

    var connection = mysql.createConnection({
        localAddress     : '35.160.300.66',
        user     : 'root',
        password : 'root',
        database : 'rootdb',
    });
    

    check mysql node module https://github.com/mysqljs/mysql

    How to use the 'main' parameter in package.json?

    For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.

    I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json

    Is there a limit on an Excel worksheet's name length?

    The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)

    Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

    In Servlet technology if you want to pass any input to a particular servlet then you need to pass in init param like below code.

     <servlet>
        <servlet-name>DBController</servlet-name>
        <servlet-class>com.test.controller.DBController</servlet-class>
        <init-param>
            <param-name>username</param-name>
            <param-value>John</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>DBController</servlet-name>
        <url-pattern>/DBController</url-pattern>
    </servlet-mapping>
    

    If you want to pass some in put that is common for all servlets then that time you need to configure context param. Example

     <context-param>
        <param-name>email</param-name>
        <param-value>[email protected]</param-value>
    </context-param>
    

    SO exactly like this when ever we are working with Spring MVC we need to provide some information to Predefined servlet provided by Spring that is DispatcherServlet through init param. So the configuration is as fallows, here we are providing the spring-servlet.xml as init parameter to DispatcherServlet.

     <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>Spring MVC App</display-name>
    
        <servlet>
            <servlet-name>SpringController</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>SpringController</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>
    </web-app>
    

    Again we need some context param. That is applicable for whole application. So we can provide the root context that is applicationcontext.xml The configuration is like this:

        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationcontext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
            <servlet-name>SpringController</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>SpringController</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>
    

    Find MongoDB records where array field is not empty

    This also works:

    db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})
    

    Telnet is not recognized as internal or external command

    You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well

    Add JsonArray to JsonObject

    Your list:

    List<MyCustomObject> myCustomObjectList;
    

    Your JSONArray:

    // Don't need to loop through it. JSONArray constructor do it for you.
    new JSONArray(myCustomObjectList)
    

    Your response:

    return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
    

    Your post/put http body request would be like this:

        {
            "yourCustomKey: [
               {
                   "myCustomObjectProperty": 1
               },
               {
                   "myCustomObjectProperty": 2
               }
            ]
        }
    

    Inline <style> tags vs. inline css properties

    It depends.

    The main point is to avoid repeated code.

    If the same code need to be re-used 2 times or more, and should be in sync when change, use external style sheet.

    If you only use it once, I think inline is ok.

    jQuery Mobile - back button

    try

    $(document).ready(function(){
        $('mybutton').click(function(){
            parent.history.back();
            return false;
        });
    });
    

    or

    $(document).ready(function(){
        $('mybutton').click(function(){
            parent.history.back();
    
        });
    });
    

    Replace Multiple String Elements in C#

    Another option using linq is

    [TestMethod]
    public void Test()
    {
      var input = "it's worth a lot of money, if you can find a buyer.";
      var expected = "its worth a lot of money if you can find a buyer";
      var removeList = new string[] { ".", ",", "'" };
      var result = input;
    
      removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));
    
      Assert.AreEqual(expected, result);
    }
    

    org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

    This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

    Both should be same ..Java version mismatched ..Check it

    Alternate output format for psql

    Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.

    How to change fontFamily of TextView in Android

    You can also do this by adding a font folder under the res directory like below.

    enter image description here

    Then, selecting Font as the resource type. enter image description here

    You can find avaliable fonts from https://www.1001fonts.com/, and then extracting the TTF files to this font directory.

    enter image description here

    Finally, just change the XML file that contains your textview by adding android:fontFamily:"@font/urfontfilename"

    enter image description here

    Check if a input box is empty

    The above answer didn't work with Angular 6. So following is how I resolved it. Lets say this is how I defined my input box -

    _x000D_
    _x000D_
    <input type="number" id="myTextBox" name="myTextBox"_x000D_
     [(ngModel)]="response.myTextBox"_x000D_
                #myTextBox="ngModel">
    _x000D_
    _x000D_
    _x000D_

    To check if the field is empty or not this should be the script.

    _x000D_
    _x000D_
    <div *ngIf="!myTextBox.value" style="color:red;">_x000D_
     Your field is empty_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value after my input name myTextBox. I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.

    Some more explanation on why this check works; when there is no value present in the input box the default value of myTextBox.value will be undefined. As soon as you enter some text, your text becomes the new value of myTextBox.value.

    When your check is !myTextBox.value it is checking that the value is undefined or not, it is equivalent to myTextBox.value == undefined.

    'module' object has no attribute 'DataFrame'

    The most likely explanation is that either a file called 'pandas.py' is in the same directory as your script, or that another variable called 'pd' is used in your program.

    bash string equality

    There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

    You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

    Create a one to many relationship using SQL Server

    If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.

    Homebrew install specific version of formula?

    Most of the other answers are obsolete by now. Unfortunately Homebrew still doesn’t have a builtin way of installing an outdated version, unless that version exists as a separate formula (e.g. python@2, [email protected] …).

    Luckily, for other formulas there’s a much easier way than the convoluted mess that used to be necessary. Here are the full instructions:

    1. Search for the correct version in the logs:

      brew log formula
      # Scroll down/up with j/k or the arrow keys
      # or use eg. /4\.4\.23 to search a specific version
      
      # This syntax only works on pre-2.0 Homebrew versions
      brew log --format=format:%H\ %s -F --grep=‹version› ‹formula›
      

      This will show a list of commit hashes. Take one that is appropriate (mostly it should be pretty obvious, and usually is the most recent (i.e. top) one.

    2. Find the URL at which the formula resides in the upstream repository:

      brew info ‹formula› | grep ^From:
      
    3. Fix the URL:

      1. Replace github.com with raw.githubusercontent.com
      2. Replace blob/master with the commit hash we found in the first step.
    4. Install the desired version by replacing master in the previously found URL by the commit hash, e.g.:

      brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/‹hash›/Formula/‹formula›.rb
      

    (The last step may necessitate running brew unlink ‹formula› before.)


    If you have copied a commit hash you want to use, you can use something like this example to install that version, replacing the value and bash with your commit hash and your desired formula.

    BREW_VERSION_SHA=32353d2286f850fd965e0a48bcf692b83a6e9a41
    BREW_FORMULA_NAME=bash
    brew info $BREW_FORMULA_NAME \
    | sed -n \
        -e '/^From: /s///' \
        -e 's/github.com/raw.githubusercontent.com/' \
        -e 's%blob/%%' \
        -e "s/master/$BREW_VERSION_SHA/p" \
    | xargs brew install
    

    This example is installing bash 4.4.23 instead of bash 5, though if you performed a brew upgrade afterward then bash 5 would get installed over top, unless you first executed brew pin bash. Instead to make this smoother WITHOUT pinning, you should first install the latest with brew install bash, then brew unlink bash, then install the older version you want per the script above, and then use brew switch bash 4.4.23 to set up the symlinks to the older version. Now a brew upgrade shouldn't affect your version of Bash. You can brew switch bash to get a list of the versions available to switch to.


    Alternative using a custom local-only tap

    Another way of achieving the same goal appears to be:

    brew tap-new username/repo-name
    # extract with a version seems to run a grep under the hood
    brew extract --version='4.4.23' bash username/repo-name
    brew install [email protected]
    # Note this "fails" when trying to grab a bottle for the package and seems to have
    # some odd doubling of the version in that output, but this isn't fatal.
    

    This creates a formula@version in your custom tap that you can install per the above example. The downside is that you probably still need to brew unlink bash and then brew link [email protected] in order to use your specific version of Bash or any other formula.

    cannot load such file -- bundler/setup (LoadError)

    i had the same issue and tried all the answers without any luck.

    steps i did to reproduce:

    1. rvm instal 2.1.10
    2. rvm gemset create my_gemset
    3. rvm use 2.1.10@my_gemset
    4. bundle install

    however bundle install installed Rails, but i still got cannot load such file -- bundler/setup (LoadError)

    finally running gem install rails -v 4.2 fixed it

    How to cancel a pull request on github?

    Super EASY way to close a Pull Request - LATEST!

    1. Navigate to the Original Repository where the pull request has been submitted to.
    2. Select the Pull requests tab
    3. Select your pull request that you wish to remove. This will open it up.
    4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

    enter image description here

    Today`s date in an excel macro

    Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

    Trigger a button click with JavaScript on the Enter key in a text box

    event.returnValue = false
    

    Use it when handling the event or in the function your event handler calls.

    It works in Internet Explorer and Opera at least.

    How do you create a Marker with a custom icon for google maps API v3?

    Try

        var marker = new google.maps.Marker({
          position: map.getCenter(),
          icon: 'http://imageshack.us/a/img826/9489/x1my.png',
          map: map
        });
    

    from here

    https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

    Hide div by default and show it on click with bootstrap

    I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

    What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

    All that the JavaScript does is makes all the other <div> hide using

    $(".main-container.collapse").not($(this)).collapse('hide');

    when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

    Note: main-container is just a custom class.

    Here it goes-

    _x000D_
    _x000D_
    $(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
    //when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
           $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    _x000D_
    <a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
    <a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
    _x000D_
    <div id="Bar" class="main-container collapse in">_x000D_
        This div (#Bar) is shown by default and can toggle_x000D_
    </div>_x000D_
    <div id="Foo" class="main-container collapse">_x000D_
        This div (#Foo) is hidden by default_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to execute an Oracle stored procedure via a database link

    The syntax is

    EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
    

    How to pass multiple parameters in json format to a web service using jquery?

    i have same issue and resolved by

     data: "Id1=" + id1 + "&Id2=" + id2
    

    Manually highlight selected text in Notepad++

    "Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

    It should be default, but it might be hidden.

    "It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

    See this for more information

    Java - checking if parseInt throws exception

    public static boolean isParsable(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (final NumberFormatException e) {
            return false;
        }
    }