Programs & Examples On #Vtiger

Vtiger is a PHP-based, open-source CRM application which forked off SugarCRM. Very suitable for small and medium enterprises, it uses the Smarty template engine. One can also import and export specific modules with or without customization.

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

If changing target sdk version doesn't help then if you have any dependency with version 3.0.2 then change it to 3.0.1.

e.g change

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'

to

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.1'

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

How do I add a foreign key to an existing SQLite table?

Basically you cannot but you can bypass the situation.

The correct way to add the foreign key constraint to an existing table is the following command.

db.execSQL("alter table child add column newCol integer REFERENCES parent(parent_Id)");

Then copy the parent_Id data to the newCol and then delete the Parent_Id column. Hence, no need for temporary table.

"No Content-Security-Policy meta tag found." error in my phonegap application

You have to add a CSP meta tag in the head section of your app's index.html

As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy

Content Security Policy

Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).

On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. <video> & WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy <meta> tag on all of your pages.

On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).

Here are some example CSP declarations for your .html pages:

<!-- Good default declaration:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
        * Enable eval(): add 'unsafe-eval' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">

<!-- Allow requests to foo.com -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com">

<!-- Enable all requests, inline styles, and eval() -->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

<!-- Allow XHRs via https only -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">

<!-- Allow iframe to https://cordova.apache.org/ -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

SQL Server loop - how do I loop through a set of records

By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;

SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')

OPEN @BusinessCursor;
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msg = '{
              "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
              "Customer": {
                "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
              }
            }|'
        print @msg
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END

Wait .5 seconds before continuing code VB.net

You'll need to use System.Threading.Thread.Sleep(number of milliseconds).

WebBrowser1.Document.Window.DomWindow.execscript("checkPasswordConfirm();","JavaScript")

Threading.Thread.Sleep(500) ' 500 milliseconds = 0.5 seconds

Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
    If webpageelement.InnerText = "Sign Up" Then
        webpageelement.InvokeMember("click")
    End If
Next

Add a background image to shape in XML Android

This is a corner image

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/img_main_blue"
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <item>
        <shape
            android:padding="10dp"
            android:shape="rectangle">
            <corners android:radius="10dp" />
            <stroke
                android:width="5dp"
                android:color="@color/white" />
        </shape>

    </item>
</layer-list>

How to revert a merge commit that's already pushed to remote branch?

I found creating a reverse patch between two know end-points and applying that patch would work. This presumes that you have created snapshots (tags) off of your master branch or even a back up of your master branch say master_bk_01012017.

Say the code branch you merged into master was mycodebranch.

  1. Checkout master.
  2. Create a full binary reverse patch between master and your backup. git diff --binary master..master_bk_01012017 > ~/myrevert.patch
  3. Check your patch git apply --check myrevert.patch
  4. Apply patch with sign-off git am --signoff < myrevert.patch
  5. If you will need to bring in this code again once it is fixed, you will need to branch off the reverted master and checkout the fix branch git branch mycodebranch_fix git checkout mycodebranch_fix
  6. Here you need to find the SHA key for the revert and revert the revert git revert [SHA]
  7. Now you can use your mycodebranch_fix to fix the issues, commit and re-merge into master once done.

What is the Swift equivalent of respondsToSelector?

I use guard let else, so that can do some default stuff if the delegate func is not implemented.

@objc protocol ViewController2Delegate: NSObjectProtocol {

    optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnVoid string: String)

    optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnString string: String) -> String
}

class ViewController2: UIViewController {

    weak var delegate: ViewController2Delegate?        

    @IBAction func onVoidButtonClicked(sender: AnyObject){

        if (delegate != nil && delegate!.respondsToSelector(Selector("viewController2:didSomethingWithStringAndReturnVoid:"))) {
            NSLog("ReturnVoid is implemented")

            delegate!.viewController2!(self, didSomethingWithStringAndReturnVoid: "dummy")
        }
        else{
            NSLog("ReturnVoid is not implemented")
            // Do something by default
        }
    }

    @IBAction func onStringButtonClicked(sender: AnyObject){

        guard let result = delegate?.viewController2?(self, didSomethingWithStringAndReturnString: "dummy") else {
            NSLog("ReturnString is not implemented")
            // Do something by default
            return
        }

        NSLog("ReturnString is implemented with result: \(result)")
    }
}

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init part on the ng-form element and the use of furryName. furryName becomes the variable name that contains the variable value for the input's name attribute.

<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
        <!-- animal is furry toggle buttons -->
        <input id="furryRadio{{$index}}"
               type="radio"
               name="{{furryName}}"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolTrue"
               required
                >
        <label for="furryRadio{{$index}}">Furry</label>

        <input id="hairlessRadio{{$index}}"
               name="{{furryName}}"
               type="radio"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolFalse"
               required
               >
        <label for="hairlessRadio{{$index}}">Hairless</label>

        <div ng-messages="animalsForm[furryName].$error"
             class="form-errors"
             ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
            <div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
        </div>
</ng-form>
</ion-item>

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

How to implement history.back() in angular.js

In AngularJS2 I found a new way, maybe is just the same thing but in this new version :

import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router'; 

(...)

constructor(private _router: Router, private _location: Location) {}

onSubmit() {
    (...)
    self._location.back();
}

After my function, I can see that my application is going to the previous page usgin location from angular2/router.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html

How do I close an Android alertdialog

Use Dialog instead of AlertDialog

AlertDialog doesn't have dismiss() but AlertDialog has some methods for button like setPositiveButton().

I recommend to use Dialog if you want customized dialog.

C# 4.0: Convert pdf to byte[] and vice versa

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

Add days to JavaScript Date

My simple solution is:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

is correct code.

Collision resolution in Java HashMap

There is difference between collision and duplication. Collision means hashcode and bucket is same, but in duplicate, it will be same hashcode,same bucket, but here equals method come in picture.

Collision detected and you can add element on existing key. but in case of duplication it will replace new value.

Best way to implement multi-language/globalization in large .NET project

I don't think there is a "best way". It really will depend on the technologies and type of application you are building.

Webapps can store the information in the database as other posters have suggested, but I recommend using seperate resource files. That is resource files seperate from your source. Seperate resource files reduces contention for the same files and as your project grows you may find localization will be done seperatly from business logic. (Programmers and Translators).

Microsoft WinForm and WPF gurus recommend using seperate resource assemblies customized to each locale.

WPF's ability to size UI elements to content lowers the layout work required eg: (japanese words are much shorter than english).

If you are considering WPF: I suggest reading this msdn article To be truthful I found the WPF localization tools: msbuild, locbaml, (and maybe an excel spreadsheet) tedious to use, but it does work.

Something only slightly related: A common problem I face is integrating legacy systems that send error messages (usually in english), not error codes. This forces either changes to legacy systems, or mapping backend strings to my own error codes and then to localized strings...yech. Error codes are localizations friend

How to identify a strong vs weak relationship on ERD?

  1. Weak (Non-Identifying) Relationship

    • Entity is existence-independent of other enties

    • PK of Child doesn’t contain PK component of Parent Entity

  2. Strong (Identifying) Relationship

    • Child entity is existence-dependent on parent

    • PK of Child Entity contains PK component of Parent Entity

    • Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..

 if (model is ViewDataDictionary)
 {
     controller.ViewData = model as ViewDataDictionary;
 } else {
     controller.ViewData.Model = model;
 }

Disabling vertical scrolling in UIScrollView

The most obvious solution is to forbid y-coordinate changes in your subclass.

override var contentOffset: CGPoint {
  get {
    return super.contentOffset
  }
  set {
    super.contentOffset = CGPoint(x: newValue.x, y: 0)
  }
}

This is the only suitable solution in situations when:

  1. You are not allowed or just don't want to use delegate.
  2. Your content height is larger than container height

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

If you use alternatives to manage multiple java versions, you can set the JAVA_HOME based on the symlinked java (or javac) like this:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

Switching to a TabBar tab view programmatically?

Use in AppDelegate.m file:

(void)tabBarController:(UITabBarController *)tabBarController
 didSelectViewController:(UIViewController *)viewController
{

     NSLog(@"Selected index: %d", tabBarController.selectedIndex);

    if (viewController == tabBarController.moreNavigationController)
    {
        tabBarController.moreNavigationController.delegate = self;
    }

    NSUInteger selectedIndex = tabBarController.selectedIndex;

    switch (selectedIndex) {

        case 0:
            NSLog(@"click me %u",self.tabBarController.selectedIndex);
            break;
        case 1:
            NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
            break;

        default:
            break;

    }

}

Javascript onHover event

If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:

$(this).hover(function(){},function(){});

The first function is the start of the hover and the next is the end. Read more at: http://docs.jquery.com/Events/hover

How to print all information from an HTTP request to the screen, in PHP

in addition, you can use get_headers(). it doesn't depend on apache..

print_r(get_headers());

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Android Home should be the root folder of SDK.

export ANDROID_HOME="$HOME/android-sdk-linux"

EDIT: Open terminal and type these commands. (yes, on a ternimal , not in bashrc file)

