Programs & Examples On #Foxpro

FoxPro is a database and application development IDE from Microsoft.

How to handle authentication popup with Selenium WebDriver using Java

Selenium 4 supports authenticating using Basic and Digest auth . It's using the CDP and currently only supports chromium-derived browsers

Java Example :

Webdriver driver = new ChromeDriver();

((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));


Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk

How do I set browser width and height in Selenium WebDriver?

Here is firefox profile default prefs from python selenium 2.31.0

and type "about:config" in firefox address bar to see all prefs

reference to the entries in about:config:

    "": "false",
    "app.update.enabled": "false",
    "": "false",
    "browser.EULA.override": "true",
    "browser.EULA.3.accepted": "true",
    "": "2",
    "": "2",
    "browser.offline": "false",
    "browser.safebrowsing.enabled": "false",
    "": "false",
    "extensions.blocklist.enabled": "false",
    "browser.sessionstore.resume_from_crash": "false",
    "": "false",
    "browser.tabs.warnOnClose": "false",
    "browser.tabs.warnOnOpen": "false",
    "": "0",
    "browser.safebrowsing.malware.enabled": "false",
    "startup.homepage_welcome_url": "\"about:blank\"",
    "devtools.errorconsole.enabled": "true",
    "dom.disable_open_during_load": "false",
    "extensions.autoDisableScopes" : 10,
    "extensions.logging.enabled": "true",
    "extensions.update.enabled": "false",
    "extensions.update.notifyUser": "false",
    "network.manage-offline-status": "false",
    "network.http.max-connections-per-server": "10",
    "network.http.phishy-userpass-length": "255",
    "offline-apps.allow_by_default": "true",
    "prompts.tab_modal.enabled": "false",
    "security.fileuri.origin_policy": "3",
    "security.fileuri.strict_origin_policy": "false",
    "security.warn_entering_secure": "false",
    "security.warn_entering_secure.show_once": "false",
    "security.warn_entering_weak": "false",
    "security.warn_entering_weak.show_once": "false",
    "security.warn_leaving_secure": "false",
    "security.warn_leaving_secure.show_once": "false",
    "security.warn_submit_insecure": "false",
    "security.warn_viewing_mixed": "false",
    "security.warn_viewing_mixed.show_once": "false",
    "signon.rememberSignons": "false",
    "toolkit.networkmanager.disable": "true",
    "toolkit.telemetry.enabled": "false",
    "toolkit.telemetry.prompted": "2",
    "toolkit.telemetry.rejected": "true",
    "javascript.options.showInConsole": "true",
    "browser.dom.window.dump.enabled": "true",
    "webdriver_accept_untrusted_certs": "true",
    "webdriver_enable_native_events": "true",
    "webdriver_assume_untrusted_issuer": "true",
    "dom.max_script_run_time": "30",

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

be attention, if path to browser have space (as example "...\Program Files (x86)...") you need add double quotes to value of param.


-Dwebdriver.firefox.bin="D:\Program Files (x86)\Mozilla Firefox\firefox.exe"

All has been run successfully when added double quotes.

How do I set proxy for chrome in python webdriver?

Its working for me...

from selenium import webdriver


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://%s' % PROXY)

chrome = webdriver.Chrome(chrome_options=chrome_options)

How do I set the selenium webdriver get timeout?

Used below code in similar situation

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.

What is the worst programming language you ever worked with?


I worked in it for a couple years, but have done a complete brain dump since then. All I can really remember was no documentation (at my location) and cryptic commands.

It was horrible. Horrible! HORRIBLE!!!

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

For my VB.Net Friends -

Dim scriptManager As ScriptManager = scriptManager.GetCurrent(Me.Page)

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.