export ANDROID_HOME=~/android-sdk-macosx
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools    

and then in the same terminal just type android. If configured you would be able to use build commands from this terminal. (it's a temporary solution)

Adding Table rows Dynamically in Android

public Boolean addArtist(String artistName){

        SQLiteDatabase db= getWritableDatabase();

        ContentValues data=new ContentValues();
        data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
        long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);

        if(id>0){
            return true;
        }else{
            return false;
        }
    }

jQuery has deprecated synchronous XMLHTTPRequest

To avoid this warning, do not use:

async: false

in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.

The default is async: true, so if you never use this option at all, your code should be safe if the feature is ever really removed.

However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.

Notice that the Fetch API that's replacing XMLHttpRequest does not even offer a synchronous option.

What range of values can integer types store in C++

Can unsigned long int hold a ten digits number (1,000,000,000 - 9,999,999,999) on a 32-bit computer.

No

How can I read numeric strings in Excel cells as string (not numbers)?

As long as the cell is in text format before the user types in the number, POI will allow you to obtain the value as a string. One key is that if there is a small green triangle in the upper left-hand corner of cell that is formatted as Text, you will be able to retrieve its value as a string (the green triangle appears whenever something that appears to be a number is coerced into a text format). If you have Text formatted cells that contain numbers, but POI will not let you fetch those values as strings, there are a few things you can do to the Spreadsheet data to allow that:

  • Double click on the cell so that the editing cursor is present inside the cell, then click on Enter (which can be done only one cell at a time).
  • Use the Excel 2007 text conversion function (which can be done on multiple cells at once).
  • Cut out the offending values to another location, reformat the spreadsheet cells as text, then repaste the previously cut out values as Unformatted Values back into the proper area.

One final thing that you can do is that if you are using POI to obtain data from an Excel 2007 spreadsheet, you can the Cell class 'getRawValue()' method. This does not care what the format is. It will simply return a string with the raw data.

how to do "press enter to exit" in batch

Use this snippet:

@echo off
echo something
echo.
echo press enter to exit
pause >nul
exit

What's better at freeing memory with PHP: unset() or $var = null

I created a new performance test for unset and =null, because as mentioned in the comments the here written has an error (the recreating of the elements). I used arrays, as you see it didn't matter now.

<?php
$arr1 = array();
$arr2 = array();
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = 'a';
    $arr2[$i] = 'a';
}

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = null;
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

But i can only test it on an PHP 5.5.9 server, here the results: - took 4.4571571350098 seconds - took 4.4425978660583 seconds

I prefer unset for readability reasons.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

WCF gives an unsecured or incorrectly secured fault error

Try with this:

catch (System.Reflection.TargetInvocationException e1)  
      String excType   
      excType = e1.InnerException.GetType().ToString()  
      choose case excType  
                case "System.ServiceModel.FaultException"  
                          System.ServiceModel.FaultException e2  
                          e2 = e1.InnerException  
                          System.ServiceModel.Channels.MessageFault fault  
                          fault = e2.CreateMessageFault()  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + fault.Reason.ToString()   
                          if (fault.HasDetail) then  
                                    System.Xml.XmlReader reader  
                                    reader = fault.GetReaderAtDetailContents()  
                                    ls_message += " " + reader.Value  
                                    do while reader.Read()  
                                              ls_message += reader.Value  
                                    loop  
                          end if  
                case "System.Text.DecoderFallbackException"  
                          System.Text.DecoderFallbackException e3  
                          e3 = e1.InnerException  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e3.Message   
                case else  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e1.Message  
      end choose  
      MessageBox ( "Error", ls_message )  
      //logError(ls_message)  
      return false  

Ignore 'Security Warning' running script from command line

I made this powershell script to unblock all files on a share on my server

Get-ChildItem "\\ServerName\e$\MyDirectory\" -Recurse -File | % {
       Unblock-File -Path $_.FullName
}

How to get document height and width without using jquery

If you want to get the full width of the page, including overflow, use document.body.scrollWidth.

Fail during installation of Pillow (Python module) in Linux

Try

pip install pillow

If it doesn't work, try clearing the

cache by pip install --upgrade pip

Then again run

pip install pillow

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

Getting only hour/minute of datetime

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

No Access-Control-Allow-Origin header is present on the requested resource

I find the solution in spring.io,like this:

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How to change color of the back arrow in the new material theme?

Just add

<item name="colorControlNormal">@color/white</item> 

to your current app theme.

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

How to check 'undefined' value in jQuery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}

Maven dependencies are failing with a 501 error

Add the following repository in pom.xml.

<project>
...
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Plugin Repository</name>
            <url>https://repo1.maven.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
...
</project>

Apply CSS rules if browser is IE

In browsers up to and including IE9, this is done through conditional comments.

<!--[if IE]>
<style type="text/css">
  IE specific CSS rules go here
</style>
<![endif]-->

How to parse this string in Java?

 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Find the location of a character in string

You could use grep as well:

grep('2', strsplit(string, '')[[1]])
#4 24

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Actually you can set custom text to that little blue button. In the xml file just use

android:imeActionLabel="whatever"

on your EditText.

Or in the java file use

etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE);

I arbitrarily choose IME_ACTION_DONE as an example of what should go in the second parameter for this function. A full list of these actions can be found here.

It should be noted that this will not cause text to appear on all keyboards on all devices. Some keyboards do not support text on that button (e.g. swiftkey). And some devices don't support it either. A good rule is, if you see text already on the button, this will change it to whatever you'd want.

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

How to check for valid email address?

from validate_email import validate_email
is_valid = validate_email('[email protected]',verify=True)
print(bool(is_valid))

See validate_email docs.

How to return a value from a Form in C#?

I raise an event in the the form setting the value and subscribe to that event in the form(s) that need to deal with the value change.

What is an application binary interface (ABI)?

An application binary interface (ABI) is similar to an API, but the function is not accessible to the caller at source code level. Only a binary representation is accessible/available.

ABIs may be defined at the processor-architecture level or at the OS level. The ABIs are standards to be followed by the code-generator phase of the compiler. The standard is fixed either by the OS or by the processor.

Functionality: Define the mechanism/standard to make function calls independent of the implementation language or a specific compiler/linker/toolchain. Provide the mechanism which allows JNI, or a Python-C interface, etc.

Existing entities: Functions in machine code form.

Consumer: Another function (including one in another language, compiled by another compiler, or linked by another linker).

Limiting the number of characters per line with CSS

You could do this:
(Note! This is CSS3 and the browser support = good!! )

   p {
    text-overflow: ellipsis; /* will make [...] at the end */
    width: 370px; /* change to your preferences */
    white-space: nowrap; /* paragraph to one line */
    overflow:hidden; /* older browsers */
    }

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode is a new feature of iOS 9

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Note: For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required

So you should disabled bitcode until all the frameworks of your app have bitcode enabled.

The view or its master was not found or no view engine supports the searched locations

In Microsoft ASP.net MVC, the routing engine, which is used to parse incoming and outgoing URL Combinations, is designed with the idea of Convention over Configuration. What this means is that if you follow the Convention (rules) that the routing engine uses, you don't have to change the Configuration.

The routing engine for ASP.net MVC does not serve web pages (.cshtml). It provides a way for a URL to be handled by a Class in your code, which can render text/html to the output stream, or parse and serve the .cshtml files in a consistent manner using Convention.

The Convention which is used for routing is to match a Controller to a Class with a name similar to ControllerNameController i.e. controller="MyAccount" means find class named MyAccountController. Next comes the action, which is mapped to a function within the Controller Class, which usually returns an ActionResult. i.e. action="LoginRegister" will look for a function public ActionResult LoginRegister(){} in the controller's class. This function may return a View() which would be by Convention named LoginRegister.cshtml and would be stored in the /Views/MyAccount/ folder.

To summarize, you would have the following code:

/Controllers/MyAccountController.cs:

public class MyAccountController : Controller 
{
    public ActionResult LoginRegister()
    {
        return View();
    }
}

/Views/MyAccount/LoginRegister.cshtml: Your view file.

Replace invalid values with None in Pandas DataFrame

Before proceeding with this post, it is important to understand the difference between NaN and None. One is a float type, the other is an object type. Pandas is better suited to working with scalar types as many methods on these types can be vectorised. Pandas does try to handle None and NaN consistently, but NumPy cannot.