Edit:(Based on @davidchambers's comment)


Calculating powers of integers

import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {

            try {
                long x = sc.nextLong();
                System.out.println(x + " can be fitted in:");
                if (x >= -128 && x <= 127) {
                    System.out.println("* byte");
                if (x >= -32768 && x <= 32767) {
                    //Complete the code
                    System.out.println("* short");
                    System.out.println("* int");
                    System.out.println("* long");
                } else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
                    System.out.println("* int");
                    System.out.println("* long");
                } else {
                    System.out.println("* long");
            } catch (Exception e) {
                System.out.println( + " can't be fitted anywhere.");


pandas: filter rows of DataFrame with operator chaining

The answer from @lodagro is great. I would extend it by generalizing the mask function as:

def mask(df, f):
  return df[f(df)]

Then you can do stuff like:

df.mask(lambda x: x[0] < 0).mask(lambda x: x[1] > 0)

Using jquery to get all checked checkboxes with a certain class name

Obligatory .map example:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;

Excel VBA - select a dynamic cell range

I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

my experience tells me that missing persistence.xml,will generate the same exception too.

i caught the same error msg today when i tried to run a jar package packed by ant.

when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.

after I manually repacked the jar file ,the error msg disappered.

so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Either switch your browser in VS2017. Or open up a command prompt as administrator and do a tskill chrome about 10 times to make sure the app fully dies. Then try again. Sometimes it gets stuck on another process and even it needs to be restarted.

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:


  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;

ViewDidAppear is not called when opening app from background

try adding this in AppDelegate applicationWillEnterForeground.

func applicationWillEnterForeground(_ application: UIApplication) {        
    // makes viewWillAppear run
    self.window?.rootViewController?.beginAppearanceTransition(true, animated: false)

Load image from resources area of project in C#

JDS's answer worked best. C# example loading image:

  • Include the image as Resource (Project tree->Resources, right click to add the desirable file ImageName.png)
  • Embedded Resource (Project tree->Resources->ImageName.png, right click select properties)
  • .png file format (.bmp .jpg should also be OK)

pictureBox1.Image = ProjectName.Properties.Resources.ImageName;

Note the followings:

  • The resource image file is "ImageName.png", file extension should be omitted.
  • ProjectName may perhaps be more adequately understood as "Assembly name", which is to be the respective text entry on the Project->Properties page.

The example code line is run successfully using VisualStudio 2015 Community.

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

Textarea onchange detection

I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.

      // Change occurred so count chars...


      // Change occurred so count chars...

How can I get the selected VALUE out of a QCombobox?

It seems you need to do combobox->itemData(combobox->currentIndex()) if you want to get the current data of the QComboBox.

If you are using your own class derived from QComboBox, you can add a currentData() function.

How to stop execution after a certain time in Java?

you should try the new Java Executor Services.

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {

Can I get a patch-compatible output from git-diff?

A useful trick to avoid creating temporary patch files:

git diff | patch -p1 -d [dst-dir]

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

Bootstrap 3.0: How to have text and input on same line?

just give mother of div "class="col-lg-12""

<div class="form-group">
<div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>

it will be

<div class="form-group">
<div class="col-lg-12">
  <div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>

ASP.NET MVC 404 Error Handling

I've investigated A LOT on how to properly manage 404s in MVC (specifically MVC3), and this, IMHO is the best solution I've come up with:

In global.asax:

public class MvcApplication : HttpApplication
    protected void Application_EndRequest()
        if (Context.Response.StatusCode == 404)

            var rd = new RouteData();
            rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
            rd.Values["controller"] = "Errors";
            rd.Values["action"] = "NotFound";

            IController c = new ErrorsController();
            c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));


public sealed class ErrorsController : Controller
    public ActionResult NotFound()
        ActionResult result;

        object model = Request.Url.PathAndQuery;

        if (!Request.IsAjaxRequest())
            result = View(model);
            result = PartialView("_NotFound", model);

        return result;


If you're using IoC (e.g. AutoFac), you should create your controller using:

var rc = new RequestContext(new HttpContextWrapper(Context), rd);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Errors");

Instead of

IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));



There are 6 scenarios that I can think of where an ASP.NET MVC3 apps can generate 404s.

Generated by ASP.NET:

  • Scenario 1: URL does not match a route in the route table.

Generated by ASP.NET MVC:

  • Scenario 2: URL matches a route, but specifies a controller that doesn't exist.

  • Scenario 3: URL matches a route, but specifies an action that doesn't exist.

Manually generated:

  • Scenario 4: An action returns an HttpNotFoundResult by using the method HttpNotFound().

  • Scenario 5: An action throws an HttpException with the status code 404.

  • Scenario 6: An actions manually modifies the Response.StatusCode property to 404.


  • (A) Show a custom 404 error page to the user.

  • (B) Maintain the 404 status code on the client response (specially important for SEO).

  • (C) Send the response directly, without involving a 302 redirection.

Solution Attempt: Custom Errors

    <customErrors mode="On">
        <error statusCode="404" redirect="~/Errors/NotFound"/>

Problems with this solution:

  • Does not comply with objective (A) in scenarios (1), (4), (6).
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • Does not comply with objective (C).

Solution Attempt: HTTP Errors

    <httpErrors errorMode="Custom">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (A) in scenarios (2), (3), (5).
  • Does not comply with objective (B) automatically. It must be programmed manually.

Solution Attempt: HTTP Errors with Replace

    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • It obscures application level http exceptions. E.g. can't use customErrors section, System.Web.Mvc.HandleErrorAttribute, etc. It can't only show generic error pages.

Solution Attempt customErrors and HTTP Errors

    <customErrors mode="On">
        <error statusCode="404" redirect="~/Errors/NotFound"/>


    <httpErrors errorMode="Custom">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • Does not comply with objective (C) in scenarios (2), (3), (5).

People that have troubled with this before even tried to create their own libraries (see But the previous solution seems to cover all the scenarios without the complexity of using an external library.

Limit Decimal Places in Android EditText

I have modified the above solutions and created following one. You can set number of digits before and after decimal point.

public class DecimalDigitsInputFilter implements InputFilter {

private final Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    mPattern = Pattern.compile(String.format("[0-9]{0,%d}(\\.[0-9]{0,%d})?", digitsBeforeZero, digitsAfterZero));

public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    Matcher matcher = mPattern.matcher(createResultString(source, start, end, dest, dstart, dend));
    if (!matcher.matches())
        return "";
    return null;

private String createResultString(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    String sourceString = source.toString();
    String destString = dest.toString();
    return destString.substring(0, dstart) + sourceString.substring(start, end) + destString.substring(dend);


Selenium: Can I set any of the attribute value of a WebElement in Selenium?

    JavascriptExecutor js = (JavascriptExecutor) driver;        
    js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");

I could add an attribute using the above code in java

C#: easiest way to populate a ListBox from a List

Is this what you are looking for:

myListBox.DataSource = MyList;

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Check recursion from command line:

php -r 'function foo() { static $x = 1; echo "foo ", $x++, "\n"; foo(); } foo();'

if result > 100 THEN check memory limit;

How to erase the file contents of text file in Python?

From user @jamylak an alternative form of open("filename","w").close() is

with open('filename.txt','w'): pass

Get current rowIndex of table in jQuery

Try this,

   var row_index = $(this).parent().index();
   var col_index = $(this).index();

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Command CompileSwift failed with a nonzero exit code in Xcode 10

Let me share my experience for this issue fix.

Open target -> Build phases -> Copy Bundle Resources and remove info.plist.

Note: If you're using any extensions, remove the info.plist of that extension from the Targets.

Hope it helps.

Error Message : Cannot find or open the PDB file

If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.

Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.

Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"

SQL Query for Logins

Starting with SQL 2008, you should use sys.server_principals instead of sys.syslogins, which has been deprecated.

Parsing CSV files in C#, with header

If you need only reading csv files then I recommend this library: A Fast CSV Reader
If you also need to generate csv files then use this one: FileHelpers

Both of them are free and opensource.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Query scopes may help you to let your code more readable.

Updating this answer with some example:

In your model, create scopes methods like this:

public function scopeActive($query)
    return $query->where('active', '=', 1);

public function scopeThat($query)
    return $query->where('that', '=', 1);

Then, you can call this scopes while building your query:

$users = User::active()->that()->get();

String replacement in java, similar to a velocity template

I threw together a small test implementation of this. The basic idea is to call format and pass in the format string, and a map of objects, and the names that they have locally.

The output of the following is:

My dog is named fido, and Jane Doe owns him.

public class StringFormatter {

    private static final String fieldStart = "\\$\\{";
    private static final String fieldEnd = "\\}";

    private static final String regex = fieldStart + "([^}]+)" + fieldEnd;
    private static final Pattern pattern = Pattern.compile(regex);

    public static String format(String format, Map<String, Object> objects) {
        Matcher m = pattern.matcher(format);
        String result = format;
        while (m.find()) {
            String[] found ="\\.");
            Object o = objects.get(found[0]);
            Field f = o.getClass().getField(found[1]);
            String newVal = f.get(o).toString();
            result = result.replaceFirst(regex, newVal);
        return result;

    static class Dog {
        public String name;
        public String owner;
        public String gender;

    public static void main(String[] args) {
        Dog d = new Dog(); = "fido";
        d.owner = "Jane Doe";
        d.gender = "him";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("d", d);
                "My dog is named ${}, and ${d.owner} owns ${d.gender}.", 

Note: This doesn't compile due to unhandled exceptions. But it makes the code much easier to read.

Also, I don't like that you have to construct the map yourself in the code, but I don't know how to get the names of the local variables programatically. The best way to do it, is to remember to put the object in the map as soon as you create it.

The following example produces the results that you want from your example:

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<String, Object>();
    Site site = new Site();
    map.put("site", site); = "";
    User user = new User();
    map.put("user", user); = "jjnguy";
         format("Hello ${},\n\tWelcome to ${}. ", map));

I should also mention that I have no idea what Velocity is, so I hope this answer is relevant.

Difference between .dll and .exe?

Two things: the extension and the header flag stored in the file.

Both files are PE files. Both contain the exact same layout. A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).

One minor difference is that in most cases DLLs have an export section where symbols are exported. EXEs should never have an export section since they aren't libraries but nothing prevents that from happening. The Win32 loader doesn't care either way.

Other than that they are identical. So, in summary, EXEs are executable programs while DLLs are libraries loaded into a process and contain some sort of useful functionality like security, database access or something.

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().

After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

How to create a dotted <hr/> tag?

hr {
    border: 1px dotted #ff0000;
    border-style: none none dotted; 
    color: #fff; 
    background-color: #fff;

Try this

How to enable CORS in ASP.NET Core

You have to configure a CORS policy at application startup in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>

    // ...

The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:


Or apply it to every request:

public void Configure(IApplicationBuilder app)

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.

Naming Conventions: What to name a boolean variable?




Maybe too wordy but they may help give you ideas.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

From $album->getTrackList() you will alwas get "AlbumTrackReference" entities back, so what about adding methods from the Track and proxy?

class AlbumTrackReference
    public function getTitle()
        return $this->getTrack()->getTitle();

    public function getDuration()
        return $this->getTrack()->getDuration();

This way your loop simplifies considerably, aswell as all other code related to looping the tracks of an album, since all methods are just proxied inside AlbumTrakcReference:

foreach ($album->getTracklist() as $track) {
    echo sprintf("\t#%d - %-20s (%s) %s\n", 
        $track->isPromoted() ? ' - PROMOTED!' : ''

Btw You should rename the AlbumTrackReference (for example "AlbumTrack"). It is clearly not only a reference, but contains additional logic. Since there are probably also Tracks that are not connected to an album but just available through a promo-cd or something this allows for a cleaner separation also.

Importing large sql file to MySql via command line

+1 to @MartinNuc, you can run the mysql client in batch mode and then you won't see the long stream of "OK" lines.

The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.

@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.

We can't really guess how long it will take to run your SQL script on your server.

Re your comment,

@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.

Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.

Compiling a java program into an executable

I use launch4j

ANT Command:

<target name="jar" depends="compile, buildDLLs, copy">
    <jar basedir="${java.bin.dir}" destfile="${build.dir}/Project.jar" manifest="META-INF/MANIFEST.MF" />

<target name="exe" depends="jar">
    <exec executable="cmd" dir="${launch4j.home}">
        <arg line="/c launch4jc.exe ${basedir}/${launch4j.dir}/L4J_ProjectConfig.xml" />

Center HTML Input Text Field Placeholder


is all you need.

Working example in FF6. This method doesn't seem to be cross-browser compatible.

Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".

How to disable Paste (Ctrl+V) with jQuery?

You can catch key event :

function checkEventObj ( _event_ ){
    // --- IE explorer
    if ( window.event )
        return window.event;
    // --- Netscape and other explorers
        return _event_;

document.keydown = function(_event) {
    var e = checkEventObject(_event);

    if( e.ctrlKey && (e.keyCode == 86) )

Not tested but, could help.

Source from comentcamarche and Zakaria

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

        keyboard: true,
        backdrop: "static",

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))


Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. |

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.


Remove the source mapping line, or do nothing. It isn't really a problem.

Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

How to update array value javascript?

"But i want to know a better way to do this, if there is one ?"

Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.

  function Update(keyValue, newKey, newValue)
    keyValue.Key = newKey;
    keyValue.Value = newValue; 

T-SQL string replace in Update

The syntax for REPLACE:

REPLACE (string_expression,string_pattern,string_replacement)

So that the SQL you need should be:

UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);

Calculating arithmetic mean (one type of average) in Python

You don't even need numpy or scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))

How to convert a python numpy array to an RGB image with Opencv 2.4?

If anyone else simply wants to display a black image as a background, here e.g. for 500x500 px:

import cv2
import numpy as np

black_screen  = np.zeros([500,500,3])
cv2.imshow("Simple_black", black_screen)

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

Write values in app.config file

private static string GetSetting(string key)
    return ConfigurationManager.AppSettings[key];

private static void SetSetting(string key, string value)
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);

How do I make an Event in the Usercontrol and have it handled in the Main Form?

you can do like this.....the below example shows text box(user control) value changed

   // Declare a delegate 
public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);
public partial class SampleUserControl : TextBox 
    public SampleUserControl() 

    // Declare an event 
    public event ValueChangedEventHandler ValueChanged;

    protected virtual void OnValueChanged(ValueChangedEventArgs e) 
        if (ValueChanged != null) 
    private void SampleUserControl_TextChanged(object sender, EventArgs e) 
        TextBox tb  = (TextBox)sender; 
        int value; 
        if (!int.TryParse(tb.Text, out value)) 
            value = 0; 
        // Raise the event 
       OnValueChanged( new ValueChangedEventArgs(value)); 

mvn command is not recognized as an internal or external command

In your Environement variable :

new system variable:

M2_HOME Your mvn directroy "C:\......\bin"

new user variable:

M2 %M2_HOME%

edit the CLASSPATH by adding %M2%

finally open the cmd and write



Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        //grab all form data  
        var formData = $(this).serialize();

            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            error: function(){
                alert("error in ajax form submission");

        return false;

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

If you are using C# 3.0 or higher you can do the following

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {

Without C# 3.0 you can do the following

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {

Or even better, write OfType in C# 2.0.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {

How to make readonly all inputs in some div in Angular2?

Just set css property of container div 'pointer-events' as none i.e. 'pointer-events:none;'

PHP substring extraction. Get the string before the first '/' or the whole string

The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..

But if you're not using 5.3, then the function below should work accurately:

function strbstr( $str, $char, $start=0 ){
    if ( isset($str[ $start ]) && $str[$start]!=$char ){
        return $str[$start].strbstr( $str, $char, $start+1 );

I haven't tested it though, but this should work just fine.. And it's pretty fast as well

Search for a string in Enum and return the Enum

class EnumStringToInt // to search for a string in enum
    enum Numbers{one,two,hree};
    static void Main()
        Numbers num =; // converting enum to string
        string str = num.ToString();
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
            for (int i = 0; i <= getnum.Length; i++)
                if (str1.Equals(getnames[i]))
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
        catch (Exception ex)
            Console.WriteLine("Value not found!", ex);

How to create a density plot in matplotlib?

Maybe try something like:

import matplotlib.pyplot as plt
import numpy
from scipy import stats
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = stats.kde.gaussian_kde(data)
x = numpy.arange(0., 8, .1)
plt.plot(x, density(x))

You can easily replace gaussian_kde() by a different kernel density estimate.

Good Hash Function for Strings

// djb2 hash function
unsigned long hash(unsigned char *str)
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;

source Logic behind djb2 hash function - SO

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?" is good place for reference using "sub-delim" as keyword. is another good source.

Byte[] to ASCII

You can use:


But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:


Or as a last resort:


Encoding Javascript Object to Json string

You can use JSON.stringify like:


Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (

type User struct {
    name string

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
        Name:     "customized" +,

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {

Cannot ping AWS EC2 instance

Please go through the below checklists

1) You have to first check whether the instance is launched in a subnet where it is reachable from the internet

For that check whether the instance launched subnet has an internet gateway attached to it.For details of networking in AWS please go through the below link.

public and private subnets in aws vpc

2) Check whether you have proper security group rules added,If notAdd the below rule in the security group attached to instance.A Security group is firewall attached to every instance launched.The security groups contain the inbound/outbound rules which allow the traffic in/out of the default every security group allow all outbound traffic from the instance and no inbound traffic to the instance.Check the below link for more details of the traffic.

security group documentation

Type: custom ICMPV4

Protocol: ICMP

Portrange : Echo Request


screenshot from aws console

3) Check whether you have the enough rules in the subnet level firewall called NACL.An NACL is a stateless firewall which needs both inbound and outbound traffic separately specified.NACL is applied at the subnet level, all the instances under the subnet will come under the NACL rules.Below is the link which will have more details on it.

NACL documentation

Inbound Rules . Outbound Rules

Type: Custom IPV4 Type: Custom IPV4

Protocol: ICMP Protocol: ICMP

Portrange: ECHO REQUEST Portrange: ECHO REPLY

Source: Destination:

Allow/Deny: Allow Allow/Deny: Allow

screenshot inbound rule

screenshot outbound rule

4) check any firewalls like IPTABLES and disble for testing the ping.

How to read data from a zip file without having to unzip the entire file

DotNetZip is your friend here.

As easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
  ZipEntry e = zip["MyReport.doc"];

(you can also extract to a file or other destinations).

Reading the zip file's table of contents is as easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
  foreach (ZipEntry e in zip)
    if (header)
      System.Console.WriteLine("Zipfile: {0}", zip.Name);
      if ((zip.Comment != null) && (zip.Comment != "")) 
        System.Console.WriteLine("Comment: {0}", zip.Comment);
      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}",
                               "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");
      System.Console.WriteLine(new System.String('-', 72));
      header = false;
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}",
                             e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                             (e.UsesEncryption) ? "Y" : "N");


Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:

How to split a string, but also keep the delimiters?

I suggest using Pattern and Matcher, which will almost certainly achieve what you want. Your regular expression will need to be somewhat more complicated than what you are using in String.split.

How does "cat << EOF" work in bash?


kennytm quoted man bash, but most of that is also POSIX 7: :

The redirection operators "<<" and "<<-" both allow redirection of lines contained in a shell input file, known as a "here-document", to the input of a command.

The here-document shall be treated as a single word that begins after the next and continues until there is a line containing only the delimiter and a , with no characters in between. Then the next here-document starts, if there is one. The format is as follows:


where the optional n represents the file descriptor number. If the number is omitted, the here-document refers to standard input (file descriptor 0).

If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.

If no characters in word are quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. In this case, the in the input behaves as the inside double-quotes (see Double-Quotes). However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}".

If the redirection symbol is "<<-", all leading <tab> characters shall be stripped from input lines and the line containing the trailing delimiter. If more than one "<<" or "<<-" operator is specified on a line, the here-document associated with the first operator shall be supplied first by the application and shall be read first by the shell.

When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variable PS2, processed as described in Shell Variables, to standard error before reading each line of input until the delimiter has been recognized.


Some examples not yet given.

Quotes prevent parameter expansion

Without quotes:

cat <<EOF



With quotes:

cat <<'EOF'

or (ugly but valid):

cat <<E"O"F



Hyphen removes leading tabs

Without hyphen:

cat <<EOF

where <tab> is a literal tab, and can be inserted with Ctrl + V <tab>



With hyphen:

cat <<-EOF



This exists of course so that you can indent your cat like the surrounding code, which is easier to read and maintain. E.g.:

if true; then
    cat <<-EOF

Unfortunately, this does not work for space characters: POSIX favored tab indentation here. Yikes.

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>

<div id="message"></div>


function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
        document.getElementById("message").innerHTML = "Having a Baby!!";

jsFiddle Demo

A shorter version and more general could be


<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>


function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
... = None
...   def __enter__(self):
...     if != 'open':
...       print 'opening the bar'
... = 'open'
...   def __exit__(self, type_, value, traceback):
...     if != 'closed':
...       print 'closing the bar', type_, value, traceback
... = 'close'
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

When is the init() function run?

Here is another example -

package main

import (

func callOut() int {
    fmt.Println("Outside is beinge executed")
    return 1

var test = callOut()

func init() {
    fmt.Println("Init3 is being executed")

func init() {
    fmt.Println("Init is being executed")

func init() {
    fmt.Println("Init2 is being executed")

func main() {
    fmt.Println("Do your thing !")

Output of the above program

$ go run init/init.go
Outside is being executed
Init3 is being executed
Init is being executed
Init2 is being executed
Do your thing !

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
>>> a = 2**1000
>>> getsizeof(a)

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

SQL Server - copy stored procedures from one db to another

  • Right click on database
  • Tasks
  • Generate Scripts
  • Select the objects you wish to script
  • Script to File
  • Run generated scripts against target database

SVN undo delete before commit

Do a (recursive) Revert operation from a level above the directory you deleted.

How do I reference tables in Excel using VBA?

Converting a range to a table as described in this answer:

Sub CreateTable()
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _
        'No go in 2003
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2"
End Sub

Counting number of words in a file

Just keep a boolean flag around that lets you know if the previous character was whitespace or not (pseudocode follows):

boolean prevWhitespace = false;
int wordCount = 0;
while (char ch = getNextChar(input)) {
  if (isWhitespace(ch)) {
    if (!prevWhitespace) {
      prevWhitespace = true;
  } else {
    prevWhitespace = false;

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Project Properties -> Compile -> Target CPU -> Any CPU And uncheck Prefer 32 bit


How do I get DOUBLE_MAX?

Its in the standard float.h include file. You want DBL_MAX

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

How to have a a razor action link open in a new tab?

You are setting it't type as submit. That means that browser should post your <form> data to the server.

In fact a tag has no type attribute according to w3schools.

So remote type attribute and it should work for you.

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

Returning http status code from Web Api controller

You can also do the following if you want to preserve the action signature as returning User:

public User GetUser(int userId, DateTime lastModifiedAtClient) 

If you want to return something other than 200 then you throw an HttpResponseException in your action and pass in the HttpResponseMessage you want to send to the client.

Class Diagrams in VS 2017

You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.

See: Visual Studio Community 2017 component directory

But this kind of item is not available on all project types. Just try for yourself:

  • In a Console App (.NET Framework) is available;

  • In a Console App (.NET Core) is not available.

I couldn't find more info on future availability also for .NET Core projects.

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

How do I update Node.js?

Some Linux distributions such as Arch Linux have Node.js in their package repositories. On such systems it is better to use a standard package update procedure, such as pacman -Suy or analogous apt-get or yum commands.

As of now (Nov 2016) EPEL7 offers a pretty recent version of Node.js (6.9.1 which is an up-to-date LTS version offered on the Node.js home page). So on CentOS 7 and derivatives you can just add EPEL repository by yum install epel-release and yum install nodejs.

CentOS 6/EPEL6 has 0.10.x which isn't supported upstream since Oct 2016.

How to calculate probability in a normal distribution given mean & standard deviation?

You can just use the error function that's built in to the math library, as stated on their website.

How do you Programmatically Download a Webpage in Java

Bill's answer is very good, but you may want to do some things with the request like compression or user-agents. The following code shows how you can various types of compression to your requests.

URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;

// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
    inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
    inStr = new InflaterInputStream(conn.getInputStream(),
      new Inflater(true));
} else {
    inStr = conn.getInputStream();

To also set the user-agent add the following code:

conn.setRequestProperty ( "User-agent", "my agent name");

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   * @example
   * import { map, filter, scan } from 'rxjs/operators';
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

django MultiValueDictKeyError error, how do I deal with it

Another thing to remember is that request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.

So, if your form is:

<form action="/login/" method="POST">
  <input type="text" name="keyword" placeholder="Search query">
  <input type="number" name="results" placeholder="Number of results">

then, request.POST['keyword'] and request.POST['results'] will contain the value of the input elements keyword and results, respectively.

What is an IIS application pool?

An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Application pools are used to separate sets of IIS worker processes that share the same configuration and application boundaries.

Does a foreign key automatically create an index?

Say you have a big table called orders, and a small table called customers. There is a foreign key from an order to a customer. Now if you delete a customer, Sql Server must check that there are no orphan orders; if there are, it raises an error.

To check if there are any orders, Sql Server has to search the big orders table. Now if there is an index, the search will be fast; if there is not, the search will be slow.

So in this case, the slow delete could be explained by the absence of an index. Especially if Sql Server would have to search 15 big tables without an index.

P.S. If the foreign key has ON DELETE CASCADE, Sql Server still has to search the order table, but then to remove any orders that reference the deleted customer.

Amazon S3 direct file upload from client browser - private key disclosure

To create a signature, I must use my secret key. But all things happens on a client side, so, the secret key can be easily revealed from page source (even if I obfuscate/encrypt my sources).

This is where you have misunderstood. The very reason digital signatures are used is so that you can verify something as correct without revealing your secret key. In this case the digital signature is used to prevent the user from modifying the policy you set for the form post.

Digital signatures such as the one here are used for security all around the web. If someone (NSA?) really were able to break them, they would have much bigger targets than your S3 bucket :)

The PowerShell -and conditional operator

Try like this:

if($user_sam -ne $NULL -and $user_case -ne $NULL)

Empty variables are $null and then different from "" ([string]::empty).

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\ set the property systemProxiesEnabled to true manually and restart eclipse.

Using Pip to install packages to Anaconda Environment

Uninstall the duplicated python installation. Just keep anaconda and create an env with the desired python version as specified here: Then your python and pip versions will change as you switch between envs.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info



  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
label {_x000D_
  cursor: pointer;_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_

Much more stylish using :before and :after

  font-family: sans-serif;  _x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_

Difference between Hive internal tables and external tables?

Consider this scenario which best suits for External Table:

A MapReduce (MR) job filters a huge log file to spit out n sub log files (e.g. each sub log file contains a specific message type log) and the output i.e n sub log files are stored in hdfs.

These log files are to be loaded into Hive tables for performing further analytic, in this scenario I would recommend an External Table(s), because the actual log files are generated and owned by an external process i.e. a MR job besides you can avoid an additional step of loading each generated log file into respective Hive table as well.

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";



Block Comments in a Shell Script

A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.

As far as the shell is concerned, you only need to replace 'END' with '=cut'.

echo "before comment"
: <<'=cut'

=head1 NAME - Example shell script with embedded POD documentation


echo "after comment"

(Found on "Embedding documentation in shell script")

Check if two unordered lists are equal

You want to see if they contain the same elements, but don't care about the order.

You can use a set:

>>> set(['one', 'two', 'three']) == set(['two', 'one', 'three'])

But the set object itself will only contain one instance of each unique value, and will not preserve order.

>>> set(['one', 'one', 'one']) == set(['one'])

So, if tracking duplicates/length is important, you probably want to also check the length:

def are_eq(a, b):
    return set(a) == set(b) and len(a) == len(b)

How can I get the baseurl of site?

To me, @warlock's looks like the best answer here so far, but I've always used this in the past;

string baseUrl = Request.Url.GetComponents(
    UriComponents.SchemeAndServer, UriFormat.UriEscaped)   

Or in a WebAPI controller;

string baseUrl = Url.Request.RequestUri.GetComponents(
    UriComponents.SchemeAndServer, UriFormat.Unescaped)

which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and @warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

Inputting a default image in case the src attribute of an html <img> is not valid?

<style type="text/css">
img {
   background-image: url('/images/default.png')

Be sure to enter dimensions of image and whether you want the image to tile or not.

Avoid web.config inheritance in child web application using inheritInChildApplications

It needs to go directly under the root <configuration> node and you need to set a path like this:

<?xml version="1.0"?>
    <location path="." inheritInChildApplications="false"> 
        <!-- Stuff that shouldn't be inherited goes in here -->

A better way to handle configuration inheritance is to use a <clear/> in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:

<?xml version="1.0"?>
        <!-- Child config's connection strings -->

Change the background color in a twitter bootstrap modal?

Add the following CSS;

.modal .modal-dialog .modal-content{  background-color: #d4c484; }

<div class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );

I don't know what that would look like with your python setup but that should be easy to translate.

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

String comparison technique used by Python

Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (

To reply to the comment

What? How else can ordering be defined other than left-to-right?

by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

How to call a php script/function on a html button click

Modify the_script.php like this.

the_function() {
    alert("You win");

Angular 4/5/6 Global Variables

Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.


    myTest = 1;

Component or anything else in Angular

..near the top right after imports:

declare const myTest: any;


console.warn(myTest); // outputs '1'

C# elegant way to check if a property's property is null

Just stumbled accross this post.

Some time ago I made a suggestion on Visual Studio Connect about adding a new ??? operator.

This would require some work from the framework team but don't need to alter the language but just do some compiler magic. The idea was that the compiler should change this code (syntax not allowed atm)

string product_name = Order.OrderDetails[0].Product.Name ??? "no product defined";

into this code

Func<string> _get_default = () => "no product defined"; 
string product_name = Order == null 
    ? _get_default.Invoke() 
    : Order.OrderDetails[0] == null 
        ? _get_default.Invoke() 
        : Order.OrderDetails[0].Product == null 
            ? _get_default.Invoke() 
            : Order.OrderDetails[0].Product.Name ?? _get_default.Invoke()

For null check this could look like

bool isNull = (Order.OrderDetails[0].Product ??? null) == null;

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?

In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Here is a basic approach - it sure can be improved - of what I understood to be your requirement.

This will display 2 columns, one with the groups name, and one with the list of items associated to the group.

The trick is simply to include a list within the items cell.

    <th>Groups Name</th>
    <th>Groups Items</th>
    <tr *ngFor="let group of groups">
          <li *ngFor="let item of group.items">{{item}}</li>

Verilog generate/genvar in an always block

To put it simply, you don't use generate inside an always process, you use generate to create a parametrized process or instantiate particular modules, where you can combine if-else or case. So you can move this generate and crea a particular process or an instantiation e.g.,

module #(
parameter XLEN = 64,
parameter USEIP = 0
 input clk,
input rstn,
input [XLEN-1:0] opA,
input [XLEN-1:0] opB,
input [XLEN-1:0] opR,
input en

always @(posedge clk or negedge rstn)
 opR <= '{default:0};
 opR <= opA+opB;
opR <= '{default:0};
  superAdder #(.XLEN(XLEN)) _adder(.clk(clk),.rstm(rstn), .opA(opA), .opB(opB), .opR(opR), .en(en));


C# Help reading foreign characters using StreamReader

I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.

How to send objects through bundle

Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.

The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:

1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.

2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.

3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.

Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)

     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.


It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

CodeIgniter : Unable to load the requested file:

try $this->load->view('home/home_view',$data);

instead of this:


jQuery: get parent, parent id?

Here are 3 examples:

$(document).on('click', 'ul li a', function (e) {_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
<script src=""></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="">Click here</a></li>_x000D_
<div id="results">_x000D_

Let me know whether it was helpful.

How can I use jQuery in Greasemonkey?

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)

Keyword not supported: "data source" initializing Entity Framework Context

Make sure you have Data Source and not DataSource in your connection string. The space is important. Trust me. I'm an idiot.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

This error typically comes up when the necessary port is taken by another program.

You said that you have changed the HTTP connector port from 8080 to 8081 so the two Tomcats do not clash, but have you also changed the <Server port="..." in tomcat/conf/server.xml to be different between your Tomcats?

Are there any other connectors ports which may possibly clash?

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

How to remove border from specific PrimeFaces p:panelGrid?

Please try this too

.ui-panelgrid tr, .ui-panelgrid td {
border:0 !important;

How can I ignore a property when serializing using the DataContractSerializer?

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

How to save the output of a console.log(object) to a file?

This is really late to the party, but maybe it will help someone. My solution seems similar to what the OP described as problematic, but maybe it's a feature that Chrome offers now, but not then. I tried right-clicking and saving the .log file after the object was written to the console, but all that gave me was a text file with this:

console.js:230 Done: Array(50000)[0 … 9999][10000 … 19999][20000 … 29999][30000 … 39999][40000 … 49999]length: 50000__proto__: Array(0)

which was of no use to anyone.

What I ended up doing was finding the console.log(data) in the code, dropped a breakpoint on it and then typed JSON.Stringify(data) in the console which displayed the entire object as a JSON string and the Chrome console actually gives you a button to copy it. Then paste into a text editor and there's your JSON

enter image description here

How to fill a Javascript object literal with many static key/value pairs efficiently?

In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Map is introduced.

let map = new Map([["key1", "value1"], ["key2", "value2"]]);
map.get("key1"); // => value1

check this reference for more info.

jQuery.inArray(), how to use it right?

I usually use

if(!(jQuery.inArray("test", myarray) < 0))


if(jQuery.inArray("test", myarray) >= 0)

How to pass password automatically for rsync SSH command?

I got it to work like this:

sshpass -p "password" rsync -ae "ssh -p remote_port_ssh" /local_dir  remote_user@remote_host:/remote_dir

ssh "permissions are too open" error

This is what worked for me (on mac)

sudo chmod 600 path_to_your_key.pem 

then :

ssh -i path_to_your_key user@server_ip

Hope it help

Git diff against a stash

Combining what I learned in this thread and in this one, when I want to see "what is inside the stash", I first run:

git stash show stash@{0}

That will show what files were modified. Then, to get a nice visual diff in a difftool, I do:

git difftool --dir-diff stash@{0} stash@{0}^

This will display all the differences at once of the given stash against its parent.

You can configure the diff tool in ~/.gitconfig, e.g. with Meld:

    tool = meld

Send email with PHP from html form on submit with the same script

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.

<!DOCTYPE html>
<title>Form submission</title>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">


Original answer

I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.


<!DOCTYPE html>
<title>Form submission</title>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">


PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    // You cannot use header and echo together. It's one or the other.

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:


  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at under Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="" or
  • action="".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.

Consult the following Q&A on Stack if sending mail fails:

Java: how to use UrlConnection to post request with authorization?

To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me

Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback

BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work. Inside my servlet to do GET using url like e.g. only method found HERE worked

Thanks to all contributors

        URL url = new URL(httpurl);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("client_id", id);
        params.put("client_secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", redirect);
        params.put("code", code);  // your INSTAGRAM code received 
        Set set = params.entrySet();
        Iterator i = set.iterator();
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
        System.out.println("INSTAGRAM token returned: "+builder.toString());

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Recommended method for escaping HTML in Java

On android (API 16 or greater) you can:


or for lower API:


How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();

    public void testSayHelloWorld() throws Exception {


What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath.


Relative Xpath: Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.

Below is the example of a relative XPath.


How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error


die (mysqli_error()); 


die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget -r -np -nH --cut-dirs=3 -R index.html http://hostname/aaa/bbb/ccc/ddd/

From man wget

‘-r’ ‘--recursive’ Turn on recursive retrieving. See Recursive Download, for more details. The default maximum depth is 5.

‘-np’ ‘--no-parent’ Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded. See Directory-Based Limits, for more details.

‘-nH’ ‘--no-host-directories’ Disable generation of host-prefixed directories. By default, invoking Wget with ‘-r’ will create a structure of directories beginning with This option disables such behavior.

‘--cut-dirs=number’ Ignore number directory components. This is useful for getting a fine-grained control over the directory where recursive retrieval will be saved.

Take, for example, the directory at ‘’. If you retrieve it with ‘-r’, it will be saved locally under While the ‘-nH’ option can remove the part, you are still stuck with pub/xemacs. This is where ‘--cut-dirs’ comes in handy; it makes Wget not “see” number remote directory components. Here are several examples of how ‘--cut-dirs’ option works.

No options -> -nH -> pub/xemacs/ -nH --cut-dirs=1 -> xemacs/ -nH --cut-dirs=2 -> .

--cut-dirs=1 -> ... If you just want to get rid of the directory structure, this option is similar to a combination of ‘-nd’ and ‘-P’. However, unlike ‘-nd’, ‘--cut-dirs’ does not lose with subdirectories—for instance, with ‘-nH --cut-dirs=1’, a beta/ subdirectory will be placed to xemacs/beta, as one would expect.

jQuery UI Dialog with ASP.NET button postback

Be aware that there is an additional setting in jQuery UI v1.10. There is an appendTo setting that has been added, to address the ASP.NET workaround you're using to re-add the element to the form.


     autoOpen: false,
     height: 280,
     width: 440,
     modal: true,

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
var data_filter = data.filter( element => =="yahoo")_x000D_

Execute a large SQL script (with GO commands)

You can use SQL Management Objects to perform this. These are the same objects that Management Studio uses to execute queries. I believe Server.ConnectionContext.ExecuteNonQuery() will perform what you need.

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 

c. Using jQuery inside tag


<div class="demo" > Some text here </div>


$(".demo").click( function() {

Writing a Python list of lists to a csv file

Make sure to indicate lineterinator='\n' when create the writer; otherwise, an extra empty line might be written into file after each data line when data sources are from other csv file...

Here is my solution:

with open('csvfile', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter='    ',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for i in range(0, len(data)):

Read CSV with Scanner()

I have seen many production problems caused by code not handling quotes ("), newline characters within quotes, and quotes within the quotes; e.g.: "he said ""this""" should be parsed into: he said "this"

Like it was mentioned earlier, many CSV parsing examples out there just read a line, and then break up the line by the separator character. This is rather incomplete and problematic.

For me and probably those who prefer build verses buy (or use somebody else's code and deal with their dependencies), I got down to classic text parsing programming and that worked for me:

 * Parse CSV data into an array of String arrays. It handles double quoted values.
 * @param is input stream
 * @param separator
 * @param trimValues
 * @param skipEmptyLines
 * @return an array of String arrays
 * @throws IOException
public static String[][] parseCsvData(InputStream is, char separator, boolean trimValues, boolean skipEmptyLines)
    throws IOException
    ArrayList<String[]> data = new ArrayList<String[]>();
    ArrayList<String> row = new ArrayList<String>();
    StringBuffer value = new StringBuffer();
    int ch = -1;
    int prevCh = -1;
    boolean inQuotedValue = false;
    boolean quoteAtStart = false;
    boolean rowIsEmpty = true;
    boolean isEOF = false;

    while (true)
        prevCh = ch;
        ch = (isEOF) ? -1 :;

        // Handle carriage return line feed
        if (prevCh == '\r' && ch == '\n')
        if (inQuotedValue)
            if (ch == -1)
                inQuotedValue = false;
                isEOF = true;

                if (ch == '"')
                    inQuotedValue = false;
        else if (ch == separator || ch == '\r' || ch == '\n' || ch == -1)
            // Add the value to the row
            String s = value.toString();

            if (quoteAtStart && s.endsWith("\""))
                s = s.substring(1, s.length() - 1);
            if (trimValues)
                s = s.trim();
            rowIsEmpty = (s.length() > 0) ? false : rowIsEmpty;

            if (ch == '\r' || ch == '\n' || ch == -1)
                // Add the row to the result
                if (!skipEmptyLines || !rowIsEmpty)
                    data.add(row.toArray(new String[0]));
                rowIsEmpty = true;

                if (ch == -1)
        else if (prevCh == '"')
            inQuotedValue = true;
            if (ch == '"')
                inQuotedValue = true;
                quoteAtStart = (value.length() == 0) ? true : false;
    return data.toArray(new String[0][]);

Unit Test:

String[][] data = parseCsvData(new ByteArrayInputStream("foo,\"\",,\"bar\",\"\"\"music\"\"\",\"carriage\r\nreturn\",\"new\nline\"\r\nnext,line".getBytes()), ',', true, true);
for (int rowIdx = 0; rowIdx < data.length; rowIdx++)

generates the output:

[foo, , , bar, "music", carriage
return, new
[next, line]

How do I compare two Integers?

Compare integer and print its value in value ascending or descending order. All you have to do is implements Comparator interface and override its compare method and compare its value as below:

public int compare(Integer o1, Integer o2) {
    if (ascending) {
        return o1.intValue() - o2.intValue();
    } else {
        return o2.intValue() - o1.intValue();


How to install older version of node.js on Windows?

For windows, best is: nvm-windows

1)install the .exe

2)restart (otherwise, nvm will not be undefined)

3)run CMD as admin,

4)nvm use 5.6.0

Note: You MUST run as Admin to switch node version every time.

Location of WSDL.exe

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\wsdl.exe

(via this question: Where can I find WSDL.exe?)

How to fix the " No subject alternative names present" error?

This code will work like charm and use the restTemple object for rest of the code.

  RestTemplate restTemplate = new RestTemplate();   
  TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            public boolean isTrusted([] x509Certificates, String s) {
                return true;


        SSLContext sslContext = null;
        try {
            sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        } catch (KeyStoreException e) {
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();


Visual Studio: How to show Overloads in IntelliSense?

Tested only on Visual Studio 2010.

Place your cursor within the (), press Ctrl+K, then P.

Now navigate by pressing the  ?  / ?   arrow keys.

Failed to build gem native extension (installing Compass)

On yosemite, all you must do is install the command line tools. then it works.

Even if other gems installed fine. You must run xcode-select --install for gem install compass to work.

Good luck.

Android emulator not able to access the internet

Simply open the AVD Manager and wipe the data of that emulator works for me.

Selenium wait until document is ready

For the people who need to wait for a specific element to show up. (used c#)

public static void WaitForElement(IWebDriver driver, By element)
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));

Then if you want to wait for example if an class="error-message" exists in the DOM you simply do:

WaitForElement(driver, By.ClassName("error-message"));

For id, it will then be

WaitForElement(driver, By.Id("yourid"));

Rebuild all indexes in a Database

Also a good script, although my laptop ran out of memory, but this was on a very large table

USE [<mydatabasename>]

--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments             Data Type               Description
--------------          ------------            ------------
--@FillFactor           [int]                   Specifies a percentage that indicates how full the Database Engine should make the leaf level
--                                              of each index page during index creation or alteration. The valid inputs for this parameter
--                                              must be an integer value from 1 to 100 The default is 0.
--                                              For more information, see

--@PadIndex             [varchar](3)            Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
--                                              because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
--                                              for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
--                                              overrides the percentage to allow for the minimum. The number of rows on an intermediate
--                                              index page is never less than two, regardless of how low the value of fillfactor. The valid
--                                              inputs for this parameter are ON or OFF. The default is OFF.
--                                              For more information, see

--@SortInTempDB         [varchar](3)            Specifies whether to store temporary sort results in tempdb. The valid inputs for this
--                                              parameter are ON or OFF. The default is OFF.
--                                              For more information, see

--@OnlineRebuild        [varchar](3)            Specifies whether underlying tables and associated indexes are available for queries and data
--                                              modification during the index operation. The valid inputs for this parameter are ON or OFF.
--                                              The default is OFF.
--                                              Note: Online index operations are only available in Enterprise edition of Microsoft
--                                                      SQL Server 2005 and above.
--                                              For more information, see

--@DataCompression      [varchar](4)            Specifies the data compression option for the specified index, partition number, or range of
--                                              partitions. The options  for this parameter are as follows:
--                                                  > NONE - Index or specified partitions are not compressed.
--                                                  > ROW  - Index or specified partitions are compressed by using row compression.
--                                                  > PAGE - Index or specified partitions are compressed by using page compression.
--                                              The default is NONE.
--                                              Note: Data compression feature is only available in Enterprise edition of Microsoft
--                                                      SQL Server 2005 and above.
--                                              For more information about compression, see

--@MaxDOP               [int]                   Overrides the max degree of parallelism configuration option for the duration of the index
--                                              operation. The valid input for this parameter can be between 0 and 64, but should not exceed
--                                              number of processors available to SQL Server.
--                                              For more information, see
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/

-- Ensure a USE <databasename> statement has been executed first.


DECLARE  @Version                           [numeric] (18, 10)
        ,@SQLStatementID                    [int]
        ,@CurrentTSQLToExecute              [nvarchar](max)
        ,@FillFactor                        [int]        = 100 -- Change if needed
        ,@PadIndex                          [varchar](3) = N'OFF' -- Change if needed
        ,@SortInTempDB                      [varchar](3) = N'OFF' -- Change if needed
        ,@OnlineRebuild                     [varchar](3) = N'OFF' -- Change if needed
        ,@LOBCompaction                     [varchar](3) = N'ON' -- Change if needed
        ,@DataCompression                   [varchar](4) = N'NONE' -- Change if needed
        ,@MaxDOP                            [int]        = NULL -- Change if needed
        ,@IncludeDataCompressionArgument    [char](1);

IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
    DROP TABLE #Work_To_Do
      [sql_id] [int] IDENTITY(1, 1)
                     PRIMARY KEY ,
      [tsql_text] [varchar](1024) ,
      [completed] [bit]

SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))

IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
    AND (
        @Version >= 10.0
        AND SERVERPROPERTY(N'EngineEdition') = 3
    SET @IncludeDataCompressionArgument = N'Y'

IF @IncludeDataCompressionArgument IS NULL
    SET @IncludeDataCompressionArgument = N'N'

INSERT INTO #Work_To_Do ([tsql_text], [completed])
        WHEN @PadIndex IS NULL
            THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
                    WHEN 1
                        THEN 'ON'
                    WHEN 0
                        THEN 'OFF'
        ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
        END + CASE
        WHEN @FillFactor IS NULL
            THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
        ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
        END + CASE
        WHEN @SortInTempDB IS NULL
            THEN ''
        ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
        END + CASE
        WHEN @OnlineRebuild IS NULL
            THEN ''
        ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
        END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + CASE
        WHEN @IncludeDataCompressionArgument = N'Y'
            THEN CASE
                    WHEN @DataCompression IS NULL
                        THEN ''
                    ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
        ELSE ''
        END + CASE
        WHEN @MaxDop IS NULL
            THEN ''
        ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
        END + SPACE(1) + ')'
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
    AND i.[index_id] > 0
    AND i.[type] IN (1, 2)
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
    AND st.[name] = i.[name]

SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0

    SELECT @CurrentTSQLToExecute = [tsql_text]
    FROM #Work_To_Do
    WHERE [sql_id] = @SQLStatementID

    PRINT @CurrentTSQLToExecute

    EXEC [sys].[sp_executesql] @CurrentTSQLToExecute

    UPDATE #Work_To_Do
    SET [completed] = 1
    WHERE [sql_id] = @SQLStatementID

    SELECT @SQLStatementID = MIN([sql_id])
    FROM #Work_To_Do
    WHERE [completed] = 0

How to parse JSON string in Typescript

There is a great library for it ts-json-object

In your case you would need to run the following code:

import {JSONObject, required} from 'ts-json-object'

class Response extends JSONObject {
    name: string;

    error: boolean;

let resp = new Response({"name": "Bob", "error": false});

This library will validate the json before parsing

Spring Boot and multiple external configuration files

spring boot allows us to write different profiles to write for different environments, for example we can have separate properties files for production, qa and local environments file with configurations according to my local machine is


Similarly, we can write and as many properties files as we want

then write some scripts to start the application for different environments, for e.g.

mvn spring-boot:run -Drun.profiles=local
mvn spring-boot:run -Drun.profiles=qa
mvn spring-boot:run -Drun.profiles=prod

Android Webview - Completely Clear the Cache

The only solution that works for me


PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.


    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)


@section JavaScript
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>

Angular 2: How to access an HTTP response body?

This is work for me 100% :

let data:Observable<any> =, postData);
  data.subscribe((data) => {

  let d = data.json();
  console.log("result = " + d.result);
  console.log("url = " + d.image_url);      

What is reflection and why is it useful?

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java have the method getClass(), which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an Object) - this might seem trivial, but such reflection is not possible in less dynamic languages such as C++. More advanced uses lets you list and call methods, constructors, etc.

Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));



PHP Adding 15 minutes to Time value

strtotime returns the current timestamp and date is to format timestamp

  $date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds

This will add 15 mins to the current time

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

Add a auto increment primary key to existing table in oracle

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

Then create a trigger that increments upon insert:

create trigger t1_trigger
before insert on t1
for each row
     select t1_seq.nextval into from dual;

Retrieve version from maven pom.xml in code

With reference to ketankk's answer:

Unfortunately, adding this messed with how my application dealt with resources:


But using this inside maven-assemble-plugin's < manifest > tag did the trick:


So I was able to get version using

String version = getClass().getPackage().getImplementationVersion();

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear:

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

You also follow this code:

var response = new HttpResponseMessage(HttpStatusCode.NotFound)
      Content = new StringContent("Users doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
      StatusCode = HttpStatusCode.NotFound
 throw new HttpResponseException(response);

What is the purpose of class methods?

When a user logs in on my website, a User() object is instantiated from the username and password.

If I need a user object without the user being there to log in (e.g. an admin user might want to delete another users account, so i need to instantiate that user and call its delete method):

I have class methods to grab the user object.

class User():
    #lots of code
    # more code

    def get_by_username(cls, username):
        return cls.query(cls.username == username).get()

    def get_by_auth_id(cls, auth_id):
        return cls.query(cls.auth_id == auth_id).get()

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called I renamed the file and the issue disappeared.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

How do I clone a range of array elements to a new array?

Array.ConstrainedCopy will work.

public static void ConstrainedCopy (
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length

Adding the "Clear" Button to an iPhone UITextField

  func clear_btn(box_is : UITextField){
    box_is.clearButtonMode = .always
    if let clearButton = box_is.value(forKey: "_clearButton") as? UIButton {
        let templateImage =  clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)

        clearButton.setImage(templateImage, for: .normal)
        clearButton.setImage(templateImage, for: .highlighted)

        clearButton.tintColor = .white


Figure out size of UILabel based on String in Swift

Swift 5:

If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

extension UILabel {
    func getSize(constrainedWidth: CGFloat) -> CGSize {
        return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)

You can use it like this:

let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)

Works for me

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

JSON to PHP Array using file_get_contents

You JSON is not a valid string as P. Galbraith has told you above.

and here is the solution for it.

$json_url = "";
$json = file_get_contents($json_url);


$data = json_decode($json);

echo "<pre>";
echo "</pre>";

Use this code it will work for you.

Turning Sonar off for certain code

Use //NOSONAR on the line you get warning if it is something you cannot help your code with. It works!

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

select 'abcd' + ltrim(str(1)) + ltrim(str(2))

Python: How to keep repeating a program until a specific input is obtained?

Easier way:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code

Separating class code into a header and cpp file

Usually you put only declarations and really short inline functions in the header file:

For instance:

class A {
  A(); // only declaration in the .h unless only a short initialization list is used.

  inline int GetA() const {
    return a_;

  void DoSomethingCoplex(); // only declaration
   int a_;

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

Strictly speaking, you can't get an iterator of the primitive array, because can only return an Object. But through the magic of autoboxing, you can get the iterator using the Arrays.asList() method.

Iterator<Integer> it = Arrays.asList(arr).iterator();

The above answer is wrong, you can't use Arrays.asList() on a primitive array, it would return a List<int[]>. Use Guava's Ints.asList() instead.

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;

Or you can leave your server side set to null and not pass the param at all.

java collections - keyset() vs entrySet() in map

Every time you call you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
        String v =;
        System.out.println("Key: "+v+" ,value: "+m.get(v));

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

Hide Text with CSS, Best Practice?

Actually, a new technique came out recently. This article will answer your questions:

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;

It is accessible, an has better performance than -99999px.

Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font:

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:


You can also set sql mode by this:


Textarea that can do syntax highlighting on the fly?

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');

var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');

  return text;

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);

function handleScroll() {
  var scrollTop = $textarea.scrollTop();

  var scrollLeft = $textarea.scrollLeft();

function fixIOS() {
    'padding-left': '+=3px',
    'padding-right': '+=3px'

function bindEvents() {
    'input': handleInput,
    'scroll': handleScroll

if (isIOS) {

@import url(;
*::after {
  box-sizing: border-box;

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;

textarea {
  width: 460px;
  height: 180px;

textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
<script src=""></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>

Original Pen:

Angular2, what is the correct way to disable an anchor element?

Just came across this question, and wanted to suggest an alternate approach.

In the markup the OP provided, there is a click event binding. This makes me think that the elements are being used as "buttons". If that is the case, they could be marked up as <button> elements and styled like links, if that is the look you desire. (For example, Bootstrap has a built-in "link" button style,

This has several direct and indirect benefits. It allows you to bind to the disabled property, which when set will disable mouse and keyboard events automatically. It lets you style the disabled state based on the disabled attribute, so you don't have to also manipulate the element's class. It is also better for accessibility.

For a good write-up about when to use buttons and when to use links, see Links are not buttons. Neither are DIVs and SPANs

When should you use 'friend' in C++?

You control the access rights for members and functions using Private/Protected/Public right? so assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something...

The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for everyone (except for an inherited child of course). But what about exceptions? every security system lets you have some type of 'white list" right?

So friend lets you have the flexibility of having rock solid object isolation, but allows for a "loophole" to be created for things that you feel are justified.

I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.

It doesn't really do any good, other than let you access a member variable without using a setting function

well that is not exactly the way to look at it. The idea is to control WHO can access what, having or not a setting function has little to do with it.