My suggestion (and Andy's) is to stick with NaN.

But to answer your question...

pandas >= 0.18: Use na_values=['-'] argument with read_csv

If you loaded this data from CSV/Excel, I have good news for you. You can quash this at the root during data loading instead of having to write a fix with code as a subsequent step.

Most of the pd.read_* functions (such as read_csv and read_excel) accept a na_values attribute.

file.csv

A,B
-,1
3,-
2,-
5,3
1,-2
-5,4
-1,-1
-,0
9,0

Now, to convert the - characters into NaNs, do,

import pandas as pd
df = pd.read_csv('file.csv', na_values=['-'])
df

     A    B
0  NaN  1.0
1  3.0  NaN
2  2.0  NaN
3  5.0  3.0
4  1.0 -2.0
5 -5.0  4.0
6 -1.0 -1.0
7  NaN  0.0
8  9.0  0.0

And similar for other functions/file formats.

P.S.: On v0.24+, you can preserve integer type even if your column has NaNs (yes, talk about having the cake and eating it too). You can specify dtype='Int32'

df = pd.read_csv('file.csv', na_values=['-'], dtype='Int32')
df

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

df.dtypes

A    Int32
B    Int32
dtype: object

The dtype is not a conventional int type... but rather, a Nullable Integer Type. There are other options.


Handling Numeric Data: pd.to_numeric with errors='coerce

If you're dealing with numeric data, a faster solution is to use pd.to_numeric with the errors='coerce' argument, which coerces invalid values (values that cannot be cast to numeric) to NaN.

pd.to_numeric(df['A'], errors='coerce')

0    NaN
1    3.0
2    2.0
3    5.0
4    1.0
5   -5.0
6   -1.0
7    NaN
8    9.0
Name: A, dtype: float64

To retain (nullable) integer dtype, use

pd.to_numeric(df['A'], errors='coerce').astype('Int32')

0    NaN
1      3
2      2
3      5
4      1
5     -5
6     -1
7    NaN
8      9
Name: A, dtype: Int32 

To coerce multiple columns, use apply:

df[['A', 'B']].apply(pd.to_numeric, errors='coerce').astype('Int32')

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

...and assign the result back after.

More information can be found in this answer.

Finding height in Binary Search Tree

I know that I’m late to the party. After looking into wonderful answers provided here, I thought mine will add some value to this post. Although the posted answers are amazing and easy to understand however, all are calculating the height to the BST in linear time. I think this can be improved and Height can be retrieved in constant time, hence writing this answer – hope you will like it. Let’s start with the Node class:

public class Node
{
    public Node(string key)
    {
        Key = key;
        Height = 1;
    }    

    public int Height { get; set; } 
    public string Key { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }

    public override string ToString()
    {
        return $"{Key}";
    }
}

BinarySearchTree class

So you might have guessed the trick here… Im keeping node instance variable Height to keep track of each node when added. Lets move to the BinarySearchTree class that allows us to add nodes into our BST:

public class BinarySearchTree
{
    public Node RootNode { get; private set; }

    public void Put(string key)
    {
        if (ContainsKey(key))
        {
            return;
        }

        RootNode = Put(RootNode, key);
    }

    private Node Put(Node node, string key)
    {
        if (node == null) return new Node(key);

        if (node.Key.CompareTo(key) < 0)
        {
            node.Right = Put(node.Right, key);
        }
        else
        {
            node.Left = Put(node.Left, key);
        }       
        
        // since each node has height property that is maintained through this Put method that creates the binary search tree.
        // calculate the height of this node by getting the max height of its left or right subtree and adding 1 to it.        
        node.Height = Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
        return node;
    }

    private int GetHeight(Node node)
    {
        return node?.Height ?? 0;
    }

    public Node Get(Node node, string key)
    {
        if (node == null) return null;
        if (node.Key == key) return node;

        if (node.Key.CompareTo(key) < 0)
        {
            // node.Key = M, key = P which results in -1
            return Get(node.Right, key);
        }

        return Get(node.Left, key);
    }

    public bool ContainsKey(string key)
    {
        Node node = Get(RootNode, key);
        return node != null;
    }
}

Once we have added the key, values in the BST, we can just call Height property on the RootNode object that will return us the Height of the RootNode tree in constant time. The trick is to keep the height updated when a new node is added into the tree. Hope this helps someone out there in the wild world of computer science enthusiast!

Unit test:

[TestCase("SEARCHEXAMPLE", 6)]
[TestCase("SEBAQRCHGEXAMPLE", 6)]
[TestCase("STUVWXYZEBAQRCHGEXAMPLE", 8)]
public void HeightTest(string data, int expectedHeight)
{
    // Arrange.
    var runner = GetRootNode(data);

    
    //  Assert.
    Assert.AreEqual(expectedHeight, runner.RootNode.Height);
}

private BinarySearchTree GetRootNode(string data)
{
    var runner = new BinarySearchTree();
    foreach (char nextKey in data)
    {
        runner.Put(nextKey.ToString());
    }

    return runner;
}

Note: This idea of keeping the Height of tree maintained in every Put operation is inspired by the Size of BST method found in the 3rd chapter (page 399) of Algorithm (Fourth Edition) book.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

How do I define a method which takes a lambda as a parameter in Java 8?

To use Lambda expression you need to either create your own functional interface or use Java functional interface for operation that require two integer and return as value. IntBinaryOperator

Using user defined functional interface

interface TwoArgInterface {

    public int operation(int a, int b);
}

public class MyClass {

    public static void main(String javalatte[]) {
        // this is lambda expression
        TwoArgInterface plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.operation(10, 34));

    }
}

Using Java functional interface

import java.util.function.IntBinaryOperator;

public class MyClass1 {

    static void main(String javalatte[]) {
        // this is lambda expression
        IntBinaryOperator plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.applyAsInt(10, 34));

    }
}

How do I get indices of N maximum values in a NumPy array?

When top_k<<axis_length,it better than argsort.

import numpy as np

def get_sorted_top_k(array, top_k=1, axis=-1, reverse=False):
    if reverse:
        axis_length = array.shape[axis]
        partition_index = np.take(np.argpartition(array, kth=-top_k, axis=axis),
                                  range(axis_length - top_k, axis_length), axis)
    else:
        partition_index = np.take(np.argpartition(array, kth=top_k, axis=axis), range(0, top_k), axis)
    top_scores = np.take_along_axis(array, partition_index, axis)
    # resort partition
    sorted_index = np.argsort(top_scores, axis=axis)
    if reverse:
        sorted_index = np.flip(sorted_index, axis=axis)
    top_sorted_scores = np.take_along_axis(top_scores, sorted_index, axis)
    top_sorted_indexes = np.take_along_axis(partition_index, sorted_index, axis)
    return top_sorted_scores, top_sorted_indexes

if __name__ == "__main__":
    import time
    from sklearn.metrics.pairwise import cosine_similarity

    x = np.random.rand(10, 128)
    y = np.random.rand(1000000, 128)
    z = cosine_similarity(x, y)
    start_time = time.time()
    sorted_index_1 = get_sorted_top_k(z, top_k=3, axis=1, reverse=True)[1]
    print(time.time() - start_time)

Read and parse a Json File in C#

How about making everything easier with Json.NET?

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }

You can even get the values dynamically without declaring Item class.

    dynamic array = JsonConvert.DeserializeObject(json);
    foreach(var item in array)
    {
        Console.WriteLine("{0} {1}", item.temp, item.vcc);
    }

How to handle a lost KeyStore password in Android?

Open taskHistory.bin and search for storePassword

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Update: this was fixed in Firefox v35. See the full gist for details.


== how to hide the select arrow in Firefox ==

Just figured out how to do it. The trick is to use a mix of -prefix-appearance, text-indent and text-overflow. It is pure CSS and requires no extra markup.

select {
    -moz-appearance: none;
    text-indent: 0.01px;
    text-overflow: '';
}

Long story short, by pushing it a tiny bit to the right, the overflow gets rid of the arrow. Pretty neat, huh?

More details on this gist I just wrote. Tested on Ubuntu, Mac and Windows, all with recent Firefox versions.

How to dynamically load a Python class

If you don't want to roll your own, there is a function available in the pydoc module that does exactly this:

from pydoc import locate
my_class = locate('my_package.my_module.MyClass')

The advantage of this approach over the others listed here is that locate will find any python object at the provided dotted path, not just an object directly within a module. e.g. my_package.my_module.MyClass.attr.

If you're curious what their recipe is, here's the function:

def locate(path, forceload=0):
    """Locate an object by name or dotted path, importing as necessary."""
    parts = [part for part in split(path, '.') if part]
    module, n = None, 0
    while n < len(parts):
        nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
        if nextmodule: module, n = nextmodule, n + 1
        else: break
    if module:
        object = module
    else:
        object = __builtin__
    for part in parts[n:]:
        try:
            object = getattr(object, part)
        except AttributeError:
            return None
    return object

It relies on pydoc.safeimport function. Here are the docs for that:

"""Import a module; handle errors; return None if the module isn't found.

If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised.  Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning.  If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

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 {
            service.shutdown();
        }
    }
}

Verify ImageMagick installation

In Bash you can check if Imagick is an installed module:

$ php -m | grep imagick

If the response is blank it is not installed.

Communication between tabs or windows

I wrote an article on this on my blog: http://www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web-application .

Using a library I created storageManager you can achieve this as follows:

storageManager.savePermanentData('data', 'key'): //saves permanent data
storageManager.saveSyncedSessionData('data', 'key'); //saves session data to all opened tabs
storageManager.saveSessionData('data', 'key'); //saves session data to current tab only
storageManager.getData('key'); //retrieves data

There are other convenient methods as well to handle other scenarios as well

How to add/update an attribute to an HTML element using JavaScript?

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe element.attributeName = 'value' might work.

Python - Count elements in list

To find count of unique elements of list use the combination of len() and set().

>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4

Using the Underscore module with Node.js

The name _ used by the node.js REPL to hold the previous input. Choose another name.

I'm getting Key error in python

I received this error when I was parsing dict with nested for:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cat:
        print(cats[cat][attr])

Traceback:

Traceback (most recent call last):
      File "<input>", line 3, in <module>
    KeyError: 'K'

Because in second loop should be cats[cat] instead just cat (what is just a key)

So:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cats[cat]:
        print(cats[cat][attr])

Gives

black
10
white
8

Predicate in Java

Adding up to what Micheal has said:

You can use Predicate as follows in filtering collections in java:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);

You don't have permission to access / on this server

Check the apache User and Group setting in the httpd.conf. It should default to apache on AMI/RedHat or www-data on Debian.

grep '^Group\|^User' /etc/httpd/conf/httpd.conf

Then add the apache user to the group setting of your site's root directory.

sudo usermod -a -G <your-site-root-dir-group> apache

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

Does Python have an argc argument?

I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:

[filename] = sys.argv[1:]

in_file = open(filename)   # Don't need the "r"

This will assign the one argument to filename and raise an exception if there isn't exactly one argument.

T-SQL CASE Clause: How to specify WHEN NULL

CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

Message 'src refspec master does not match any' when pushing commits in Git

I had the same problem. I did it by the following steps:

1. git commit -m 'message'
2. git config --global user.email "your mail"
3. git config --global user.name "name"
4. git commit -m 'message'
5. git push -u origin master

Show loading image while $.ajax is performed

  1. Create a load element for e.g. an element with id = example_load.
  2. Hide it by default by adding style="display:none;".
  3. Now show it using jquery show element function just above your ajax.

    $('#example_load').show(); $.ajax({ type: "POST", data: {}, url: '/url', success: function(){ // Now hide the load element $('#example_load').hide(); } });

CSS change button style after click

It is possible to do with CSS only by selecting active and focus pseudo element of the button.

button:active{
    background:olive;
}

button:focus{
    background:olive;
}

See codepen: http://codepen.io/fennefoss/pen/Bpqdqx

You could also write a simple jQuery click function which changes the background color.

HTML:

<button class="js-click">Click me!</button>

CSS:

button {
  background: none;
}

JavaScript:

  $( ".js-click" ).click(function() {
    $( ".js-click" ).css('background', 'green');
  });

Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

Redirect in Spring MVC

i know this is late , but you should try redirecting to a path and not to a file ha ha

Quick Sort Vs Merge Sort

Quick sort is typically faster than merge sort when the data is stored in memory. However, when the data set is huge and is stored on external devices such as a hard drive, merge sort is the clear winner in terms of speed. It minimizes the expensive reads of the external drive and also lends itself well to parallel computing.

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

How can I check if a string represents an int, without using try/except?

def is_int_or_float(x):
    try:    
        if int(float(x)):
            if float(x).is_integer():  return 'int'
            else:                      return 'float'
    except ValueError:  return False


for  i  in ['*', '-1', '01', '1.23', '+0011.002', ]:
    print(i, is_int_or_float(i))

# * False
# -1 int
# 01 int
# 1.23 float
# +0011.002 float

Initializing a two dimensional std::vector

Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'

Write it as

std::vector<vector<int>> arr(n, vector<int>(m,VAL));

This VAL can be a integer type variable or constant such as 100

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

Drop rows with all zeros in pandas data frame

Replace the zeros with nan and then drop the rows with all entries as nan. After that replace nan with zeros.

import numpy as np
df = df.replace(0, np.nan)
df = df.dropna(how='all', axis=0)
df = df.replace(np.nan, 0)

Java Security: Illegal key size or default parameters?

There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:

Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.

Get the current user, within an ApiController action, without passing the userID as a parameter

In .Net Core use User.Identity.Name to get the Name claim of the user.

Returning a value from callback function in Node.js

I am facing small trouble in returning a value from callback function in Node.js

This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.

Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        // call the function that needs the value
        callback(finalData);
        // we are done
        return;
    });
}

Line callback(finalData); is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)

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

// Enable scrolling based on content height self.tableView.scrollEnabled = table.contentSize.height > table.frame.size.height;

npm - how to show the latest version of a package

The npm view <pkg> version prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.

The solution is to list all versions and fetch the last one by version number

$ npm view <pkg> versions --json | jq -r '.[-1]'

Or with awk instead of jq:

$ npm view <pkg> --json  | awk '/"$/{print gensub("[ \"]", "", "G")}'

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

calling parent class method from child class object in java

Say the hierarchy is C->B->A with A being the base class.

I think there's more to fixing this than renaming a method. That will work but is that a fix?

One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.

C# with MySQL INSERT parameters

comm.Parameters.Add("person", "Myname");

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

Remove duplicates from a list of objects based on property in Java 8

Try this code:

Collection<Employee> nonDuplicatedEmployees = employees.stream()
   .<Map<Integer, Employee>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll)
   .values();

How to pass form input value to php function

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

Filter object properties by key in ES6

If you are OK with using ES6 syntax, I find that the cleanest way to do this, as noted here and here is:

const data = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const { item2, ...newData } = data;

Now, newData contains:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

Or, if you have the key stored as a string:

const key = 'item2';
const { [key]: _, ...newData } = data;

In the latter case, [key] is converted to item2 but since you are using a const assignment, you need to specify a name for the assignment. _ represents a throw away value.

More generally:

const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...

Not only does this reduce your operation to a one-liner but it also doesn't require you to know what the other keys are (those that you want to preserve).

A simple utility function would look like this:

function removePropFromObject(obj, prop) {
  const { [prop]: _, ...rest } = obj
  return { ...rest }
}

Python Sets vs Lists

Set wins due to near instant 'contains' checks: https://en.wikipedia.org/wiki/Hash_table

List implementation: usually an array, low level close to the metal good for iteration and random access by element index.

Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list could be faster if you have very few elements (< 5), the larger element count the better the set will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !

NOTE: If the list is already sorted, searching the list could be quite fast on small lists, but with more data a set is faster for contains checks.

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

In order to apply all of these great comments to my daily coding, for continuity between all my applications, I have decided to use the following in both my jquery and jquery mobile code.

window.onresize = function (event) {
  applyOrientation();
}

function applyOrientation() {
  if (window.innerHeight > window.innerWidth) {
    alert("You are now in portrait");
  } else {
    alert("You are now in landscape");
  }
}

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

How can I rollback an UPDATE query in SQL server 2005?

begin transaction

// execute SQL code here

rollback transaction

If you've already executed the query and want to roll it back, unfortunately your only real option is to restore a database backup. If you're using Full backups, then you should be able to restore the database to a specific point in time.

How can I start PostgreSQL on Windows?

I found using

net start postgres_service_name

the only reliable way to operate Postgres on Windows

ComboBox.SelectedText doesn't give me the SelectedText

All of the previous answers explain what the OP 'should' do. I am explaining what the .SelectedText property is.

The .SelectedText property is not the text in the combobox. It is the text that is highlighted. It is the same as .SelectedText property for a textbox.

The following picture shows that the .SelectedText property would be equal to "ort".

enter image description here

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

Circle line-segment collision detection algorithm?

Here's an implementation in Javascript. My approach is to first convert the line segment into an infinite line then find the intersection point(s). From there I check if the point(s) found are on the line segment. The code is well documented, you should be able to follow along.

You can try out the code here on this live demo. The code was taken from my algorithms repo.

enter image description here

// Small epsilon value
var EPS = 0.0000001;

// point (x, y)
function Point(x, y) {
  this.x = x;
  this.y = y;
}

// Circle with center at (x,y) and radius r
function Circle(x, y, r) {
  this.x = x;
  this.y = y;
  this.r = r;
}

// A line segment (x1, y1), (x2, y2)
function LineSegment(x1, y1, x2, y2) {
  var d = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
  if (d < EPS) throw 'A point is not a line segment';
  this.x1 = x1; this.y1 = y1;
  this.x2 = x2; this.y2 = y2;
}

// An infinite line defined as: ax + by = c
function Line(a, b, c) {
  this.a = a; this.b = b; this.c = c;
  // Normalize line for good measure
  if (Math.abs(b) < EPS) {
    c /= a; a = 1; b = 0;
  } else { 
    a = (Math.abs(a) < EPS) ? 0 : a / b;
    c /= b; b = 1; 
  }
}

// Given a line in standard form: ax + by = c and a circle with 
// a center at (x,y) with radius r this method finds the intersection
// of the line and the circle (if any). 
function circleLineIntersection(circle, line) {

  var a = line.a, b = line.b, c = line.c;
  var x = circle.x, y = circle.y, r = circle.r;

  // Solve for the variable x with the formulas: ax + by = c (equation of line)
  // and (x-X)^2 + (y-Y)^2 = r^2 (equation of circle where X,Y are known) and expand to obtain quadratic:
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  // Then use quadratic formula X = (-b +- sqrt(a^2 - 4ac))/2a to find the 
  // roots of the equation (if they exist) and this will tell us the intersection points

  // In general a quadratic is written as: Ax^2 + Bx + C = 0
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  var A = a*a + b*b;
  var B = 2*a*b*y - 2*a*c - 2*b*b*x;
  var C = b*b*x*x + b*b*y*y - 2*b*c*y + c*c - b*b*r*r;

  // Use quadratic formula x = (-b +- sqrt(a^2 - 4ac))/2a to find the 
  // roots of the equation (if they exist).

  var D = B*B - 4*A*C;
  var x1,y1,x2,y2;

  // Handle vertical line case with b = 0
  if (Math.abs(b) < EPS) {

    // Line equation is ax + by = c, but b = 0, so x = c/a
    x1 = c/a;

    // No intersection
    if (Math.abs(x-x1) > r) return [];

    // Vertical line is tangent to circle
    if (Math.abs((x1-r)-x) < EPS || Math.abs((x1+r)-x) < EPS)
      return [new Point(x1, y)];

    var dx = Math.abs(x1 - x);
    var dy = Math.sqrt(r*r-dx*dx);

    // Vertical line cuts through circle
    return [
      new Point(x1,y+dy),
      new Point(x1,y-dy)
    ];

  // Line is tangent to circle
  } else if (Math.abs(D) < EPS) {

    x1 = -B/(2*A);
    y1 = (c - a*x1)/b;

    return [new Point(x1,y1)];

  // No intersection
  } else if (D < 0) {

    return [];

  } else {

    D = Math.sqrt(D);

    x1 = (-B+D)/(2*A);
    y1 = (c - a*x1)/b;

    x2 = (-B-D)/(2*A);
    y2 = (c - a*x2)/b;

    return [
      new Point(x1, y1),
      new Point(x2, y2)
    ];

  }

}

// Converts a line segment to a line in general form
function segmentToGeneralForm(x1,y1,x2,y2) {
  var a = y1 - y2;
  var b = x2 - x1;
  var c = x2*y1 - x1*y2;
  return new Line(a,b,c);
}

// Checks if a point 'pt' is inside the rect defined by (x1,y1), (x2,y2)
function pointInRectangle(pt,x1,y1,x2,y2) {
  var x = Math.min(x1,x2), X = Math.max(x1,x2);
  var y = Math.min(y1,y2), Y = Math.max(y1,y2);
  return x - EPS <= pt.x && pt.x <= X + EPS &&
         y - EPS <= pt.y && pt.y <= Y + EPS;
}

// Finds the intersection(s) of a line segment and a circle
function lineSegmentCircleIntersection(segment, circle) {

  var x1 = segment.x1, y1 = segment.y1, x2 = segment.x2, y2 = segment.y2;
  var line = segmentToGeneralForm(x1,y1,x2,y2);
  var pts = circleLineIntersection(circle, line);

  // No intersection
  if (pts.length === 0) return [];

  var pt1 = pts[0];
  var includePt1 = pointInRectangle(pt1,x1,y1,x2,y2);

  // Check for unique intersection
  if (pts.length === 1) {
    if (includePt1) return [pt1];
    return [];
  }

  var pt2 = pts[1];
  var includePt2 = pointInRectangle(pt2,x1,y1,x2,y2);

  // Check for remaining intersections
  if (includePt1 && includePt2) return [pt1, pt2];
  if (includePt1) return [pt1];
  if (includePt2) return [pt2];
  return [];

}

How to jump to top of browser page

You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.

although as you are using modals, I assume you don't care about being js free. ;)

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

Getting return value from stored procedure in C#

Suppose you need to pass Username and Password to Stored Procedure and know whether login is successful or not and check if any error has occurred in Stored Procedure.

public bool IsLoginSuccess(string userName, string password)
{
    try
    {
        SqlConnection SQLCon = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
        SqlCommand sqlcomm = new SqlCommand();
        SQLCon.Open();
        sqlcomm.CommandType = CommandType.StoredProcedure;
        sqlcomm.CommandText = "spLoginCheck"; // Stored Procedure name
        sqlcomm.Parameters.AddWithValue("@Username", userName); // Input parameters
        sqlcomm.Parameters.AddWithValue("@Password", password); // Input parameters

        // Your output parameter in Stored Procedure           
        var returnParam1 = new SqlParameter
        {
            ParameterName = "@LoginStatus",
            Direction = ParameterDirection.Output,
            Size = 1                    
        };
        sqlcomm.Parameters.Add(returnParam1);

        // Your output parameter in Stored Procedure  
        var returnParam2 = new SqlParameter
        {
            ParameterName = "@Error",
            Direction = ParameterDirection.Output,
            Size = 1000                    
        };

        sqlcomm.Parameters.Add(returnParam2);

        sqlcomm.ExecuteNonQuery(); 
        string error = (string)sqlcomm.Parameters["@Error"].Value;
        string retunvalue = (string)sqlcomm.Parameters["@LoginStatus"].Value;                    
    }
    catch (Exception ex)
    {

    }
    return false;
}

Your connection string in Web.Config

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Databasename;User id=yourusername;Password=yourpassword"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

And here is the Stored Procedure for reference

CREATE PROCEDURE spLoginCheck
    @Username Varchar(100),
    @Password Varchar(100) ,
    @LoginStatus char(1) = null output,
    @Error Varchar(1000) output 
AS
BEGIN

    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN

            SET @Error = 'None'
            SET @LoginStatus = ''

            IF EXISTS(SELECT TOP 1 * FROM EMP_MASTER WHERE EMPNAME=@Username AND EMPPASSWORD=@Password)
            BEGIN
                SET @LoginStatus='Y'
            END

            ELSE
            BEGIN
                SET @LoginStatus='N'
            END

        END
    END TRY

    BEGIN CATCH
        BEGIN           
            SET @Error = ERROR_MESSAGE()
        END
    END CATCH
END
GO

A potentially dangerous Request.Path value was detected from the client (*)

Try to set web project's server propery as Local IIS if it is IIS Express. Be sure if project url is right and create virual directory.

How does MySQL process ORDER BY and LIMIT in a query?

LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

What's the meaning of exception code "EXC_I386_GPFLT"?

You can often get information from the header files. For example:

$ cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk
$ find usr -name \*.h -exec fgrep -l EXC_I386_GPFLT {} \;
usr/include/mach/i386/exception.h
^C
$ more usr/include/mach/i386/exception.h
....
#define EXC_I386_GPFLT          13      /* general protection fault     */

OK, so it's a general protection fault (as its name suggests anyway). Googling "i386 general protection fault" yields many hits, but this looks interesting:

Memory protection is also implemented using the segment descriptors. First, the processor checks whether a value loaded in a segment register references a valid descriptor. Then it checks that every linear address calculated actually lies within the segment. Also, the type of access (read, write, or execute) is checked against the information in the segment descriptor. Whenever one of these checks fails, exception (interrupt) 13 (hex 0D) is raised. This exception is called a General Protection Fault (GPF).

That 13 matches what we saw in the header files, so it looks like the same thing. However from the application programmer's point-of-view, it just means we're referencing memory we shouldn't be, and it's doesn't really matter how it's implemented on the hardware.

How to set min-font-size in CSS

Judging by your above comment, you're OK doing this with jQuery — here goes:

// for every element in the body tag
$("*", "body").each(function() {
  // parse out its computed font size, and see if it is less than 12
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    // if so, then manually give it a CSS property of 12px
    $(this).css("font-size", "12px")
});

A cleaner way to do this might be to have a "min-font" class in your CSS that sets font-size: 12px, and just add the class instead:

$("*", "body").each(function() {
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    $(this).addClass("min-font")
});

Select rows from a data frame based on values in a vector

Have a look at ?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

You could also use ?is.element:

dt[is.element(dt$fct, vc),]

Get the ID of a drawable in ImageView

A simple solution might be to just store the drawable id in a temporary variable. I'm not sure how practical this would be for your situation but it's definitely a quick fix.

Detect when browser receives file download

One possible solution uses JavaScript on the client.

The client algorithm:

  1. Generate a random unique token.
  2. Submit the download request, and include the token in a GET/POST field.
  3. Show the "waiting" indicator.
  4. Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide).
  5. If the cookie exists, and its value matches the token, hide the "waiting" indicator.

The server algorithm:

  1. Look for the GET/POST field in the request.
  2. If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value.

Client source code (JavaScript):

function getCookie( name ) {
  var parts = document.cookie.split(name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

function expireCookie( cName ) {
    document.cookie = 
        encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString();
}

function setCursor( docStyle, buttonStyle ) {
    document.getElementById( "doc" ).style.cursor = docStyle;
    document.getElementById( "button-id" ).style.cursor = buttonStyle;
}

function setFormToken() {
    var downloadToken = new Date().getTime();
    document.getElementById( "downloadToken" ).value = downloadToken;
    return downloadToken;
}

var downloadTimer;
var attempts = 30;

// Prevents double-submits by waiting for a cookie from the server.
function blockResubmit() {
    var downloadToken = setFormToken();
    setCursor( "wait", "wait" );

    downloadTimer = window.setInterval( function() {
        var token = getCookie( "downloadToken" );

        if( (token == downloadToken) || (attempts == 0) ) {
            unblockSubmit();
        }

        attempts--;
    }, 1000 );
}

function unblockSubmit() {
  setCursor( "auto", "pointer" );
  window.clearInterval( downloadTimer );
  expireCookie( "downloadToken" );
  attempts = 30;
}

Example server code (PHP):

$TOKEN = "downloadToken";

// Sets a cookie so that when the download begins the browser can
// unblock the submit button (thus helping to prevent multiple clicks).
// The false parameter allows the cookie to be exposed to JavaScript.
$this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false );

$result = $this->sendFile();

Where:

public function setCookieToken(
    $cookieName, $cookieValue, $httpOnly = true, $secure = false ) {

    // See: http://stackoverflow.com/a/1459794/59087
    // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
    // See: http://stackoverflow.com/a/3290474/59087
    setcookie(
        $cookieName,
        $cookieValue,
        2147483647,            // expires January 1, 2038
        "/",                   // your path
        $_SERVER["HTTP_HOST"], // your domain
        $secure,               // Use true over HTTPS
        $httpOnly              // Set true for $AUTH_COOKIE_NAME
    );
}

Adding custom radio buttons in android

I have updated accepted answer and removed unnecessary things.

I have created XML for following image.

enter image description here

Your XML code for RadioButton will be:

<RadioGroup
        android:id="@+id/daily_weekly_button_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="@dimen/_80sdp"
            android:gravity="center"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_flat_selector"
            android:button="@android:color/transparent"
            android:checked="true"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingTop="@dimen/_3sdp"
            android:paddingRight="@dimen/_16sdp"
            android:paddingBottom="@dimen/_3sdp"
            android:text="Daily"
            android:textColor="@color/radio_flat_text_selector" />

        <RadioButton
            android:id="@+id/radio1"
            android:gravity="center"
            android:layout_width="@dimen/_80sdp"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_flat_selector"
            android:button="@android:color/transparent"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingTop="@dimen/_3sdp"
            android:paddingRight="@dimen/_16sdp"
            android:paddingBottom="@dimen/_3sdp"
            android:text="Weekly"
            android:textColor="@color/radio_flat_text_selector" />

</RadioGroup>

radio_flat_selector.xml for background selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/radio_flat_selected" android:state_checked="true" />
    <item android:drawable="@drawable/radio_flat_regular" />
</selector>

radio_flat_selected.xml for selected button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="1dp"
        />
    <solid android:color="@color/colorAccent" />
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />
</shape>

radio_flat_regular.xml for regular selector:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="1dp" />
    <solid android:color="#fff" />
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />
</shape>

All the above 3 file code will be in drawable/ folder.

Now we also need Text Color Selector to change color of text accordingly.

radio_flat_text_selector.xml for text color selector

(Use color/ folder for this file.)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorAccent" android:state_checked="false" />
    <item android:color="@color/colorWhite" android:state_checked="true" />
</selector>

Note: I refereed many answers for this type of solution but didn't found good solution so I make it.

Hope it will be helpful to you.

Thanks.

How do I know which version of Javascript I'm using?

Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.

  • Most browsers are on 1.5 (though they have features of later versions)
  • Mozilla progresses with every dot release (they maintain the standard so that's not surprising)
  • Firefox 4 is on JavaScript 1.8.5
  • The other big off-the-beaten-path one is IE9 - it implements ECMAScript 5, but doesn't implement all the features of JavaScript 1.8.5 (not sure what they're calling this version of JScript, engine codenamed Chakra, yet).

CodeIgniter - return only one row?

$this->db->get()->row()->campaign_id;

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Force browser to clear cache

Look into the cache-control and the expires META Tag.

<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT">

Another common practices is to append constantly-changing strings to the end of the requested files. For instance:

<script type="text/javascript" src="main.js?v=12392823"></script>

segmentation fault : 11

Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.

Writing that much data to a file is going to take a while.

You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).

You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?

You should also write a function to do the calculation; you could use an inline function in C99 or later (or C++). The repetition in the code is excruciating to behold.

You should also use C99 notation for main(), with the explicit return type (and preferably void for the argument list when you are not using argc or argv):

int main(void)

Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 }; (thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static in front of the functions, and the main array; file becomes a local to main; error check the fopen(), etc.).

I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.

#include <stdio.h>

#define   lambda   2.0
#define   g        1.0
#define   F0       1.0
#define   h        0.1
#define   e        0.00001

enum { ROWS = 1000, COLS = 10000 };

static double F[ROWS][COLS];

static void Inicio(double D[ROWS][COLS])
{
    for (int i = 399; i < 600; i++) // Magic numbers!!
        D[i][0] = F0;
}

enum { R = ROWS - 1 };

static inline int ko(int k, int n)
{
    int rv = k + n;
    if (rv >= R)
        rv -= R;
    else if (rv < 0)
        rv += R;
    return(rv);
}

static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
    int ks2 = ko(k, -2);
    int ks1 = ko(k, -1);
    int kp1 = ko(k, +1);
    int kp2 = ko(k, +2);

    A[k][i] = A[k][i-1]
            + e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
            + 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
            + e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}

static void Iteration(double A[ROWS][COLS])
{
    for (int i = 1; i < COLS; i++)
    {
        for (int k = 0; k < R; k++)
            calculate_value(i, k, A);
        A[999][i] = A[0][i];
    }
}

int main(void)
{
    FILE *file = fopen("P2.txt","wt");
    if (file == 0)
        return(1);
    Inicio(F);
    Iteration(F);
    for (int i = 0; i < COLS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
        }
    }
    fclose(file);
    return(0);
}

This program writes to P2.txt instead of P1.txt. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:

Original   Modified
6.334s      6.367s
6.241s      6.231s
6.315s     10.778s
6.378s      6.320s
6.388s      6.293s
6.285s      6.268s
6.387s     10.954s
6.377s      6.227s
8.888s      6.347s
6.304s      6.286s
6.258s     10.302s
6.975s      6.260s
6.663s      6.847s
6.359s      6.313s
6.344s      6.335s
7.762s      6.533s
6.310s      9.418s
8.972s      6.370s
6.383s      6.357s

However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for loop became:

for (int i = COLS - 1; i < COLS; i++)

the timings were vastly reduced and very much more consistent:

Original    Modified
0.168s      0.165s
0.145s      0.165s
0.165s      0.166s
0.164s      0.163s
0.151s      0.151s
0.148s      0.153s
0.152s      0.171s
0.165s      0.165s
0.173s      0.176s
0.171s      0.165s
0.151s      0.169s

The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.

How to select option in drop down protractorjs e2e tests

This is how i did my selection.

function switchType(typeName) {
     $('.dropdown').element(By.cssContainingText('option', typeName)).click();
};

import .css file into .less file

Try this :

@import "lib.css";

From the Official Documentation :

You can import both css and less files. Only less files import statements are processed, css file import statements are kept as they are. If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:


Source : http://lesscss.org/

Editing hosts file to redirect url?

Make sure to double the entry with an additional "www"-prefix. If you don't addresses like "www.acme.com" will not work!

Uncaught SyntaxError: Unexpected token :

For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn't be found. I just had to provide a reachable path and the problem went away.

Regular expression to match DNS hostname or IP Address?

It's worth noting that there are libraries for most languages that do this for you, often built into the standard library. And those libraries are likely to get updated a lot more often than code that you copied off a Stack Overflow answer four years ago and forgot about. And of course they'll also generally parse the address into some usable form, rather than just giving you a match with a bunch of groups.

For example, detecting and parsing IPv4 in (POSIX) C:

#include <arpa/inet.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  for (int i=1; i!=argc; ++i) {
    struct in_addr addr = {0};
    printf("%s: ", argv[i]);
    if (inet_pton(AF_INET, argv[i], &addr) != 1)
      printf("invalid\n");
    else
      printf("%u\n", addr.s_addr);
  }
  return 0;
}

Obviously, such functions won't work if you're trying to, e.g., find all valid addresses in a chat message—but even there, it may be easier to use a simple but overzealous regex to find potential matches, and then use the library to parse them.

For example, in Python:

>>> import ipaddress
>>> import re
>>> msg = "My address is 192.168.0.42; 192.168.0.420 is not an address"
>>> for maybeip in re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', msg):
...     try:
...         print(ipaddress.ip_address(maybeip))
...     except ValueError:
...         pass

Best practices for catching and re-throwing .NET exceptions

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow":

  • C#'s "throw ex;" gets compiled into MSIL's "throw"
  • C#'s "throw;" - into MSIL "rethrow"!

Basically I can see the reason why "throw ex" overrides the stack trace.

Can an abstract class have a constructor?

Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).

A good example of an abstract class having a constructor is the Calendar class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). GregorianCalendar is an example of a class that extends Calendar.

How to open a link in new tab (chrome) using Selenium WebDriver?

I am trying to do a robot to my little son and just play a Youtube video and than show a robot dancing.

For some reason, commands like CONTROL + T explained above was not working for me and maybe it is not the correct answer but I solved my problem using custom Javascript script like this:

using (var driver = new ChromeDriver())
            {
                var link1 = "https://www.youtube.com/watch?v=0GIgk4yuHOQ";
                //open a music
                driver.Navigate().GoToUrl(link1);
                var link2 = "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/fbe53d6d-c13f-4eec-9bcf-62f19cfab15a/d4m0h4v-9442b1f2-6a49-4818-8f51-5ebe216f043c.gif?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwic3ViIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsImF1ZCI6WyJ1cm46c2VydmljZTpmaWxlLmRvd25sb2FkIl0sIm9iaiI6W1t7InBhdGgiOiIvZi9mYmU1M2Q2ZC1jMTNmLTRlZWMtOWJjZi02MmYxOWNmYWIxNWEvZDRtMGg0di05NDQyYjFmMi02YTQ5LTQ4MTgtOGY1MS01ZWJlMjE2ZjA0M2MuZ2lmIn1dXX0.BTTlingNpBqH5O9dNVienFsArNqkfUc7KXnIgHumrBQ";
                //Dance robot, dance
                driver.ExecuteScript($"window.open('{link2}', '_blank');");
                Thread.Sleep(20000);
            }

Is it possible to pull just one file in Git?

Here is a slightly easier method I just came up with when researching this:

git fetch {remote}
git checkout FETCH_HEAD -- {file}

JSON date to Java date?

Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).

So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX") produces a format that can parse both "2013-03-11T01:38:18.309Z" and "2013-03-11T01:38:18.309+0000" and will give you the same result.

Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.

I actually have more trouble on the JavaScript side to deal with both formats.

Creating a range of dates in Python

I thought I'd throw in my two cents with a simple (and not complete) implementation of a date range:

from datetime import date, timedelta, datetime

class DateRange:
    def __init__(self, start, end, step=timedelta(1)):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        start = self.start
        step = self.step
        end = self.end

        n = int((end - start) / step)
        d = start

        for _ in range(n):
            yield d
            d += step

    def __contains__(self, value):
        return (
            (self.start <= value < self.end) and 
            ((value - self.start) % self.step == timedelta(0))
        )

Python syntax for "if a or b or c but not all of them"

How about:

conditions = [a, b, c]
if any(conditions) and not all(conditions):
   ...

Other variant:

if 1 <= sum(map(bool, conditions)) <= 2:
   ...

How to detect Adblock on my website?

My solution is not specific to a certain ad network and is very lightweight. I've been running it in production for a few years. AdBlock blocks all URLs containing the word "ads" or "prebid". So this is what I did:

I added a small js file to my webroot with the name prebid-ads.js

Update 2020-07-27: you might want to call the file prebid-ads.js or something, because uBlock Origin does not block files with name like ads.js anymore.

This is the only line of code in that file

var canRunAds = true;

Then somewhere in my page:

<html>
  <head>
    <script src="/js/prebid-ads.js"></script>
  </head>
  <body>
    <script>
      if( window.canRunAds === undefined ){
        // adblocker detected, show fallback
        showFallbackImage();
      }
    </script>
  </body>
</html>

Files like ads.js are blocked by at least these adblockers on Chrome:

  • AdBlock
  • Adblock Plus
  • Adblock Pro
  • Ghostery

Update on 2019-02-15:

Added Ghostery in the list above because the extension now also blocks requests to ads.js. Very handy. Does this mean that Ghostery is actually helping us devs to detect the blocking of ads with their extension?

Does not work with:

Privacy Badger

Log4j output not displayed in Eclipse console

Check for log4j configuration files in your output (i.e. bin or target/classes) directory or within generated project artifacts (.jar/.war/.ear). If this is on your classpath it gets picked up by log4j.

Delete duplicate elements from an array

As elements are yet ordered, you don't have to build a map, there's a fast solution :

var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
   if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}

If your array weren't sorted, you would use a map :

var newarr = (function(arr){
  var m = {}, newarr = []
  for (var i=0; i<arr.length; i++) {
    var v = arr[i];
    if (!m[v]) {
      newarr.push(v);
      m[v]=true;
    }
  }
  return newarr;
})(arr);

Note that this is, by far, much faster than the accepted answer.

Why is it that "No HTTP resource was found that matches the request URI" here?

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

How to detect if a string contains at least a number?

The simplest method is to use LIKE:

SELECT CASE WHEN 'FDAJLK' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- False
SELECT CASE WHEN 'FDAJ1K' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- True

How to use the ProGuard in Android Studio?

Here is Some of Most Common Proguard Rules that you need to add in proguard-rules.pro file in Android Sutdio.

ButterKnife

 -keep class butterknife.** { *; }
 -dontwarn butterknife.internal.**
 -keep class **$$ViewBinder { *; }
 -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
  }
 -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
  }

Retrofit

 -dontwarn retrofit.**
 -keep class retrofit.** { *; }
 -keepattributes Signature
 -keepattributes Exceptions

OkHttp3

 -keepattributes Signature
 -keepattributes *Annotation*
 -keep class okhttp3.** { *; }
 -keep interface okhttp3.** { *; }
 -dontwarn okhttp3.** 
 -keep class sun.misc.Unsafe { *; }
 -dontwarn java.nio.file.*
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 

Gson

 -keep class sun.misc.Unsafe { *; }
 -keep class com.google.gson.stream.** { *; }

Code obfuscation

-keepclassmembers class com.yourname.models** { <fields>; }

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

set -e
fail () {
    touch .failure
}
expect () {
    wait
    if [ -f .failure ]; then
        rm -f .failure
        exit 1
    fi
}

sleep 2 || fail &
sleep 2 && false || fail &
sleep 2 || fail
expect

The set -e at top makes your script stop on failure.

expect will return 1 if any subjob failed.

How to write :hover condition for a:before and a:after?

BoltClock's answer is correct. The only thing I want to append is that if you want to only select the pseudo element, put in a span.

For example:

<li><span data-icon='u'></span> List Element </li>

instead of:

<li> data-icon='u' List Element</li>

This way you can simply say

ul [data-icon]:hover::before {color: #f7f7f7;}

which will only highlight the pseudo element, not the entire li element

Is using 'var' to declare variables optional?

They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.

This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.

IndexError: tuple index out of range ----- Python

Probably one of the indexes is wrong, either the inner one or the outer one.

I suspect you mean to say [0] where you say [1] and [1] where you say [2]. Indexes are 0-based in Python.

What is the difference between UNION and UNION ALL?

Not sure that it matters which database

UNION and UNION ALL should work on all SQL Servers.

You should avoid of unnecessary UNIONs they are huge performance leak. As a rule of thumb use UNION ALL if you are not sure which to use.

Unix shell script find out which directory the script file resides?

The best answer for this question was answered here:
Getting the source directory of a Bash script from within

And it is:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

One-liner which will give you the full directory name of the script no matter where it is being called from.

To understand how it works you can execute the following script:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  TARGET="$(readlink "$SOURCE")"
  if [[ $TARGET == /* ]]; then
    echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
    SOURCE="$TARGET"
  else
    DIR="$( dirname "$SOURCE" )"
    echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
    SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
  fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
  echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"

Jquery, Clear / Empty all contents of tbody element?

jQuery:

$("#tbodyid").empty();

HTML:

<table>
    <tbody id="tbodyid">
        <tr>
            <td>something</td>
        </tr>
    </tbody>
</table>

Works for me
http://jsfiddle.net/mbsh3/

How to display image from URL on Android

You can try with Picasso, it's really nice and easy. Don't forget to add the permissions in the manifest.

Picasso.with(context)
                     .load("http://ImageURL")
                     .resize(width,height)
                     .into(imageView );

You can also take a look at a tutorial here : Youtube / Github

How do I convert uint to int in C#?

Take note of the checked and unchecked keywords.

It matters if you want the result truncated to the int or an exception raised if the result doesnt fit in signed 32 bits. The default is unchecked.

Object Dump JavaScript

For Chrome/Chromium

console.log(myObj)

or it's equivalent

console.debug(myObj)

Disable developer mode extensions pop up in Chrome

1) Wait for the popup balloon to appear.

2) Open a new tab.

3) Close the a new tab. The popup will be gone from the original tab.

A small Chrome extension can automate these steps:

manifest.json

{
  "name": "Open and close tab",
  "description": "After Chrome starts, open and close a new tab.",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["tabs"],
  "background": {
    "scripts": ["background.js"], 
    "persistent": false
  }
}

background.js

// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {

  // Execute the inner function after a few seconds
  setTimeout(function() {

    // Open new tab
    chrome.tabs.create({url: "about:blank"});

    // Get tab ID of newly opened tab, then close the tab
    chrome.tabs.query({'currentWindow': true}, function(tabs) {
      var newTabId = tabs[1].id;
      chrome.tabs.remove(newTabId);
    });

  }, 5000);

});

With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.

Change header text of columns in a GridView

Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.

ASPX:

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
    <Columns>
        <asp:BoundField HeaderText="Date" DataField="CreatedDate" />
    </Columns>
</asp:GridView>

CS:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
            {
                e.Row.Cells[i].Text = "Created Date";
            }
        }
    }
}

How to redirect to another page using AngularJS?

Using location.href="./index.html"

or create scope $window

and using $window.location.href="./index.html"

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

To state the obvious, the cup represents outerScopeVar.

Asynchronous functions be like...

asynchronous call for coffee

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Change link color of the current page with CSS

It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :target pseudo selector, which relies on #someid appearing in the addressbar.

<!DOCTYPE>
<html>
<head>
    <title>Some Title</title>
<style>
:target {
    background-color: yellow;
}
</style>
</head>
<body>
<ul>
    <li><a id="news" href="news.html#news">News</a></li>
    <li><a id="games" href="games.html#games">Games</a></li>
    <li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>

There are a couple of restrictions:

  • If the page wasn't navigated to using one of these links it won't be coloured;
  • The ids need to occur at the top of the page otherwise the page will jump down a bit when visited.

As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.


Other in-page links (bookmarks) will also cause the colour to be lost.

Java - How to create a custom dialog box?

If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.

Example:

JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
        new JLabel("First"),
        firstName,
        new JLabel("Last"),
        lastName,
        new JLabel("Password"),
        password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    System.out.println("You entered " +
            firstName.getText() + ", " +
            lastName.getText() + ", " +
            password.getText());
} else {
    System.out.println("User canceled / closed the dialog, result = " + result);
}

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

jQuery - Sticky header that shrinks when scrolling down

http://callmenick.com/2014/02/18/create-an-animated-resizing-header-on-scroll/

This link has a great tutorial with source code that you can play with, showing how to make elements within the header smaller as well as the header itself.

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

Hidden features of Python

Manipulating sys.modules

You can manipulate the modules cache directly, making modules available or unavailable as you wish:

>>> import sys
>>> import ham
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named ham

# Make the 'ham' module available -- as a non-module object even!
>>> sys.modules['ham'] = 'ham, eggs, saussages and spam.'
>>> import ham
>>> ham
'ham, eggs, saussages and spam.'

# Now remove it again.
>>> sys.modules['ham'] = None
>>> import ham
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named ham

This works even for modules that are available, and to some extent for modules that already are imported:

>>> import os
# Stop future imports of 'os'.
>>> sys.modules['os'] = None
>>> import os
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named os
# Our old imported module is still available.
>>> os
<module 'os' from '/usr/lib/python2.5/os.pyc'>

As the last line shows, changing sys.modules only affects future import statements, not past ones, so if you want to affect other modules it's important to make these changes before you give them a chance to try and import the modules -- so before you import them, typically. None is a special value in sys.modules, used for negative caching (indicating the module was not found the first time, so there's no point in looking again.) Any other value will be the result of the import operation -- even when it is not a module object. You can use this to replace modules with objects that behave exactly like you want. Deleting the entry from sys.modules entirely causes the next import to do a normal search for the module, even if it was already imported before.

how to open .mat file without using MATLAB?

There's a really nice easy way to do this in Macintosh OsX. A fellow has made a quicklook plugin (command-space) that renders .mat formats so you can view the variables inside etc. Quite useful! https://github.com/jaketmp/matlab-quicklook/releases

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

I got the same same error.

I was using gmail account and Google's SMTP server to send emails. The problem was due to SMTP server refusing to authorize as it considered my web host (through whom I sent email) as an intruder.

I followed Google's process to identify my web host as an valid entity to send email through my account and problem was solved.

How do I auto-submit an upload form when a file is selected?

<form action="http://example.com">
    <input type="file" onchange="Submit()" />
</form>

 <script>
     // it will submit form 0 or you have to select particular form
     document.getElementsByTagName("form")[0].submit();       
 </script>

How to install a node.js module without using npm?

Step-by-step:

  • let's say you are working on a project use-gulp which uses(requires) node_modules like gulp and gulp-util.
  • Now you want to make some modifications to gulp-util lib and test it locally with your use-gulp project...
  • Fork gulp-util project on github\bitbucket etc.
  • Switch to your project: cd use-gulp/node_modules
  • Clone gulp-util as gulp-util-dev : git clone https://.../gulp-util.git gulp-util-dev
  • Run npm install to ensure dependencies of gulp-util-dev are available.
  • Now you have a mirror of gulp-util as gulp-util-dev. In your use-gulp project, you can now replace: require('gulp-util')...; call with : require('gulp-util-dev') to test your changes you made to gulp-util-dev

What does the term "canonical form" or "canonical representation" in Java mean?

I believe there are two related uses of canonical: forms and instances.

A canonical form means that values of a particular type of resource can be described or represented in multiple ways, and one of those ways is chosen as the favored canonical form. (That form is canonized, like books that made it into the bible, and the other forms are not.) A classic example of a canonical form is paths in a hierarchical file system, where a single file can be referenced in a number of ways:

myFile.txt                                   # in current working dir
../conf/myFile.txt                           # relative to the CWD
/apps/tomcat/conf/myFile.txt                 # absolute path using symbolic links
/u1/local/apps/tomcat-5.5.1/conf/myFile.txt  # absolute path with no symlinks

The classic definition of the canonical representation of that file would be the last path. With local or relative paths you cannot globally identify the resource without contextual information. With absolute paths you can identify the resource, but cannot tell if two paths refer to the same entity. With two or more paths converted to their canonical forms, you can do all the above, plus determine if two resources are the same or not, if that is important to your application (solve the aliasing problem).

Note that the canonical form of a resource is not a quality of that particular form itself; there can be multiple possible canonical forms for a given type like file paths (say, lexicographically first of all possible absolute paths). One form is just selected as the canonical form for a particular application reason, or maybe arbitrarily so that everyone speaks the same language.

Forcing objects into their canonical instances is the same basic idea, but instead of determining one "best" representation of a resource, it arbitrarily chooses one instance of a class of instances with the same "content" as the canonical reference, then converts all references to equivalent objects to use the one canonical instance.

This can be used as a technique for optimizing both time and space. If there are multiple instances of equivalent objects in an application, then by forcing them all to be resolved as the single canonical instance of a particular value, you can eliminate all but one of each value, saving space and possibly time since you can now compare those values with reference identity (==) as opposed to object equivalence (equals() method).

A classic example of optimizing performance with canonical instances is collapsing strings with the same content. Calling String.intern() on two strings with the same character sequence is guaranteed to return the same canonical String object for that text. If you pass all your strings through that canonicalizer, you know equivalent strings are actually identical object references, i.e., aliases

The enum types in Java 5.0+ force all instances of a particular enum value to use the same canonical instance within a VM, even if the value is serialized and deserialized. That is why you can use if (day == Days.SUNDAY) with impunity in java if Days is an enum type. Doing this for your own classes is certainly possible, but takes care. Read Effective Java by Josh Bloch for details and advice.

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Why is the Java main method static?

Because otherwise, it would need an instance of the object to be executed. But it must be called from scratch, without constructing the object first, since it is usually the task of the main() function (bootstrap), to parse the arguments and construct the object, usually by using these arguments/program parameters.

python: how to identify if a variable is an array or a scalar

You can check data type of variable.

N = [2,3,5]
P = 5
type(P)

It will give you out put as data type of P.

<type 'int'>

So that you can differentiate that it is an integer or an array.

Functional, Declarative, and Imperative Programming

imperative - expressions describe sequence of actions to perform (associative)

declarative - expressions are declarations that contribute to behavior of program (associative, commutative, idempotent, monotonic)

functional - expressions have value as only effect; semantics support equational reasoning

Giving graphs a subtitle in matplotlib

As mentioned here, uou can use matplotlib.pyplot.text objects in order to achieve the same result:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)

How do I run a shell script without using "sh" or "bash" commands?

In this example the file will be called myShell

First of all we will need to make this file we can just start off by typing the following:

sudo nano myShell

Notice we didn't put the .sh extension? That's because when we run it from the terminal we will only need to type myShell in order to run our command!

Now, in nano the top line MUST be #!/bin/bash then you may leave a new line before continuing.

For demonstration I will add a basic Hello World! response

So, I type the following:

echo Hello World!

After that my example should look like this:

#!/bin/bash
echo Hello World!

Now save the file and then run this command:

chmod +x myShell

Now we have made the file executable we can move it to /usr/bin/ by using the following command:

sudo cp myShell /usr/bin/

Congrats! Our command is now done! In the terminal we can type myShell and it should say Hello World!

PHP: Possible to automatically get all POSTed data?

You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

Java Swing - how to show a panel on top of another panel?

JOptionPane.showInternalInputDialog probably does what you want. If not, it would be helpful to understand what it is missing.

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

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

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

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

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

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

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

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