Programs & Examples On #Genetic programming

Genetic programming (GP) is a specialization of evolutionary computation where each individual is a computer program. It is used to optimize a population of computer programs according to a fitness landscape determined by a program's ability to perform a given computational task.

How to embed HTML into IPython output?

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython's docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "?" if item['completed'] else "?",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ? Buy milk
  2. ? Do homework
  3. ? Play video games

static function in C

C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.

checking if a number is divisible by 6 PHP

So you want the next multiple of 6, is that it?

You can divide your number by 6, then ceil it, and multiply it again:

$answer = ceil($foo / 6) * 6;

Laravel 5 route not defined, while it is?

On a side note:

I had the similar issues where many times I get the error Action method not found, but clearly it is define in controller.

The issue is not in controller, but rather how routes.php file is setup

Lets say you have Controller class set as a resource in route.php file

Route::resource('example', 'ExampleController');

then '/example' will have all RESTful Resource listed here: http://laravel.com/docs/5.0/controllers#restful-resource-controllers

but now you want to have some definition in form e.g: 'action'=>'ExampleController@postStore' then you have to change this route (in route.php file) to:

Route::controller('example', 'ExampleController');

How do I clear only a few specific objects from the workspace?

Use the following command

remove(list=c("data_1", "data_2", "data_3"))

trigger click event from angularjs directive

Here is perhaps a different way for you to achieve this. Pass into the directive both the index and the item and let the directive setup the html in a template:

Demo: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

html:

<ul id="thumbnails">
    <li class="thumbnail" ng-repeat="item in items" options='#my-container' itemdata='item' index="$index">

    </li>
  </ul>

js directive:

app.directive('thumbnail', [function() {
  return {
    restrict: 'CA',
    replace: false,
    transclude: false,
    scope: {
        index: '=index',
        item: '=itemdata'
    },
    template: '<a href="#"><img src="{{item.src}}" alt="{{item.alt}}" /></a>',
    link: function(scope, elem, attrs) {
        if (parseInt(scope.index) == 0) {
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        }

        elem.bind('click', function() {
            var src = elem.find('img').attr('src');

            // call your SmoothZoom here
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        });
    }
}
}]);

You probably would be better off adding a ng-click to the image as pointed out in another answer.

Update

The link for the demo was incorrect. It has been updated to: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

Colorizing text in the console with C++

In Windows, you can use any combination of red green and blue on the foreground (text) and the background.

/* you can use these constants
FOREGROUND_BLUE
FOREGROUND_GREEN
FOREGROUND_RED
FOREGROUND_INTENSITY
BACKGROUND_BLUE
BACKGROUND_GREEN
BACKGROUND_RED
BACKGROUND_INTENSITY
*/

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
std::cout << "I'm cyan! Who are you?" << std::endl;

Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes

How to identify numpy types in python?

Old question but I came up with a definitive answer with an example. Can't hurt to keep questions fresh as I had this same problem and didn't find a clear answer. The key is to make sure you have numpy imported, and then run the isinstance bool. While this may seem simple, if you are doing some computations across different data types, this small check can serve as a quick test before your start some numpy vectorized operation.

##################
# important part!
##################

import numpy as np

####################
# toy array for demo
####################

arr = np.asarray(range(1,100,2))

########################
# The instance check
######################## 

isinstance(arr,np.ndarray)

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

How to prevent a dialog from closing when a button is clicked

An alternate solution

I would like to present an alternate answer from a UX perspective.

Why would you want to prevent a dialog from closing when a button is clicked? Presumably it is because you have a custom dialog in which the user hasn't made a choice or hasn't completely filled everything out yet. And if they are not finished, then you shouldn't allow them to click the positive button at all. Just disable it until everything is ready.

The other answers here give lots of tricks for overriding the positive button click. If that were important to do, wouldn't Android have made a convenient method to do it? They didn't.

Instead, the Dialogs design guide shows an example of such a situation. The OK button is disabled until the user makes a choice. No overriding tricks are necessary at all. It is obvious to the user that something still needs to be done before going on.

enter image description here

How to disable the positive button

See the Android documentation for creating a custom dialog layout. It recommends that you place your AlertDialog inside a DialogFragment. Then all you need to do is set listeners on the layout elements to know when to enable or disable the positive button.

The positive button can be disabled like this:

AlertDialog dialog = (AlertDialog) getDialog();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);

Here is an entire working DialogFragment with a disabled positive button such as might be used in the image above.

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

public class MyDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // inflate the custom dialog layout
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.my_dialog_layout, null);

        // add a listener to the radio buttons
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                // enable the positive button after a choice has been made
                AlertDialog dialog = (AlertDialog) getDialog();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            }
        });

        // build the alert dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO: use an interface to pass the user choice back to the activity
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MyDialogFragment.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    @Override
    public void onResume() {
        super.onResume();

        // disable positive button by default
        AlertDialog dialog = (AlertDialog) getDialog();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
}

The custom dialog can be run from an activity like this:

MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getFragmentManager(), "MyTag");

Notes

  • For the sake of brevity, I omitted the communication interface to pass the user choice info back to the activity. The documentation shows how this is done, though.
  • The button is still null in onCreateDialog so I disabled it in onResume. This has the undesireable effect of disabling the it again if the user switches to another app and then comes back without dismissing the dialog. This could be solved by also unselecting any user choices or by calling a Runnable from onCreateDialog to disable the button on the next run loop.

    view.post(new Runnable() {
        @Override
        public void run() {
            AlertDialog dialog = (AlertDialog) getDialog();
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        }
    });
    

Related

SSH library for Java

http://code.google.com/p/connectbot/, Compile src\com\trilead\ssh2 on windows linux or android , it can create Local Port Forwarder or create Dynamic Port Forwarder or other else

jQuery Datepicker close datepicker after selected date

This is my edited version : you just need to add an extra argument "autoClose".

example :

 $('input[name="fieldName"]').datepicker({ autoClose: true});

also you can specify a close callback if you want. :)

replace datepicker.js with this:

!function( $ ) {

// Picker object

var Datepicker = function(element, options , closeCallBack){
    this.element = $(element);
    this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
    this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
    this.closeCallback = closeCallBack || function(){};
    this.picker = $(DPGlobal.template)
                        .appendTo('body')
                        .on({
                            click: $.proxy(this.click, this)//,
                            //mousedown: $.proxy(this.mousedown, this)
                        });
    this.isInput = this.element.is('input');
    this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

    if (this.isInput) {
        this.element.on({
            focus: $.proxy(this.show, this),
            //blur: $.proxy(this.hide, this),
            keyup: $.proxy(this.update, this)
        });
    } else {
        if (this.component){
            this.component.on('click', $.proxy(this.show, this));
        } else {
            this.element.on('click', $.proxy(this.show, this));
        }
    }

    this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
    if (typeof this.minViewMode === 'string') {
        switch (this.minViewMode) {
            case 'months':
                this.minViewMode = 1;
                break;
            case 'years':
                this.minViewMode = 2;
                break;
            default:
                this.minViewMode = 0;
                break;
        }
    }
    this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
    if (typeof this.viewMode === 'string') {
        switch (this.viewMode) {
            case 'months':
                this.viewMode = 1;
                break;
            case 'years':
                this.viewMode = 2;
                break;
            default:
                this.viewMode = 0;
                break;
        }
    }
    this.startViewMode = this.viewMode;
    this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
    this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
    this.onRender = options.onRender;
    this.fillDow();
    this.fillMonths();
    this.update();
    this.showMode();
};

Datepicker.prototype = {
    constructor: Datepicker,

    show: function(e) {
        this.picker.show();
        this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
        this.place();
        $(window).on('resize', $.proxy(this.place, this));
        if (e ) {
            e.stopPropagation();
            e.preventDefault();
        }
        if (!this.isInput) {
        }
        var that = this;
        $(document).on('mousedown', function(ev){
            if ($(ev.target).closest('.datepicker').length == 0) {
                that.hide();
            }
        });
        this.element.trigger({
            type: 'show',
            date: this.date
        });
    },

    hide: function(){
        this.picker.hide();
        $(window).off('resize', this.place);
        this.viewMode = this.startViewMode;
        this.showMode();
        if (!this.isInput) {
            $(document).off('mousedown', this.hide);
        }
        //this.set();
        this.element.trigger({
            type: 'hide',
            date: this.date
        });
    },

    set: function() {
        var formated = DPGlobal.formatDate(this.date, this.format);
        if (!this.isInput) {
            if (this.component){
                this.element.find('input').prop('value', formated);
            }
            this.element.data('date', formated);
        } else {
            this.element.prop('value', formated);
        }
    },

    setValue: function(newDate) {
        if (typeof newDate === 'string') {
            this.date = DPGlobal.parseDate(newDate, this.format);
        } else {
            this.date = new Date(newDate);
        }
        this.set();
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    place: function(){
        var offset = this.component ? this.component.offset() : this.element.offset();
        this.picker.css({
            top: offset.top + this.height,
            left: offset.left
        });
    },

    update: function(newDate){
        this.date = DPGlobal.parseDate(
            typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
            this.format
        );
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    fillDow: function(){
        var dowCnt = this.weekStart;
        var html = '<tr>';
        while (dowCnt < this.weekStart + 7) {
            html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
        }
        html += '</tr>';
        this.picker.find('.datepicker-days thead').append(html);
    },

    fillMonths: function(){
        var html = '';
        var i = 0
        while (i < 12) {
            html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
        }
        this.picker.find('.datepicker-months td').append(html);
    },

    fill: function() {
        var d = new Date(this.viewDate),
            year = d.getFullYear(),
            month = d.getMonth(),
            currentDate = this.date.valueOf();
        this.picker.find('.datepicker-days th:eq(1)')
                    .text(DPGlobal.dates.months[month]+' '+year);
        var prevMonth = new Date(year, month-1, 28,0,0,0,0),
            day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
        prevMonth.setDate(day);
        prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
        var nextMonth = new Date(prevMonth);
        nextMonth.setDate(nextMonth.getDate() + 42);
        nextMonth = nextMonth.valueOf();
        var html = [];
        var clsName,
            prevY,
            prevM;
        while(prevMonth.valueOf() < nextMonth) {zs
            if (prevMonth.getDay() === this.weekStart) {
                html.push('<tr>');
            }
            clsName = this.onRender(prevMonth);
            prevY = prevMonth.getFullYear();
            prevM = prevMonth.getMonth();
            if ((prevM < month &&  prevY === year) ||  prevY < year) {
                clsName += ' old';
            } else if ((prevM > month && prevY === year) || prevY > year) {
                clsName += ' new';
            }
            if (prevMonth.valueOf() === currentDate) {
                clsName += ' active';
            }
            html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
            if (prevMonth.getDay() === this.weekEnd) {
                html.push('</tr>');
            }
            prevMonth.setDate(prevMonth.getDate()+1);
        }
        this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
        var currentYear = this.date.getFullYear();

        var months = this.picker.find('.datepicker-months')
                    .find('th:eq(1)')
                        .text(year)
                        .end()
                    .find('span').removeClass('active');
        if (currentYear === year) {
            months.eq(this.date.getMonth()).addClass('active');
        }

        html = '';
        year = parseInt(year/10, 10) * 10;
        var yearCont = this.picker.find('.datepicker-years')
                            .find('th:eq(1)')
                                .text(year + '-' + (year + 9))
                                .end()
                            .find('td');
        year -= 1;
        for (var i = -1; i < 11; i++) {
            html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
            year += 1;
        }
        yearCont.html(html);
    },

    click: function(e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('span, td, th');
        if (target.length === 1) {
            switch(target[0].nodeName.toLowerCase()) {
                case 'th':
                    switch(target[0].className) {
                        case 'switch':
                            this.showMode(1);
                            break;
                        case 'prev':
                        case 'next':
                            this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                this.viewDate,
                                this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
                                DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                            );
                            this.fill();
                            this.set();
                            break;
                    }
                    break;
                case 'span':
                    if (target.is('.month')) {
                        var month = target.parent().find('span').index(target);
                        this.viewDate.setMonth(month);
                    } else {
                        var year = parseInt(target.text(), 10)||0;
                        this.viewDate.setFullYear(year);
                    }
                    if (this.viewMode !== 0) {
                        this.date = new Date(this.viewDate);
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                    }
                    this.showMode(-1);
                    this.fill();
                    this.set();
                    break;
                case 'td':
                    if (target.is('.day') && !target.is('.disabled')){
                        var day = parseInt(target.text(), 10)||1;
                        var month = this.viewDate.getMonth();
                        if (target.is('.old')) {
                            month -= 1;
                        } else if (target.is('.new')) {
                            month += 1;
                        }
                        var year = this.viewDate.getFullYear();
                        this.date = new Date(year, month, day,0,0,0,0);
                        this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                        this.fill();
                        this.set();
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                        if(this.autoClose === true){
                            this.hide();
                            this.closeCallback();
                        }

                    }
                    break;
            }
        }
    },

    mousedown: function(e){
        e.stopPropagation();
        e.preventDefault();
    },

    showMode: function(dir) {
        if (dir) {
            this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
        }
        this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
    }
};

$.fn.datepicker = function ( option, val ) {
    return this.each(function () {
        var $this = $(this);
        var datePicker = $this.data('datepicker');
        var options = typeof option === 'object' && option;
        if (!datePicker) {
            if (typeof val === 'function')
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
            else{
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
        }
        if (typeof option === 'string') datePicker[option](val);

    });
};

$.fn.datepicker.defaults = {
    onRender: function(date) {
        return '';
    }
};
$.fn.datepicker.Constructor = Datepicker;

var DPGlobal = {
    modes: [
        {
            clsName: 'days',
            navFnc: 'Month',
            navStep: 1
        },
        {
            clsName: 'months',
            navFnc: 'FullYear',
            navStep: 1
        },
        {
            clsName: 'years',
            navFnc: 'FullYear',
            navStep: 10
    }],
    dates:{
        days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
                    daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
                    daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
                    months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
                    monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
                    today: "Aujourd'hui",
                    clear: "Effacer",
                    weekStart: 1,
                    format: "dd/mm/yyyy"
    },
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth: function (year, month) {
        return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    parseFormat: function(format){
        var separator = format.match(/[.\/\-\s].*?/),
            parts = format.split(/\W+/);
        if (!separator || !parts || parts.length === 0){
            throw new Error("Invalid date format.");
        }
        return {separator: separator, parts: parts};
    },
    parseDate: function(date, format) {
        var parts = date.split(format.separator),
            date = new Date(),
            val;
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        if (parts.length === format.parts.length) {
            var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                val = parseInt(parts[i], 10)||1;
                switch(format.parts[i]) {
                    case 'dd':
                    case 'd':
                        day = val;
                        date.setDate(val);
                        break;
                    case 'mm':
                    case 'm':
                        month = val - 1;
                        date.setMonth(val - 1);
                        break;
                    case 'yy':
                        year = 2000 + val;
                        date.setFullYear(2000 + val);
                        break;
                    case 'yyyy':
                        year = val;
                        date.setFullYear(val);
                        break;
                }
            }
            date = new Date(year, month, day, 0 ,0 ,0);
        }
        return date;
    },
    formatDate: function(date, format){
        var val = {
            d: date.getDate(),
            m: date.getMonth() + 1,
            yy: date.getFullYear().toString().substring(2),
            yyyy: date.getFullYear()
        };
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
        var date = [];
        for (var i=0, cnt = format.parts.length; i < cnt; i++) {
            date.push(val[format.parts[i]]);
        }
        return date.join(format.separator);
    },
    headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">&lsaquo;</th>'+
                            '<th colspan="5" class="switch"></th>'+
                            '<th class="next">&rsaquo;</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';

}( window.jQuery );

How do I include negative decimal numbers in this regular expression?

This will allow both positive and negative integers

ValidationExpression="^-?[0-9]\d*(\d+)?$"

How can I change IIS Express port for a site

Here's a more manual method that works both for Website projects and Web Application projects. (you can't change the project URL from within Visual Studio for Website projects.)

Web Application projects

  1. In Solution Explorer, right-click the project and click Unload Project.

  2. Navigate to the IIS Express ApplicationHost.config file. By default, this file is located in:

    %userprofile%\Documents\IISExpress\config

    In recent Visual Studio versions and Web Application projects, this file is in the solution folder under [Solution Dir]\.vs\config\applicationhost.config (note the .vs folder is a hidden item)

  3. Open the ApplicationHost.config file in a text editor. In the <sites> section, search for your site's name. In the <bindings> section of your site, you will see an element like this:

    <binding protocol="http" bindingInformation="*:56422:localhost" />

    Change the port number (56422 in the above example) to anything you want. e.g.:

    <binding protocol="http" bindingInformation="*:44444:localhost" />

    Bonus: You can even bind to a different host name and do cool things like:

    <binding protocol="http" bindingInformation="*:80:mysite.dev" />

    and then map mysite.dev to 127.0.0.1 in your hosts file, and then open your website from "http://mysite.dev"

  4. In Solution Explorer, right-click the the project and click Reload Project.

  5. In Solution Explorer, right-click the the project and select Properties.

    • Select the Web tab.

    • In the Servers section, under Use Local IIS Web server, in the Project URL box enter a URL to match the hostname and port you entered in the ApplicationHost.config file from before.

    • To the right of the Project URL box, click Create Virtual Directory. If you see a success message, then you've done the steps correctly.

    • In the File menu, click Save Selected Items.

Website projects

  1. In Solution Explorer, right-click the project name and then click Remove or Delete; don't worry, this removes the project from your solution, but does not delete the corresponding files on disk.

  2. Follow step 2 from above for Web Application projects.

  3. In Solution Explorer, right-click the solution, select Add, and then select Existing Web Site.... In the Add Existing Web Site dialog box, make sure that the Local IIS tab is selected. Under IIS Express Sites, select the site for which you have changed the port number, then click OK.

Now you can access your website from your new hostname/port.

LAST_INSERT_ID() MySQL

This enables you to insert a row into 2 different tables and creates a reference to both tables too.

START TRANSACTION;
INSERT INTO accounttable(account_username) 
    VALUES('AnAccountName');
INSERT INTO profiletable(profile_account_id) 
    VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
    SET @profile_id = LAST_INSERT_ID(); 
UPDATE accounttable SET `account_profile_id` = @profile_id;
COMMIT;

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Find 'gradle-wrapper.properties' in root project

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

Change "https" to "http".

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

How do you open a file in C++?

fstream are great but I will go a little deeper and tell you about RAII.

The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.

Update: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII.

class FileOpener
{
public:
    FileOpener(std::fstream& file, const char* fileName): m_file(file)
    { 
        m_file.open(fileName); 
    }
    ~FileOpeneer()
    { 
        file.close(); 
    }

private:
    std::fstream& m_file;
};

You can now use this class in your code like this:

int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called

Learning how RAII works can save you some headaches and some major memory management bugs.

Return multiple values from a function in swift

Swift 3

func getTime() -> (hour: Int, minute: Int,second: Int) {
        let hour = 1
        let minute = 20
        let second = 55
        return (hour, minute, second)
    }

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

Going from MM/DD/YYYY to DD-MMM-YYYY in java

Below should work.

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date oldDate = df.parse(df.format(date)); //this date is your old date object

Cast a Double Variable to Decimal

You only use the M for a numeric literal, when you cast it's just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

How to make this Header/Content/Footer layout using CSS?

Try This

<!DOCTYPE html>

<html>

<head>

<title>Sticky Header and Footer</title>

<style type="text/css">

/* Reset body padding and margins */

body {
    margin:0;

    padding:0;
}

/* Make Header Sticky */

#header_container {

    background:#eee;

    border:1px solid #666;

    height:60px;

    left:0;

    position:fixed;

    width:100%;

    top:0;
}

#header {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;
}

/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/

#container {

    margin:0 auto;

    overflow:auto;

    padding:80px 0;

    width:940px;

}

#content {

}

/* Make Footer Sticky */

#footer_container {

    background:#eee;

    border:1px solid #666;

    bottom:0;

    height:60px;

    left:0;

    position:fixed;

    width:100%;
}

#footer {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;

}

</style>

</head>

<body>

<!-- BEGIN: Sticky Header -->
<div id="header_container">

    <div id="header">
        Header Content
    </div>

</div>
<!-- END: Sticky Header -->

<!-- BEGIN: Page Content -->
<div id="container">

    <div id="content">

            content
        <br /><br />
            blah blah blah..
        ...
    </div>

</div>
<!-- END: Page Content -->

<!-- BEGIN: Sticky Footer -->
<div id="footer_container">

    <div id="footer">

        Footer Content

    </div>

</div>

<!-- END: Sticky Footer -->

</body>

</html>

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

How can I get href links from HTML using Python?

This answer is similar to others with requests and BeautifulSoup, but using list comprehension.

Because find_all() is the most popular method in the Beautiful Soup search API, you can use soup("a") as a shortcut of soup.findAll("a") and using list comprehension:

import requests
from bs4 import BeautifulSoup

URL = "http://www.yourwebsite.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all

Extending from two classes

The creators of java decided that the problems of multiple inheritance outweigh the benefits, so they did not include multiple inheritance. You can read about one of the largest issues of multiple inheritance (the double diamond problem) here.

The two most similar concepts are interface implementation and including objects of other classes as members of the current class. Using default methods in interfaces is almost exactly the same as multiple inheritance, however it is considered bad practice to use an interface with only default methods.

How to write both h1 and h2 in the same line?

In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.

<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>

Will give you:

What the...heck is going on?

and not

What the... 
heck is going on?

Math functions in AngularJS bindings

I think the best way to do it is by creating a filter, like this:

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

then the markup looks like this:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

Updated fiddle: http://jsfiddle.net/BB4T4/

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Using a HTTP debugging proxy can cause this - such as Fiddler.

I was loading a PFX certificate from a local file (authentication to Apple.com) and it failed because Fiddler wasn't able to pass this certificate on.

Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.

How can I use "." as the delimiter with String.split() in java

When splitting with a string literal delimiter, the safest way is to use the Pattern.quote() method:

String[] words = line.split(Pattern.quote("."));

As described by other answers, splitting with "\\." is correct, but quote() will do this escaping for you.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

This is my mix:

overflow-y: scroll;
height: 13em; // Initial height.
resize: vertical; // Allow user to change the vertical size.
max-height: 31em; // If you want to constrain the max size.

Python - Check If Word Is In A String

If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:

def smart_find(haystack, needle):
    if haystack.startswith(needle+" "):
        return True
    if haystack.endswith(" "+needle):
        return True
    if haystack.find(" "+needle+" ") != -1:
        return True
    return False

This assumes that commas and other punctuations have already been stripped out.

Open Form2 from Form1, close Form1 from Form2

Form1:

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

Form2:

public partial class Form2 : Form
{
    Form opener;

    public Form2(Form parentForm)
    {
        InitializeComponent();
        opener = parentForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        opener.Close();
        this.Close();
    }
}

Could not establish secure channel for SSL/TLS with authority '*'

In case it helps anyone else, using the new Microsoft Web Service Reference Provider tool, which is for .NET Standard and .NET Core, I had to add the following lines to the binding definition as below:

binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport = new HttpTransportSecurity{ClientCredentialType = HttpClientCredentialType.Certificate};

This is effectively the same as Micha's answer but in code as there is no config file.

So to incorporate the binding with the instantiation of the web service I did this:

 System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
 binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
 binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Certificate;
 var client = new WebServiceClient(binding, GetWebServiceEndpointAddress());

Where WebServiceClient is the proper name of your web service as you defined it.

django change default runserver port

In Pycharm you can simply add the port to the parameters

enter image description here

How to remove/delete a large file from commit history in Git repository?

This will remove it from your history

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch bigfile.txt' --prune-empty --tag-name-filter cat -- --all

Can't drop table: A foreign key constraint fails

I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.

Basically, your table should be changed like so:

ALTER TABLE 'bericht' DROP FOREIGN KEY 'your_foreign_key';

ALTER TABLE 'bericht' ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;

Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.

Hope this helps.

How do I make a relative reference to another workbook in Excel?

In Excel, there is a way to embed relative reference to file or directory. You can try type in excel cell : =HYPERLINK("..\Name_of_file_or_folder\","DisplayLinkName")

Efficient way to remove ALL whitespace from String?

I needed to replace white space in a string with spaces, but not duplicate spaces. e.g., I needed to convert something like the following:

"a b   c\r\n d\t\t\t e"

to

"a b c d e"

I used the following method

private static string RemoveWhiteSpace(string value)
{
    if (value == null) { return null; }
    var sb = new StringBuilder();

    var lastCharWs = false;
    foreach (var c in value)
    {
        if (char.IsWhiteSpace(c))
        {
            if (lastCharWs) { continue; }
            sb.Append(' ');
            lastCharWs = true;
        }
        else
        {
            sb.Append(c);
            lastCharWs = false;
        }
    }
    return sb.ToString();
}

Parse date without timezone javascript

This is the solution that I came up with for this problem which works for me.


library used: momentjs with plain javascript Date class.

Step 1. Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):

const dateMoment = moment("2005-07-08T11:22:33+0000");

Step 2. Extract hours and minutes values from the previously created moment object:

  const hours = dateMoment.hours();
  const mins = dateMoment.minutes();

Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):

  const dateObj = dateMoment.toDate();

Step 4. Manually set the hours and minutes extracted in Step 2.

  dateObj.setHours(hours);
  dateObj.setMinutes(mins);

Step 5. dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.

Hope this helps.

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

If "0" then leave the cell blank

Use this

=IFERROR((H15+G16-F16)^2/(H15+G16-F16),"")

How to position the form in the center screen?

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

How can I check if the current date/time is past a set date/time?

date_default_timezone_set('Asia/Kolkata');

$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
}else{
    echo "inactive";exit;
}

TensorFlow, "'module' object has no attribute 'placeholder'"

I had the same problem before after tried to upgrade tensorflow, I solved it by reinstalling Tensorflow and Keras.

pip uninstall tensorflow

pip uninstall keras

Then:

pip install tensorflow

pip install keras

C# Change A Button's Background Color

In WPF, the background is not a Color, it is a Brush. So, try this for starters:

using System.Windows.Media;

// ....

ButtonToday.Background = new SolidColorBrush(Colors.Red);

More sensibly, though, you should probably look at doing this in your Xaml instead of in code.

Where can I find free WPF controls and control templates?

Syncfusion has a free community version available with over 650 controls.

Syncfusion

You will find an FAQ there with any licensing questions you may have, it sound great to be honest. Have fun!

Edit: The WPF controls themselves are 100+, the number of 650+ refers to all controls for all areas (WPF, Windows Forms etc).

How do you get current active/default Environment profile programmatically in Spring?

Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles

Getting current directory in VBScript

You can use CurrentDirectory property.

Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir    = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Import error: No module name urllib2

The above didn't work for me in 3.3. Try this instead (YMMV, etc)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

iPhone App Development on Ubuntu

It can be done!!!!!!

There is someone who did it.

Enjoy :)

Check if string is in a pandas dataframe

I bumped into the same problem, I used:

if "Mel" in a["Names"].values:
    print("Yep")

But this solution may be slower since internally pandas create a list from a Series.

C# looping through an array

This should work:

//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
    var a = theData[i];
    var b = theData[i + 1];
    var c = theData[i + 2];
}

I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.

Could not resolve '...' from state ''

I had a case where the error was thrown by a

$state.go('');

Which is obvious. I guess this can help someone in future.

Unable to execute dex: Multiple dex files define

Even after going through multiple answers, no solution worked for me.

I deleted "Android Dependencies" from the build path. Added all the jar files again to the build path and the error was gone. Somehow eclipse seemed to cache the things.

Amazon S3 upload file and get URL

        System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

with this you can retrieve the link of already uploaded file to S3 bucket.

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-

Second.h:

void second();
int third();
double fourth();

main.cpp:

#include <iostream>
#include "second.h"
int main()
{
    //.....
    return 0;
}

second.cpp:

void second()
{
    //...
}

int third()
{ 
    //...
    return foo;
}

double fourth()
{ 
    //...
    return f;
}

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

Difference between const reference and normal parameter

Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.

$8.3.2/1- "Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored."

Here are the differences

$13.1 - "Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.112). In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

void f(int &n){
   cout << 1; 
   n++;
}

void f(int const &n){
   cout << 2;
   //n++; // Error!, Non modifiable lvalue
}

int main(){
   int x = 2;

   f(x);        // Calls overload 1, after the call x is 3
   f(2);        // Calls overload 2
   f(2.2);      // Calls overload 2, a temporary of double is created $8.5/3
}

Check if a number is odd or even in python

The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.

Hint: all you need is a slight tweak to the following line to make this work for all word lengths:

secondHalf = word[finalWordLength + 1:]

P.S. If you insist on handling the two cases separately, if len(word) % 2: ... would tell you that the word has an odd number of characters.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

What is the default boolean value in C#?

Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

Only the following variables are automatically initialized to their default values:

  • Static variables
  • Instance variables of class and struct instances
  • Array elements

The default values are as follows (assigned in default constructor of a class):

  • The default value of a variable of reference type is null.
  • For integer types, the default value is 0
  • For char, the default value is `\u0000'
  • For float, the default value is 0.0f
  • For double, the default value is 0.0d
  • For decimal, the default value is 0.0m
  • For bool, the default value is false
  • For an enum type, the default value is 0
  • For a struct type, the default value is obtained by setting all value type fields to their default values

As far as later parts of your question are conerned:

  • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
  • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.

Most useful NLog configurations

Log from Silverlight

When using NLog with Silverlight you can send the trace to the server side via the provided web service. You can also write to a local file in the Isolated Storage, which come in handy if the web server is unavailable. See here for details, i.e. use something like this to make yourself a target:

namespace NLogTargets
{
    [Target("IsolatedStorageTarget")]
    public sealed class IsolatedStorageTarget : TargetWithLayout
    {
        IsolatedStorageFile _storageFile = null;
        string _fileName = "Nlog.log"; // Default. Configurable through the 'filename' attribute in nlog.config

        public IsolatedStorageTarget()
        {
        }

        ~IsolatedStorageTarget()
        {
            if (_storageFile != null)
            {
                _storageFile.Dispose();
                _storageFile = null;
            }
        }

        public string filename
        {
            set
            {
                _fileName = value; 
            }
            get
            {
                return _fileName;  
            }
         }

        protected override void Write(LogEventInfo logEvent)
        {
            try
            {
                writeToIsolatedStorage(this.Layout.Render(logEvent));
            }
            catch (Exception e)
            {
                // Not much to do about his....
            }
        }

        public void writeToIsolatedStorage(string msg)
        {
            if (_storageFile == null)
                _storageFile = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // The isolated storage is limited in size. So, when approaching the limit
                // simply purge the log file. (Yeah yeah, the file should be circular, I know...)
                if (_storageFile.AvailableFreeSpace < msg.Length * 100)
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Truncate, FileAccess.Write, isolatedStorage))
                    { }
                }
                // Write to isolated storage
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Append, FileAccess.Write, isolatedStorage))
                {
                    using (TextWriter writer = new StreamWriter(stream))
                    {
                        writer.WriteLine(msg);
                    }
                }
            }
        }
    } 
}

How to delete/remove nodes on Firebase

The problem is that you call remove on the root of your Firebase:

ref = new Firebase("myfirebase.com")
ref.remove();

This will remove the entire Firebase through the API.

You'll typically want to remove specific child nodes under it though, which you do with:

ref.child(key).remove();

How to convert string to float?

Why one should not use function atof() to convert string to double?

On success, atof() function returns the converted floating point number as a double value. If no valid conversion could be performed, the function returns zero (0.0). If the converted value would be out of the range of representable values by a double, it causes undefined behavior.

Refrence:http://www.cplusplus.com/reference/cstdlib/atof/

Instead use function strtod(), it is more robust.

Try this code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char s[100] = "4.0800";
    printf("Float value : %4.8f\n",strtod(s,NULL));
    return 0;
}

You will get the following output:

Float value : 4.08000000

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

            using (var tbl = new DataTable())
            using (var rdr = cmd.ExecuteReader())
            {
                tbl.BeginLoadData();

                try
                {
                    tbl.Load(rdr);
                }
                catch (ConstraintException ex)
                {
                    rdr.Close();
                    tbl.Clear();

                    // clear constraints, source of exceptions
                    // note: column schema already loaded!
                    tbl.Constraints.Clear();
                    tbl.Load(cmd.ExecuteReader());
                }
                finally
                {
                    tbl.EndLoadData();
                }
            }

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

How do I tokenize a string in C++?

Another quick way is to use getline. Something like:

stringstream ss("bla bla");
string s;

while (getline(ss, s, ' ')) {
 cout << s << endl;
}

If you want, you can make a simple split() method returning a vector<string>, which is really useful.

Select a random sample of results from a query result

I know this has already been answered, but seeing so many visits here I'd like to add one version that uses the SAMPLE clause but still allows to filter the rows first:

with cte1 as (
    select *
    from t_your_table
    where your_column = 'ABC'
)
select * from cte1 sample (5)

Note however that the base select needs a ROWID column, which means it may not work for some views for example.

How do I fix MSB3073 error in my post-build event?

Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.

What is the equivalent of Java's final in C#?

http://en.csharp-online.net/CSharp_FAQ:_What_are_the_differences_between_CSharp_and_Java_constant_declarations

C# constants are declared using the const keyword for compile time constants or the readonly keyword for runtime constants. The semantics of constants is the same in both the C# and Java languages.

Does Java have something like C#'s ref and out keywords?

Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.

An example is included in the code below.

//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
    public XOBJ<T> Obj = null;

    public XOUT(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XOUT()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(this);
    }

    public XREF<T> Ref()
    {
        return(Obj.Ref());
    }
};

//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************

public class XREF<T>
{
    public XOBJ<T> Obj = null;

    public XREF(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XREF()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(Obj.Out());
    }

    public XREF<T> Ref()
    {
        return(this);
    }
};

//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
 *
 * @author jsimms
 */
/*
    XOBJ is the base object that houses the value. XREF and XOUT are classes that
    internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
    the object to be used as XREF or XOUT parameter; This is important, because
    objects of these types are interchangeable.

    See Method:
       XXX.Ref()
       XXX.Out()

    The below example shows how to use XOBJ, XREF, and XOUT;
    //
    // Reference parameter example
    //
    void AddToTotal(int a, XREF<Integer> Total)
    {
       Total.Obj.Value += a;
    }

    //
    // out parameter example
    //
    void Add(int a, int b, XOUT<Integer> ParmOut)
    {
       ParmOut.Obj.Value = a+b;
    }

    //
    // XOBJ example
    //
    int XObjTest()
    {
       XOBJ<Integer> Total = new XOBJ<>(0);
       Add(1, 2, Total.Out());    // Example of using out parameter
       AddToTotal(1,Total.Ref()); // Example of using ref parameter
       return(Total.Value);
    }
*/


public class XOBJ<T> {

    public T Value;

    public  XOBJ() {

    }

    public XOBJ(T value) {
        this.Value = value;
    }

    //
    // Method: Ref()
    // Purpose: returns a Reference Parameter object using the XOBJ value
    //
    public XREF<T> Ref()
    {
        XREF<T> ref = new XREF<T>();
        ref.Obj = this;
        return(ref);
    }

    //
    // Method: Out()
    // Purpose: returns an Out Parameter Object using the XOBJ value
    //
    public XOUT<T> Out()
    {
        XOUT<T> out = new XOUT<T>();
        out.Obj = this;
        return(out);
    }

    //
    // Method get()
    // Purpose: returns the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public T get() {
        return Value;
    }

    //
    // Method get()
    // Purpose: sets the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public void set(T anotherValue) {
        Value = anotherValue;
    }

    @Override
    public String toString() {
        return Value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return Value.equals(obj);
    }

    @Override
    public int hashCode() {
        return Value.hashCode();
    }
}

ImageView rounded corners

You should use RoundedCornersTransformation from this library and create a circular ImageView.

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;

public class RoundedCornersTransformation implements Transformation {

    public enum CornerType {
        ALL,
        TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
        TOP, BOTTOM, LEFT, RIGHT,
        OTHER_TOP_LEFT, OTHER_TOP_RIGHT, OTHER_BOTTOM_LEFT, OTHER_BOTTOM_RIGHT,
        DIAGONAL_FROM_TOP_LEFT, DIAGONAL_FROM_TOP_RIGHT
    }

    private int mRadius;
    private int mDiameter;
    private int mMargin;
    private CornerType mCornerType;

    public RoundedCornersTransformation(int radius, int margin) {
        this(radius, margin, CornerType.ALL);
    }

    public RoundedCornersTransformation(int radius, int margin, CornerType cornerType) {
        mRadius = radius;
        mDiameter = radius * 2;
        mMargin = margin;
        mCornerType = cornerType;
    }

    @Override public Bitmap transform(Bitmap source) {
        int width = source.getWidth();
        int height = source.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        drawRoundRect(canvas, paint, width, height);
        source.recycle();
        return bitmap;
    }

    private void drawRoundRect(Canvas canvas, Paint paint, float width, float height) {
        float right = width - mMargin;
        float bottom = height - mMargin;
        switch (mCornerType) {
            case ALL:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
            case TOP_LEFT:
                drawTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case TOP_RIGHT:
                drawTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_LEFT:
                drawBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_RIGHT:
                drawBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case TOP:
                drawTopRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM:
                drawBottomRoundRect(canvas, paint, right, bottom);
            break;
            case LEFT:
                drawLeftRoundRect(canvas, paint, right, bottom);
            break;
            case RIGHT:
                drawRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_LEFT:
                drawOtherTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_RIGHT:
                drawOtherTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_LEFT:
                drawOtherBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_RIGHT:
                drawOtherBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_LEFT:
                drawDiagonalFromTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_RIGHT:
                drawDiagonalFromTopRightRoundRect(canvas, paint, right, bottom);
            break;
            default:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
        }
    }

    private void drawTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, mMargin + mRadius, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawTopRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right, bottom - mRadius), paint);
    }

    private void drawLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
    }

    private void drawOtherTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
    }

    private void drawOtherTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawOtherBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mRadius, bottom), paint);
    }

    private void drawOtherBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawDiagonalFromTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mDiameter, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mDiameter, mMargin, right, bottom - mRadius), paint);
    }

    private void drawDiagonalFromTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    @Override public String key() {
        return "RoundedTransformation(radius=" + mRadius + ", margin=" + mMargin + ", diameter=" + mDiameter + ", cornerType=" + mCornerType.name() + ")";
    }
}

DataTrigger where value is NOT null?

Stop! No converter! I dont want to "sell" the library of this guy, but I hated the fact of doing converter everytime I wanted to compare stuff in XAML.

So with this library : https://github.com/Alex141/CalcBinding

you can do that [and a lot more] :

First, In the declaration of the windows/userControl :

<Windows....
     xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"
>

then, in the textblock

<TextBlock>
      <TextBlock.Style>
          <Style.Triggers>
          <DataTrigger Binding="{conv:Binding 'MyValue==null'}" Value="false">
             <Setter Property="Background" Value="#FF80C983"></Setter>
          </DataTrigger>
        </Style.Triggers>
      </TextBlock.Style>
    </TextBlock>

The magic part is the conv:Binding 'MYValue==null'. In fact, you could set any condition you wanted [look at the doc].

note that I am not a fan of third party. but this library is Free, and little impact (just add 2 .dll to the project).

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

How to use git merge --squash?

For Git

Create a new feature

via Terminal/Shell:

git checkout origin/feature/<featurename>
git merge --squash origin/feature/<featurename>

This doesnt commit it, allows you to review it first.

Then commit, and finish feature from this new branch, and delete/ignore the old one (the one you did dev on).

Is there a function in python to split a word into a list?

def count(): list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'

word_list = []
# dict = {}
for i in range(len(list)):
    word_list.append(list[i])
# word_list1 = sorted(word_list)
for i in range(len(word_list) - 1, 0, -1):
    for j in range(i):
        if word_list[j] > word_list[j + 1]:
            temp = word_list[j]
            word_list[j] = word_list[j + 1]
            word_list[j + 1] = temp
print("final count of arrival of each letter is : \n", dict(map(lambda x: (x, word_list.count(x)), word_list)))

Redirect stderr to stdout in C shell

I object the above answer and provide my own. csh DOES have this capability and here is how it's done:

xxx |& some_exec # will pipe merged output to your some_exec 

or

xxx |& cat > filename

or if you just want it to merge streams (to stdout) and not redirect to a file or some_exec:

xxx |& tee /dev/null

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In the case where the problem is that System.loadLibrary cannot find the DLL in question, one common misconception (reinforced by Java's error message) is that the system property java.library.path is the answer. If you set the system property java.library.path to the directory where your DLL is located, then System.loadLibrary will indeed find your DLL. However, if your DLL in turn depends on other DLLs, as is often the case, then java.library.path cannot help, because the loading of the dependent DLLs is managed entirely by the operating system, which knows nothing of java.library.path. Thus, it is almost always better to bypass java.library.path and simply add your DLL's directory to LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (MacOS), or Path (Windows) prior to starting the JVM.

(Note: I am using the term "DLL" in the generic sense of DLL or shared library.)

Make an existing Git branch track a remote branch?

To avoid remembering what you need to do each time you get the message:

Please specify which branch you want to merge with. See git-pull(1)
for details.
.....

You can use the following script which sets origin as upstream for the current branch you are in.

In my case I almost never set something else than origin as the default upstream. Also I almost always keep the same branch name for local and remote branch. So the following fits me:

#!/bin/bash
# scriptname: git-branch-set-originupstream
current_branch="$(git branch | grep -oP '(?<=^\* )(.*)$')"
upstream="origin/$current_branch"
git branch -u "$upstream"

Dynamically update values of a chartjs chart

Update: Looks like chartjs has been updated (see comment below). There are some examples up that look very nice:

  1. Here's an example of updating a line chart using new data: http://jsbin.com/yitep/5/edit
  2. Here's how we can update existing data on a line chart: http://jsbin.com/yitep/4/edit

Original Post

As of Nov 2013, there seem to be very few options for updating charts.

There is a good example here (duplicated below) of adding new points to a line chart. Still kind of jumpy but not too bad. However, I think the effect probably depends on the chart you are using.

It does look like this is somewhere in the development pipeline. I don't see any indication of a release date yet though: https://github.com/nnnick/Chart.js/issues/13 [Closed as of Jul 26, 2014]

JS

$(document).ready(function(){
  var count = 10;
  var data = {
      labels : ["1","2","3","4","5", "6", "7", "8", "9", "10"],
        datasets : [
          {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,1)",
                pointColor : "rgba(220,220,220,1)",
                pointStrokeColor : "#fff",
                data : [65,59,90,81,56,45,30,20,3,37]
            },
            {
                fillColor : "rgba(151,187,205,0.5)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                data : [28,48,40,19,96,87,66,97,92,85]
            }
        ]
  }
  // this is ugly, don't judge me
  var updateData = function(oldData){
    var labels = oldData["labels"];
    var dataSetA = oldData["datasets"][0]["data"];
    var dataSetB = oldData["datasets"][1]["data"];

    labels.shift();
    count++;
    labels.push(count.toString());
    var newDataA = dataSetA[9] + (20 - Math.floor(Math.random() * (41)));
    var newDataB = dataSetB[9] + (20 - Math.floor(Math.random() * (41)));
    dataSetA.push(newDataA);
    dataSetB.push(newDataB);
    dataSetA.shift();
    dataSetB.shift();    };

  var optionsAnimation = {
    //Boolean - If we want to override with a hard coded scale
    scaleOverride : true,
    //** Required if scaleOverride is true **
    //Number - The number of steps in a hard coded scale
    scaleSteps : 10,
    //Number - The value jump in the hard coded scale
    scaleStepWidth : 10,
    //Number - The scale starting value
    scaleStartValue : 0
  }

  // Not sure why the scaleOverride isn't working...
  var optionsNoAnimation = {
    animation : false,
    //Boolean - If we want to override with a hard coded scale
    scaleOverride : true,
    //** Required if scaleOverride is true **
    //Number - The number of steps in a hard coded scale
    scaleSteps : 20,
    //Number - The value jump in the hard coded scale
    scaleStepWidth : 10,
    //Number - The scale starting value
    scaleStartValue : 0
  }

  //Get the context of the canvas element we want to select
  var ctx = document.getElementById("myChart").getContext("2d");
  var optionsNoAnimation = {animation : false}
  var myNewChart = new Chart(ctx);
  myNewChart.Line(data, optionsAnimation);  

  setInterval(function(){
    updateData(data);
    myNewChart.Line(data, optionsNoAnimation)
    ;}, 2000
  );
});


// ChartJS
var Chart=function(s){function v(a,c,b){a=A((a-c.graphMin)/(c.steps*c.stepValue),1,0);return b*c.steps*a}function x(a,c,b,e){function h(){g+=f;var k=a.animation?A(d(g),null,0):1;e.clearRect(0,0,q,u);a.scaleOverlay?(b(k),c()):(c(),b(k));if(1>=g)D(h);else if("function"==typeof a.onAnimationComplete)a.onAnimationComplete()}var f=a.animation?1/A(a.animationSteps,Number.MAX_VALUE,1):1,d=B[a.animationEasing],g=a.animation?0:1;"function"!==typeof c&&(c=function(){});D(h)}function C(a,c,b,e,h,f){var d;a=
Math.floor(Math.log(e-h)/Math.LN10);h=Math.floor(h/(1*Math.pow(10,a)))*Math.pow(10,a);e=Math.ceil(e/(1*Math.pow(10,a)))*Math.pow(10,a)-h;a=Math.pow(10,a);for(d=Math.round(e/a);d<b||d>c;)a=d<b?a/2:2*a,d=Math.round(e/a);c=[];z(f,c,d,h,a);return{steps:d,stepValue:a,graphMin:h,labels:c}}function z(a,c,b,e,h){if(a)for(var f=1;f<b+1;f++)c.push(E(a,{value:(e+h*f).toFixed(0!=h%1?h.toString().split(".")[1].length:0)}))}function A(a,c,b){return!isNaN(parseFloat(c))&&isFinite(c)&&a>c?c:!isNaN(parseFloat(b))&&
isFinite(b)&&a<b?b:a}function y(a,c){var b={},e;for(e in a)b[e]=a[e];for(e in c)b[e]=c[e];return b}function E(a,c){var b=!/\W/.test(a)?F[a]=F[a]||E(document.getElementById(a).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+a.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return c?
b(c):b}var r=this,B={linear:function(a){return a},easeInQuad:function(a){return a*a},easeOutQuad:function(a){return-1*a*(a-2)},easeInOutQuad:function(a){return 1>(a/=0.5)?0.5*a*a:-0.5*(--a*(a-2)-1)},easeInCubic:function(a){return a*a*a},easeOutCubic:function(a){return 1*((a=a/1-1)*a*a+1)},easeInOutCubic:function(a){return 1>(a/=0.5)?0.5*a*a*a:0.5*((a-=2)*a*a+2)},easeInQuart:function(a){return a*a*a*a},easeOutQuart:function(a){return-1*((a=a/1-1)*a*a*a-1)},easeInOutQuart:function(a){return 1>(a/=0.5)?
0.5*a*a*a*a:-0.5*((a-=2)*a*a*a-2)},easeInQuint:function(a){return 1*(a/=1)*a*a*a*a},easeOutQuint:function(a){return 1*((a=a/1-1)*a*a*a*a+1)},easeInOutQuint:function(a){return 1>(a/=0.5)?0.5*a*a*a*a*a:0.5*((a-=2)*a*a*a*a+2)},easeInSine:function(a){return-1*Math.cos(a/1*(Math.PI/2))+1},easeOutSine:function(a){return 1*Math.sin(a/1*(Math.PI/2))},easeInOutSine:function(a){return-0.5*(Math.cos(Math.PI*a/1)-1)},easeInExpo:function(a){return 0==a?1:1*Math.pow(2,10*(a/1-1))},easeOutExpo:function(a){return 1==
a?1:1*(-Math.pow(2,-10*a/1)+1)},easeInOutExpo:function(a){return 0==a?0:1==a?1:1>(a/=0.5)?0.5*Math.pow(2,10*(a-1)):0.5*(-Math.pow(2,-10*--a)+2)},easeInCirc:function(a){return 1<=a?a:-1*(Math.sqrt(1-(a/=1)*a)-1)},easeOutCirc:function(a){return 1*Math.sqrt(1-(a=a/1-1)*a)},easeInOutCirc:function(a){return 1>(a/=0.5)?-0.5*(Math.sqrt(1-a*a)-1):0.5*(Math.sqrt(1-(a-=2)*a)+1)},easeInElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*
Math.PI)*Math.asin(1/e);return-(e*Math.pow(2,10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b))},easeOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return e*Math.pow(2,-10*a)*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(2==(a/=0.5))return 1;b||(b=1*0.3*1.5);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return 1>a?-0.5*e*Math.pow(2,10*
(a-=1))*Math.sin((1*a-c)*2*Math.PI/b):0.5*e*Math.pow(2,-10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInBack:function(a){return 1*(a/=1)*a*(2.70158*a-1.70158)},easeOutBack:function(a){return 1*((a=a/1-1)*a*(2.70158*a+1.70158)+1)},easeInOutBack:function(a){var c=1.70158;return 1>(a/=0.5)?0.5*a*a*(((c*=1.525)+1)*a-c):0.5*((a-=2)*a*(((c*=1.525)+1)*a+c)+2)},easeInBounce:function(a){return 1-B.easeOutBounce(1-a)},easeOutBounce:function(a){return(a/=1)<1/2.75?1*7.5625*a*a:a<2/2.75?1*(7.5625*(a-=1.5/2.75)*
a+0.75):a<2.5/2.75?1*(7.5625*(a-=2.25/2.75)*a+0.9375):1*(7.5625*(a-=2.625/2.75)*a+0.984375)},easeInOutBounce:function(a){return 0.5>a?0.5*B.easeInBounce(2*a):0.5*B.easeOutBounce(2*a-1)+0.5}},q=s.canvas.width,u=s.canvas.height;window.devicePixelRatio&&(s.canvas.style.width=q+"px",s.canvas.style.height=u+"px",s.canvas.height=u*window.devicePixelRatio,s.canvas.width=q*window.devicePixelRatio,s.scale(window.devicePixelRatio,window.devicePixelRatio));this.PolarArea=function(a,c){r.PolarArea.defaults={scaleOverlay:!0,
scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",
animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.PolarArea.defaults,c):r.PolarArea.defaults;return new G(a,b,s)};this.Radar=function(a,c){r.Radar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!1,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",
scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,angleShowLineOut:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:12,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Radar.defaults,c):r.Radar.defaults;return new H(a,b,s)};this.Pie=function(a,
c){r.Pie.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.Pie.defaults,c):r.Pie.defaults;return new I(a,b,s)};this.Doughnut=function(a,c){r.Doughnut.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,
onAnimationComplete:null};var b=c?y(r.Doughnut.defaults,c):r.Doughnut.defaults;return new J(a,b,s)};this.Line=function(a,c){r.Line.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0,
pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:2,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Line.defaults,c):r.Line.defaults;return new K(a,b,s)};this.Bar=function(a,c){r.Bar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",
scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Bar.defaults,c):r.Bar.defaults;return new L(a,b,s)};var G=function(a,c,b){var e,h,f,d,g,k,j,l,m;g=Math.min.apply(Math,[q,u])/2;g-=Math.max.apply(Math,[0.5*c.scaleFontSize,0.5*c.scaleLineWidth]);
d=2*c.scaleFontSize;c.scaleShowLabelBackdrop&&(d+=2*c.scaleBackdropPaddingY,g-=1.5*c.scaleBackdropPaddingY);l=g;d=d?d:5;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.length;f++)a[f].value>e&&(e=a[f].value),a[f].value<h&&(h=a[f].value);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,
m);k=g/j.steps;x(c,function(){for(var a=0;a<j.steps;a++)if(c.scaleShowLine&&(b.beginPath(),b.arc(q/2,u/2,k*(a+1),0,2*Math.PI,!0),b.strokeStyle=c.scaleLineColor,b.lineWidth=c.scaleLineWidth,b.stroke()),c.scaleShowLabels){b.textAlign="center";b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;var e=j.labels[a];if(c.scaleShowLabelBackdrop){var d=b.measureText(e).width;b.fillStyle=c.scaleBackdropColor;b.beginPath();b.rect(Math.round(q/2-d/2-c.scaleBackdropPaddingX),Math.round(u/2-k*(a+
1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(d+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY));b.fill()}b.textBaseline="middle";b.fillStyle=c.scaleFontColor;b.fillText(e,q/2,u/2-k*(a+1))}},function(e){var d=-Math.PI/2,g=2*Math.PI/a.length,f=1,h=1;c.animation&&(c.animateScale&&(f=e),c.animateRotate&&(h=e));for(e=0;e<a.length;e++)b.beginPath(),b.arc(q/2,u/2,f*v(a[e].value,j,k),d,d+h*g,!1),b.lineTo(q/2,u/2),b.closePath(),b.fillStyle=a[e].color,b.fill(),
c.segmentShowStroke&&(b.strokeStyle=c.segmentStrokeColor,b.lineWidth=c.segmentStrokeWidth,b.stroke()),d+=h*g},b)},H=function(a,c,b){var e,h,f,d,g,k,j,l,m;a.labels||(a.labels=[]);g=Math.min.apply(Math,[q,u])/2;d=2*c.scaleFontSize;for(e=l=0;e<a.labels.length;e++)b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily,h=b.measureText(a.labels[e]).width,h>l&&(l=h);g-=Math.max.apply(Math,[l,1.5*(c.pointLabelFontSize/2)]);g-=c.pointLabelFontSize;l=g=A(g,null,0);d=d?d:5;e=Number.MIN_VALUE;
h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(m=0;m<a.datasets[f].data.length;m++)a.datasets[f].data[m]>e&&(e=a.datasets[f].data[m]),a.datasets[f].data[m]<h&&(h=a.datasets[f].data[m]);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,m);k=g/j.steps;x(c,function(){var e=2*Math.PI/
a.datasets[0].data.length;b.save();b.translate(q/2,u/2);if(c.angleShowLineOut){b.strokeStyle=c.angleLineColor;b.lineWidth=c.angleLineWidth;for(var d=0;d<a.datasets[0].data.length;d++)b.rotate(e),b.beginPath(),b.moveTo(0,0),b.lineTo(0,-g),b.stroke()}for(d=0;d<j.steps;d++){b.beginPath();if(c.scaleShowLine){b.strokeStyle=c.scaleLineColor;b.lineWidth=c.scaleLineWidth;b.moveTo(0,-k*(d+1));for(var f=0;f<a.datasets[0].data.length;f++)b.rotate(e),b.lineTo(0,-k*(d+1));b.closePath();b.stroke()}c.scaleShowLabels&&
(b.textAlign="center",b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily,b.textBaseline="middle",c.scaleShowLabelBackdrop&&(f=b.measureText(j.labels[d]).width,b.fillStyle=c.scaleBackdropColor,b.beginPath(),b.rect(Math.round(-f/2-c.scaleBackdropPaddingX),Math.round(-k*(d+1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(f+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY)),b.fill()),b.fillStyle=c.scaleFontColor,b.fillText(j.labels[d],0,-k*(d+
1)))}for(d=0;d<a.labels.length;d++){b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily;b.fillStyle=c.pointLabelFontColor;var f=Math.sin(e*d)*(g+c.pointLabelFontSize),h=Math.cos(e*d)*(g+c.pointLabelFontSize);b.textAlign=e*d==Math.PI||0==e*d?"center":e*d>Math.PI?"right":"left";b.textBaseline="middle";b.fillText(a.labels[d],f,-h)}b.restore()},function(d){var e=2*Math.PI/a.datasets[0].data.length;b.save();b.translate(q/2,u/2);for(var g=0;g<a.datasets.length;g++){b.beginPath();
b.moveTo(0,d*-1*v(a.datasets[g].data[0],j,k));for(var f=1;f<a.datasets[g].data.length;f++)b.rotate(e),b.lineTo(0,d*-1*v(a.datasets[g].data[f],j,k));b.closePath();b.fillStyle=a.datasets[g].fillColor;b.strokeStyle=a.datasets[g].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.fill();b.stroke();if(c.pointDot){b.fillStyle=a.datasets[g].pointColor;b.strokeStyle=a.datasets[g].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(f=0;f<a.datasets[g].data.length;f++)b.rotate(e),b.beginPath(),b.arc(0,d*-1*
v(a.datasets[g].data[f],j,k),c.pointDotRadius,2*Math.PI,!1),b.fill(),b.stroke()}b.rotate(e)}b.restore()},b)},I=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=0;f<a.length;f++)e+=a[f].value;x(c,null,function(d){var g=-Math.PI/2,f=1,j=1;c.animation&&(c.animateScale&&(f=d),c.animateRotate&&(j=d));for(d=0;d<a.length;d++){var l=j*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,f*h,g,g+l);b.lineTo(q/2,u/2);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&(b.lineWidth=
c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());g+=l}},b)},J=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=h*(c.percentageInnerCutout/100),d=0;d<a.length;d++)e+=a[d].value;x(c,null,function(d){var k=-Math.PI/2,j=1,l=1;c.animation&&(c.animateScale&&(j=d),c.animateRotate&&(l=d));for(d=0;d<a.length;d++){var m=l*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,j*h,k,k+m,!1);b.arc(q/2,u/2,j*f,k+m,k,!0);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&
(b.lineWidth=c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());k+=m}},b)},K=function(a,c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(s=45,q/a.labels.length<Math.cos(s)*t?(s=90,g-=t):g-=Math.sin(s)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=
0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;
for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=Math.floor(r/(a.labels.length-1));n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<s?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<s?(b.translate(n+d*m,p+c.scaleFontSize),b.rotate(-(s*(Math.PI/180))),b.fillText(a.labels[d],
0,0),b.restore()):b.fillText(a.labels[d],n+d*m,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+d*m,p+3),c.scaleShowGridLines&&0<d?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+d*m,5)):b.lineTo(n+d*m,p+3),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,
b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){function e(b,c){return p-d*v(a.datasets[b].data[c],j,k)}for(var f=0;f<a.datasets.length;f++){b.strokeStyle=a.datasets[f].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.beginPath();b.moveTo(n,p-d*v(a.datasets[f].data[0],j,k));for(var g=1;g<a.datasets[f].data.length;g++)c.bezierCurve?b.bezierCurveTo(n+m*(g-0.5),e(f,g-1),n+m*(g-0.5),
e(f,g),n+m*g,e(f,g)):b.lineTo(n+m*g,e(f,g));b.stroke();c.datasetFill?(b.lineTo(n+m*(a.datasets[f].data.length-1),p),b.lineTo(n,p),b.closePath(),b.fillStyle=a.datasets[f].fillColor,b.fill()):b.closePath();if(c.pointDot){b.fillStyle=a.datasets[f].pointColor;b.strokeStyle=a.datasets[f].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(g=0;g<a.datasets[f].data.length;g++)b.beginPath(),b.arc(n+m*g,p-d*v(a.datasets[f].data[g],j,k),c.pointDotRadius,0,2*Math.PI,!0),b.fill(),b.stroke()}}},b)},L=function(a,
c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s,w=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(w=45,q/a.labels.length<Math.cos(w)*t?(w=90,g-=t):g-=Math.sin(w)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<
h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=
Math.floor(r/a.labels.length);s=(m-2*c.scaleGridLineWidth-2*c.barValueSpacing-(c.barDatasetSpacing*a.datasets.length-1)-(c.barStrokeWidth/2*a.datasets.length-1))/a.datasets.length;n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<w?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<w?(b.translate(n+
d*m,p+c.scaleFontSize),b.rotate(-(w*(Math.PI/180))),b.fillText(a.labels[d],0,0),b.restore()):b.fillText(a.labels[d],n+d*m+m/2,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+(d+1)*m,p+3),b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+(d+1)*m,5),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*
k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){b.lineWidth=c.barStrokeWidth;for(var e=0;e<a.datasets.length;e++){b.fillStyle=a.datasets[e].fillColor;b.strokeStyle=a.datasets[e].strokeColor;for(var f=0;f<a.datasets[e].data.length;f++){var g=n+c.barValueSpacing+m*f+s*e+c.barDatasetSpacing*e+c.barStrokeWidth*e;b.beginPath();
b.moveTo(g,p);b.lineTo(g,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p);c.barShowStroke&&b.stroke();b.closePath();b.fill()}}},b)},D=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1E3/60)},F={}};

HTML

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <h1>Live Updating Chart.js</h1>

        <canvas id="myChart" width="400" height="150"></canvas>


    </body>
</html>

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You can still use the textmode and force the linefeed-newline with the keyword argument newline

f = open("./foo",'w',newline='\n')

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

Convert JSON String to JSON Object c#

This works

    string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
    JavaScriptSerializer j = new JavaScriptSerializer();
    object a = j.Deserialize(str, typeof(object));

How to handle login pop up window using Selenium WebDriver?

I used IE, then create code like that and works after modification several code:

       public class TestIEBrowser {
                          public static void main(String[] args) throws Exception {
               //Set path of IEDriverServer.exe.
              // Note : IEDriverServer.exe should be In D: drive.
              System.setProperty("webdriver.ie.driver", "path /IEDriverServer.exe");

              // Initialize InternetExplorerDriver Instance.
              WebDriver driver = new InternetExplorerDriver();

              // Load sample calc test URL.
              driver.get("http://...  /");

              //Code to handle Basic Browser Authentication in Selenium.
              Alert aa = driver.switchTo().alert();

              Robot a = new Robot();
              aa.sendKeys("host"+"\\"+"user");  

              a.keyPress(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_ADD);                

              setClipboardData("password");

              a.keyPress(KeyEvent.VK_CONTROL);
              a.keyPress(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_CONTROL);
              //Thread.sleep(5000);
              aa.accept();        




    }

             private static void setClipboardData(String string) {
            // TODO Auto-generated method stub
                        StringSelection stringSelection = new StringSelection(string);                            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        }
}

Create Carriage Return in PHP String?

PHP_EOL returns a string corresponding to the line break on the platform(LF, \n ou #10 sur Unix, CRLF, \n\r ou #13#10 sur Windows).

echo "Hello World".PHP_EOL;

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
    }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");
}

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

Regarding Java switch statements - using return and omitting breaks in each case

If you're going to have a method that just runs the switch and then returns some value, then sure this way works. But if you want a switch with other stuff in a method then you can't use return or the rest of the code inside the method will not execute. Notice in the tutorial how it has a print after the code? Yours would not be able to do this.

PostgreSQL: export resulting data from SQL query to Excel/CSV

The correct script for postgres (Ubuntu) is:

COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';

How do you run multiple programs in parallel from a bash script?

Your script should look like:

prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.

Assuming your system can take n jobs at a time. use wait to run only n jobs at a time.

How do you specify the Java compiler version in a pom.xml file?

Generally you don't want to value only the source version (javac -source 1.8 for example) but you want to value both the source and the target version (javac -source 1.8 -target 1.8 for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9).
Maven that wraps the javac command provides multiple ways to convey all these JVM standard options.

How to specify the JDK version?

Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties to specify the source and the target are equivalent.

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

and

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

are equivalent according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

<release> tag — new way to specify Java version in maven-compiler-plugin 3.6

You can use the release argument :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>9</release>
    </configuration>
</plugin>

You could also declare just the user property maven.compiler.release:

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time the last one will not be enough as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.

Which is the best way to specify the JDK version?

Java 8 and below

Neither maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin is better. It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Java 9 and later

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

Can a constructor in Java be private?

Private Constructors can be defnied in the Java for the following reasons

  1. To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.

  2. It wont allow the class to be Subclassed

  3. This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.

  4. when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.

What is the shortcut in IntelliJ IDEA to find method / functions?

CTRL + F12 brings up the File Structure navigation menu, which lets you search for members of the currently open file.

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

How can I use the apply() function for a single column?

Although the given responses are correct, they modify the initial data frame, which is not always desirable (and, given the OP asked for examples "using apply", it might be they wanted a version that returns a new data frame, as apply does).

This is possible using assign: it is valid to assign to existing columns, as the documentation states (emphasis is mine):

Assign new columns to a DataFrame.

Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

In short:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

In [3]: df.assign(a=lambda df: df.a / 2)
Out[3]: 
      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

In [4]: df
Out[4]: 
    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9

Note that the function will be passed the whole dataframe, not only the column you want to modify, so you will need to make sure you select the right column in your lambda.

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

How to install pandas from pip on windows cmd?

install pip, securely download get-pip.py

Then run the following:

python get-pip.py

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

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

warning: assignment makes integer from pointer without a cast

The expression *src refers to the first character in the string, not the whole string. To reassign src to point to a different string tgt, use src = tgt;.

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Fling gesture detection on grid layout

To all: don't forget about case MotionEvent.ACTION_CANCEL:

it calls in 30% swipes without ACTION_UP

and its equal to ACTION_UP in this case

How do I skip a header from CSV files in Spark?

It's an option that you pass to the read() command:

context = new org.apache.spark.sql.SQLContext(sc)

var data = context.read.option("header","true").csv("<path>")

What’s the best way to check if a file exists in C++? (cross platform)

Another possibility consists in using the good() function in the stream:

#include <fstream>     
bool checkExistence(const char* filename)
{
     ifstream Infield(filename);
     return Infield.good();
}

How to know if an object has an attribute in Python

You can check whether object contains attribute by using hasattr builtin method.

For an instance if your object is a and you want to check for attribute stuff

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

The method signature itself is hasattr(object, name) -> bool which mean if object has attribute which is passed to second argument in hasattr than it gives boolean True or False according to the presence of name attribute in object.

What's the difference between event.stopPropagation and event.preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases.

preventDefault prevents the default action the browser makes on that event.

Examples

preventDefault

_x000D_
_x000D_
$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

stopPropagation

_x000D_
_x000D_
$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

With stopPropagation, only the button's click handler is called while the div's click handler never fires.

Where as if you use preventDefault, only the browser's default action is stopped but the div's click handler still fires.

Below are some docs on the DOM event properties and methods from MDN:

For IE9 and FF you can just use preventDefault & stopPropagation.

To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

Setup a Git server with msysgit on Windows

I just wanted to add my experiences with the PATH setup that Steve and timc mentions above: I got permission problems using shell tools (like mv and cp) having Git's shell executables first in the path.

Appending them after the existing PATH instead this solved my problems. Example:

GITPATH='/cygdrive/c/Program Files (x86)/Git/bin' GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core' PATH=${PATH}:${GITPATH}:${GITCOREPATH}

I guess CopSSH doesn't go along well with all of msysgit's shell executables...

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

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

Partial Dependency (Databases)

If there is a Relation R(ABC)

-----------
|A | B | C |
-----------
|a | 1 | x |
|b | 1 | x |
|c | 1 | x |
|d | 2 | y |
|e | 2 | y |
|f | 3 | z |
|g | 3 | z |
 ----------
Given,
F1: A --> B 
F2: B --> C

The Primary Key and Candidate Key is: A

As the closure of A+ = {ABC} or R --- So only attribute A is sufficient to find Relation R.

DEF-1: From Some Definitions (unknown source) - A partial dependency is a dependency when prime attribute (i.e., an attribute that is a part(or proper subset) of Candidate Key) determines non-prime attribute (i.e., an attribute that is not the part (or subset) of Candidate Key).

Hence, A is a prime(P) attribute and B, C are non-prime(NP) attributes.

So, from the above DEF-1,

CONSIDERATION-1:: F1: A --> B (P determines NP) --- It must be Partial Dependency.

CONSIDERATION-2:: F2: B --> C (NP determines NP) --- Transitive Dependency.

What I understood from @philipxy answer (https://stackoverflow.com/a/25827210/6009502) is...

CONSIDERATION-1:: F1: A --> B; Should be fully functional dependency because B is completely dependent on A and If we Remove A then there is no proper subset of (for complete clarification consider L.H.S. as X NOT BY SINGLE ATTRIBUTE) that could determine B.

For Example: If I consider F1: X --> Y where X = {A} and Y = {B} then if we remove A from X; i.e., X - {A} = {}; and an empty set is not considered generally (or not at all) to define functional dependency. So, there is no proper subset of X that could hold the dependency F1: X --> Y; Hence, it is fully functional dependency.

F1: A --> B If we remove A then there is no attribute that could hold functional dependency F1. Hence, F1 is fully functional dependency not partial dependency.

If F1 were, F1: AC --> B;
and F2 were, F2: C --> B; 
then on the removal of A;
C --> B that means B is still dependent on C; 
we can say F1 is partial dependecy.

So, @philipxy answer contradicts DEF-1 and CONSIDERATION-1 that is true and crystal clear.

Hence, F1: A --> B is Fully Functional Dependency not partial dependency.

I have considered X to show left hand side of functional dependency because single attribute couldn't have a proper subset of attributes. Here, I am considering X as a set of attributes and in current scenario X is {A}

-- For the source of DEF-1, please search on google you may be able to hit similar definitions. (Consider that DEF-1 is incorrect or do not work in the above-mentioned example).

Unable to run Java code with Intellij IDEA

Last resort option when nothing else seems to work: close and reopen IntelliJ.

My issue was with reverting a Git commit, which happened to change the Java SDK configured for the Project to a no longer installed version of the JDK. But fixing that back still didn't allow me to run the program. Restarting IntelliJ fixed this

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

To fix this install the specific typescript version 3.1.6

npm i [email protected] --save-dev --save-exact

How do I make a Windows batch script completely silent?

If you want that all normal output of your Batch script be silent (like in your example), the easiest way to do that is to run the Batch file with a redirection:

C:\Temp> test.bat >nul

This method does not require to modify a single line in the script and it still show error messages in the screen. To supress all the output, including error messages:

C:\Temp> test.bat >nul 2>&1

If your script have lines that produce output you want to appear in screen, perhaps will be simpler to add redirection to those lineas instead of all the lines you want to keep silent:

@ECHO OFF
SET scriptDirectory=%~dp0
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat
FOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (
del "%scriptDirectory%%%f"
)
ECHO
REM Next line DO appear in the screen
ECHO Script completed >con

Antonio

Error parsing yaml file: mapping values are not allowed here

I've seen this error in a similar situation to mentioned in Joe's answer:

description: Too high 5xx responses rate: {{ .Value }} > 0.05

We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:

description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'

Django - taking values from POST request

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Plot 3D data in R

Not sure why the code above did not work for the library rgl, but the following link has a great example with the same library. Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.

http://statisticsr.blogspot.de/2008/10/some-r-functions.html

########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system

library(rgl);
data(volcano)
dim(volcano)

peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));

zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()

ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)

title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)

sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));

axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))

ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);

title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();

Convert a python UTC datetime to a local datetime using only python standard library?

Building on Alexei's comment. This should work for DST too.

import time
import datetime

def utc_to_local(dt):
    if time.localtime().tm_isdst:
        return dt - datetime.timedelta(seconds = time.altzone)
    else:
        return dt - datetime.timedelta(seconds = time.timezone)

How do I combine 2 javascript variables into a string

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

stopPropagation vs. stopImmediatePropagation

Surprisingly, all other answers only say half the truth or are actually wrong!

  • e.stopImmediatePropagation() stops any further handler from being called for this event, no exceptions
  • e.stopPropagation() is similar, but does still call all handlers for this phase on this element if not called already

What phase?

E.g. a click event will always first go all the way down the DOM (called “capture phase”), finally reach the origin of the event (“target phase”) and then bubble up again (“bubble phase”). And with addEventListener() you can register multiple handlers for both capture and bubble phase independently. (Target phase calls handlers of both types on the target without distinguishing.)

And this is what the other answers are incorrect about:

  • quote: “event.stopPropagation() allows other handlers on the same element to be executed”
    • correction: if stopped in the capture phase, bubble phase handlers will never be reached, also skipping them on the same element
  • quote: “event.stopPropagation() [...] is used to stop executions of its corresponding parent handler only”
    • correction: if propagation is stopped in the capture phase, handlers on any children, including the target aren’t called either, not only parents
    • ...and: if propagation is stopped in the bubble phase, all capture phase handlers have already been called, including those on parents

A fiddle and mozilla.org event phase explanation with demo.

Laravel Eloquent compare date from datetime field

You can use this

whereDate('date', '=', $date)

If you give whereDate then compare only date from datetime field.

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

Custom alert and confirm box in jquery

Check the jsfiddle http://jsfiddle.net/CdwB9/3/ and click on delete

function yesnodialog(button1, button2, element){
  var btns = {};
  btns[button1] = function(){ 
      element.parents('li').hide();
      $(this).dialog("close");
  };
  btns[button2] = function(){ 
      // Do nothing
      $(this).dialog("close");
  };
  $("<div></div>").dialog({
    autoOpen: true,
    title: 'Condition',
    modal:true,
    buttons:btns
  });
}
$('.delete').click(function(){
    yesnodialog('Yes', 'No', $(this));
})

This should help you

How to wrap text in textview in Android

By setting android:maxEms to a given value together with android:layout_weight="1" will cause the TextView to wrap once it reaches the given length of the ems.

Subtract one day from datetime

To simply subtract one day from todays date:

Select DATEADD(day,-1,GETDATE())

(original post used -7 and was incorrect)

How to get value of Radio Buttons?

To Get the Value when the radio button is checked

if (rdbtnSN06.IsChecked == true)
{
string RadiobuttonContent =Convert.ToString(rdbtnSN06.Content.ToString());
}
else
{
string RadiobuttonContent =Convert.ToString(rdbtnSN07.Content.ToString());
}

How to configure encoding in Maven?

It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8 not effective. To avoid having issues with encoding you should follow the following simple rules

  1. Set maven encoding, as described above:
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  1. Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8 exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.

  2. Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:

$ file --mime F_PRDAUFT.dsv

  1. Force clients/server set encoding explicitly in requests/responses, here are examples:
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")

Hope this will be useful to someone.

Logical operators for boolean indexing in Pandas

When you say

(a['x']==1) and (a['y']==10)

You are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to boolean values.

NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.

Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.

Instead, you must be explicit, by calling the empty(), all() or any() method to indicate which behavior you desire.

In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the & binary operator performs:

(a['x']==1) & (a['y']==10)

returns a boolean array.


By the way, as alexpmil notes, the parentheses are mandatory since & has a higher operator precedence than ==. Without the parentheses, a['x']==1 & a['y']==10 would be evaluated as a['x'] == (1 & a['y']) == 10 which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10). That is an expression of the form Series and Series. The use of and with two Series would again trigger the same ValueError as above. That's why the parentheses are mandatory.

Changing background colour of tr element on mouseover

tr:hover td {background-color:#000;}

Where am I? - Get country

Here is a complete solution based on the LocationManager and as fallbacks the TelephonyManager and the Network Provider's locations. I used the above answer from @Marco W. for the fallback part(great answer as itself!).

Note: the code contains PreferencesManager, this is a helper class that saves and loads data from SharedPrefrences. I'm using it to save the country to S"P, I'm only getting the country if it is empty. For my product I don't really care for all the edge cases(user travels abroad and so on).

public static String getCountry(Context context) {
    String country = PreferencesManager.getInstance(context).getString(COUNTRY);
    if (country != null) {
        return country;
    }

    LocationManager locationManager = (LocationManager) PiplApp.getInstance().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (location == null) {
            log.w("Couldn't get location from network and gps providers")
            return
        }
        Geocoder gcd = new Geocoder(context, Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);

            if (addresses != null && !addresses.isEmpty()) {
                country = addresses.get(0).getCountryName();
                if (country != null) {
                    PreferencesManager.getInstance(context).putString(COUNTRY, country);
                    return country;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    country = getCountryBasedOnSimCardOrNetwork(context);
    if (country != null) {
        PreferencesManager.getInstance(context).putString(COUNTRY, country);
        return country;
    }
    return null;
}


/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 *
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
private static String getCountryBasedOnSimCardOrNetwork(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    } catch (Exception e) {
    }
    return null;
}

Android background music service

Theres an excellent tutorial on this subject at HelloAndroid regarding this very subject. Infact it was the first hit i got on google. You should try googling before asking here, as it is good practice.

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

Change color of Back button in navigation bar

Use this code in AppDelegate class, inside of didFinishLaunchingWithOptions.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

UINavigationBar.appearance().tintColor = .white

}

How to extract the first two characters of a string in shell scripting?

You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed and awk and (almost) no one else offered solutions based on them, I offer you these:

echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'

and

echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'

The awk one ought to be fairly obvious, but here's an explanation of the sed one:

  • substitute "s/"
  • the group "()" of two of any characters ".." starting at the beginning of the line "^" and followed by any character "." repeated zero or more times "*" (the backslashes are needed to escape some of the special characters)
  • by "/" the contents of the first (and only, in this case) group (here the backslash is a special escape referring to a matching sub-expression)
  • done "/"

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

As others said, you simply put :not(.class). For CSS selectors, I recommend visiting this link, it's been very helpful throughout my journey: https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

div:not(.success) {
  color: red;
}

The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

*:not(p) {
  color: green;
}

ImportError: No Module Named bs4 (BeautifulSoup)

Just tagging onto Balthazar's answer. Running

pip install BeautifulSoup4

did not work for me. Instead use

pip install beautifulsoup4

Hibernate Query By Example and Projections

Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).

getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();

I've never used the alaistToBean, but I just read about it. You could also just loop over the results..

List<Object> rows = criteria.list();
for(Object r: rows){
  Object[] row = (Object[]) r;
  Type t = ((<Type>) row[0]);
}

If you have to you can manually populate User yourself that way.

Its sort of hard to look into the issue without some more information to diagnose the issue.

Using LINQ to concatenate strings

There are various alternative answers at this previous question - which admittedly was targeting an integer array as the source, but received generalised answers.

take(1) vs first()

It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo')), it will emit an error if the stream completes before a value that passes the predicate is emitted.

take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:

const subject$ = new Subject();

// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));

// never does anything
subject$.take(1).subscribe(console.log);

subject$.complete();

Another example, using a predicate:

const observable$ = of(1, 2, 3);

// logs "no elements in sequence" when the observable completes
observable$
 .first((value) => value > 5)
 .subscribe(null, (err) => console.log(err.message));

// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
observable$
 .filter((value) => value > 5);
 .take(1)
 .subscribe(console.log);

As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:

Throws an error if defaultValue was not provided and a matching element is not found.

The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy lifecycle hook:

class MyComponent implements OnInit, OnDestroy {
  private stream$: Subject = someDelayedStream();
  private destroy$ = new Subject();

  ngOnInit() {
    this.stream$
      .takeUntil(this.destroy$)
      .first()
      .subscribe(doSomething);
  }

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

The code looks harmless at first, but problems arise when the component in destroyed before stream$ can emit a value. Because I'm using first(), an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1) in almost all places where I would have previously used first().

filter(fn).take(1) is a bit more verbose than first(fn), but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.

Also important to note: The same applies for last() and takeLast(1).

reference

List of Stored Procedures/Functions Mysql Command Line

SHOW PROCEDURE STATUS;
SHOW FUNCTION STATUS;

How to make remote REST call inside Node.js? any CURL?

Warning: As of Feb 11th 2020, request is fully deprecated.

If you implement with form-data, for more info (https://tanaikech.github.io/2017/07/27/multipart-post-request-using-node.js):

var fs = require('fs');
var request = require('request');
request.post({
  url: 'https://slack.com/api/files.upload',
  formData: {
    file: fs.createReadStream('sample.zip'),
    token: '### access token ###',
    filetype: 'zip',
    filename: 'samplefilename',
    channels: 'sample',
    title: 'sampletitle',
  },
}, function (error, response, body) {
  console.log(body);
});

How to do a HTTP HEAD request from the windows command line?

If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

TELNET server_name 80

followed by:

HEAD /virtual/directory/file.ext

or

GET /virtual/directory/file.ext

depending on if you want just the header (HEAD) or the full contents (GET)

How to check if a network port is open on linux?

Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:

from contextlib import closing
import socket
class example:
    def __init__():

       self.machine_ip = socket.gethostbyname(socket.gethostname())
       self.ready:bool = self.check_socket()

    def check_socket(self)->bool:
        result:bool = True
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        modbus_tcp_port:int = 502
        if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
            result = False
        return result

Querying DynamoDB by date

Updated Answer:

DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.

For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.

For more on DynamoDB secondary indexes see the secondary index documentation

Original Answer:

DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.

You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.

If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.

How to create byte array from HttpPostedFile

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

Event handlers for Twitter Bootstrap dropdowns?

Here you go, options have values, label and css classes that gets reflected on parent element upon selection.

_x000D_
_x000D_
$(document).on('click','.update_app_status', function (e) {
            let $div = $(this).parent().parent(); 
            let $btn = $div.find('.vBtnMain');
            let $btn2 = $div.find('.vBtnArrow');
            let cssClass = $(this).data('status_class');
            let status_value = $(this).data('status_value');
            let status_label = $(this).data('status_label');
            $btn.html(status_label);
            $btn.removeClass();
            $btn2.removeClass();
            $btn.addClass('btn btn-sm vBtnMain '+cssClass);
            $btn2.addClass('btn btn-sm vBtnArrow dropdown-toggle dropdown-toggle-split '+cssClass);
            $div.removeClass('show');
            $div.find('.dropdown-menu').removeClass('show');
            e.preventDefault();
            return false;
    });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


  

   <div class="btn-group">
   <button type="button" class="btn btn-sm vBtnMain btn-warning">Awaiting Review</button>
   <button type="button" class="btn btn-sm vBtnArrow btn-warning dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
       <span class="sr-only">Toggle Dropdown</span>
   </button>
   <div class="dropdown-menu dropdown-menu-right">
     <a class="dropdown-item update_app_status" data-status_class="btn-warning" data-status_value="1" data-status_label="Awaiting Review" href="#">Awaiting Review</a>
     <a class="dropdown-item update_app_status" data-status_class="btn-info" data-status_value="2" data-status_label="Reviewed" href="#">Reviewed</a>
     <a class="dropdown-item update_app_status" data-status_class="btn-dark" data-status_value="3" data-status_label="Contacting" href="#">Contacting</a>
     <a class="dropdown-item update_app_status" data-status_class="btn-success" data-status_value="4" data-status_label="Hired" href="#">Hired</a>
     <a class="dropdown-item update_app_status" data-status_class="btn-danger" data-status_value="5" data-status_label="Rejected" href="#">Rejected</a>
   </div>
   </div>
_x000D_
_x000D_
_x000D_

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

It's unclear to me why there is all of this complexity in the answer. Sure there are lots of ways you can do this, with QueryStrings, headers and options... but what I believe to be the best practice is simple. You request a plain URL (ex: http://yourstartup.com/api/cars) and in return you get JSON. You get JSON with the proper response header:

Content-Type: application/json

In looking for an answer to this very same question, I found this thread, and had to keep going because this accepted answer doesn't work exactly. I did find an answer which I feel is just too simple not to be the best one:

Set the default WebAPI formatter

I'll add my tip here as well.

WebApiConfig.cs

namespace com.yourstartup
{
  using ...;
  using System.Net.Http.Formatting;
  ...
  config.Formatters.Clear(); //because there are defaults of XML..
  config.Formatters.Add(new JsonMediaTypeFormatter());
}

I do have a question of where the defaults (at least the ones I am seeing) come from. Are they .NET defaults, or perhaps created somewhere else (by someone else on my project). Anways, hope this helps.

Get array of object's keys

Use Object.keys:

_x000D_
_x000D_
var foo = {_x000D_
  'alpha': 'puffin',_x000D_
  'beta': 'beagle'_x000D_
};_x000D_
_x000D_
var keys = Object.keys(foo);_x000D_
console.log(keys) // ['alpha', 'beta'] _x000D_
// (or maybe some other order, keys are unordered).
_x000D_
_x000D_
_x000D_

This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.

The ES5-shim has a implementation of Object.keys you can steal

C++11 reverse range-based for-loop

You could simply use BOOST_REVERSE_FOREACH which iterates backwards. For example, the code

#include <iostream>
#include <boost\foreach.hpp>

int main()
{
    int integers[] = { 0, 1, 2, 3, 4 };
    BOOST_REVERSE_FOREACH(auto i, integers)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

generates the following output:

4

3

2

1

0

Single selection in RecyclerView

This simple one worked for me

private RadioButton lastCheckedRB = null;
...
@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
  holder.priceRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
        if (lastCheckedRB != null && lastCheckedRB != checked_rb) {
            lastCheckedRB.setChecked(false);
        }
        //store the clicked radiobutton
        lastCheckedRB = checked_rb;
    }
});

How do I merge a git tag onto a branch

Just complementing the answer.

Merging the last tag on a branch:

git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))

Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0

How to prevent rm from reporting that a file was not found?

-f is the correct flag, but for the test operator, not rm

[ -f "$THEFILE" ] && rm "$THEFILE"

this ensures that the file exists and is a regular file (not a directory, device node etc...)

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

How we can bold only the name in table td tag not the value

Wrap the name in a span, give it a class and assign a style to that class:

<td><span class="names">Name text you want bold</span> rest of your text</td>

style:

.names { font-weight: bold; }

How do I escape a reserved word in Oracle?

Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.

CREATE TABLE table AS ...

Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!

How to rename with prefix/suffix?

You could use the rename(1) command:

rename 's/(.*)$/new.$1/' original.filename

Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

How to automatically generate unique id in SQL like UID12345678?

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju

PHP decoding and encoding json with unicode characters

$json = array('tag' => 'Odómetro'); // Original array
$json = json_encode($json); // {"Tag":"Od\u00f3metro"}
$json = json_decode($json); // Od\u00f3metro becomes  Odómetro
echo $json->{'tag'}; // Odómetro
echo utf8_decode($json->{'tag'}); // Odómetro

You were close, just use utf8_decode.

os.walk without digging into directories below

This is a nice python example

def walk_with_depth(root_path, depth):
        if depth < 0:
            for root, dirs, files in os.walk(root_path):
                yield [root, dirs[:], files]

            return

        elif depth == 0:
            return

        base_depth = root_path.rstrip(os.path.sep).count(os.path.sep)
        for root, dirs, files in os.walk(root_path):
            yield [root, dirs[:], files]

            cur_depth = root.count(os.path.sep)
            
            if base_depth + depth <= cur_depth:
                del dirs[:]

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

A method to count occurrences in a list

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

How to compare types

http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx

Console.WriteLine("typeField is a {0}", typeField.GetType());

which would give you something like

typeField is a String

typeField is a DateTime

or

http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx

html select option separator

If it's WebKit-only, you can use <hr> to create a real separator.

http://code.google.com/p/chromium/issues/detail?id=99534

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

It took me few hours to solved this because all off the settings that I found here about this error were the same but it still didn't work. The problem was tha I had a folder in my web service from which the file should be send to WinCE device, after converting that folder to an application with Classic.NetAppPool it started to work.

wamp server mysql user id and password

Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link. alt text

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Simply adding docker as a supplementary group for the jenkins user

sudo usermod -a -G docker jenkins

is not always enough when using a Docker image as the Jenkins Agent. That is, if your Jenkinsfile starts with pipeline{agent{dockerfile or pipeline{agent{image:

pipeline {
    agent {
        dockerfile {
            filename 'Dockerfile.jenkinsAgent'
        }
    }
    stages {

This is because Jenkins performs a docker run command, which results in three problems.

  • The Agent will (probably) not have the Docker programs installed.
  • The Agent will not have access to the Docker daemon socket, and so will try to run Docker-in-Docker, which is not recommended.
  • Jenkins gives the numeric user ID and numeric group ID that the Agent should use. The Agent will not have any supplementary groups, because docker run does not do a login to the container (it's more like a sudo).

Installing Docker for the Agent

Making the Docker programs available within the Docker image simply requires running the Docker installation steps in your Dockerfile:

# Dockerfile.jenkinsAgent
FROM debian:stretch-backports
# Install Docker in the image, which adds a docker group
RUN apt-get -y update && \
 apt-get -y install \
   apt-transport-https \
   ca-certificates \
   curl \
   gnupg \
   lsb-release \
   software-properties-common

RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/debian \
   $(lsb_release -cs) \
   stable"

RUN apt-get -y update && \
 apt-get -y install \
   docker-ce \
   docker-ce-cli \
   containerd.io

...

Sharing the Docker daemon socket

As has been said before, fixing the second problem means running the Jenkins Docker container so it shares the Docker daemon socket with the Docker daemon that is outside the container. So you need to tell Jenkins to run the Docker container with that sharing, thus:

pipeline {
    agent {
        dockerfile {
            filename 'Dockerfile.jenkinsAgent'
            args '-v /var/run/docker.sock:/var/run/docker.sock'
        }
    }

Setting UIDs and GIDs

The ideal fix to the third problem would be set up supplementary groups for the Agent. That does not seem possible. The only fix I'm aware of is to run the Agent with the Jenkins UID and the Docker GID (the socket has group write permission and is owned by root.docker). But in general, you do not know what those IDs are (they were allocated when the useradd ... jenkins and groupadd ... docker ran when Jenkins and Docker were installed on the host). And you can not simply tell Jenkins to user user jenkins and group docker

args '-v /var/run/docker.sock:/var/run/docker.sock -u jenkins:docker'

because that tells Docker to use the user and group that are named jenkins and docker within the image, and your Docker image probably does not have the jenkins user and group, and even if it did there would be no guarantee it would have the same UID and GID as the host, and there is similarly no guarantee that the docker GID is the same

Fortunately, Jenkins runs the docker build command for your Dockerfile in a script, so you can do some shell-script magic to pass through that information as Docker build arguments:

pipeline {
    agent {
        dockerfile {
            filename 'Dockerfile.jenkinsAgent'
            additionalBuildArgs  '--build-arg JENKINSUID=`id -u jenkins` --build-arg JENKINSGID=`id -g jenkins` --build-arg DOCKERGID=`stat -c %g /var/run/docker.sock`'
            args '-v /var/run/docker.sock:/var/run/docker.sock -u jenkins:docker'
        }
    }

That uses the id command to get the UID and GID of the jenkins user and the stat command to get information about the Docker socket.

Your Dockerfile can use that information to setup a jenkins user and docker group for the Agent, using groupadd, groupmod and useradd:

# Dockerfile.jenkinsAgent
FROM debian:stretch-backports
ARG JENKINSUID
ARG JENKINSGID
ARG DOCKERGID
...
# Install Docker in the image, which adds a docker group
RUN apt-get -y update && \
 apt-get -y install \
   apt-transport-https \
   ca-certificates \
   curl \
   gnupg \
   lsb-release \
   software-properties-common

RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/debian \
   $(lsb_release -cs) \
   stable"

RUN apt-get -y update && \
 apt-get -y install \
   docker-ce \
   docker-ce-cli \
   containerd.io

...
# Setup users and groups
RUN groupadd -g ${JENKINSGID} jenkins
RUN groupmod -g ${DOCKERGID} docker
RUN useradd -c "Jenkins user" -g ${JENKINSGID} -G ${DOCKERGID} -M -N -u ${JENKINSUID} jenkins

Looking to understand the iOS UIViewController lifecycle

As of iOS 6 and onward. The new diagram is as follows:

enter image description here

How to make an HTTP POST web request

When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.

Check if textbox has empty value

if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

Restart pods when configmap updates in Kubernetes?

The best way I've found to do it is run Reloader

It allows you to define configmaps or secrets to watch, when they get updated, a rolling update of your deployment is performed. Here's an example:

You have a deployment foo and a ConfigMap called foo-configmap. You want to roll the pods of the deployment every time the configmap is changed. You need to run Reloader with:

kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

Then specify this annotation in your deployment:

kind: Deployment
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
  name: foo
...

jQuery input button click event listener

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Why do we have to override the equals() method in Java?

The default behavior for java.lang.Object is to compare references, but that's not appropriate for every kind of object. There are things called Value Objects (like BigDecimal or String), where objects with the same value are considered to be interchangeable, so the default behavior of equals is not desirable. Those kinds of objects have to implement equals and hashcode based on the value that the object takes on.

How do I check if file exists in jQuery or pure JavaScript?

For a client computer this can be achieved by:

try
{
  var myObject, f;
  myObject = new ActiveXObject("Scripting.FileSystemObject");
  f =   myObject.GetFile("C:\\img.txt");
  f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
  alert("file does not exist")
}

This is my program to transfer a file to a specific location and shows alert if it does not exist

How to load CSS Asynchronously

If you need to programmatically and asynchronously load a CSS link:

// https://www.filamentgroup.com/lab/load-css-simpler/
function loadCSS(href, position) {
  const link = document.createElement('link');
  link.media = 'print';
  link.rel = 'stylesheet';
  link.href = href;
  link.onload = () => { link.media = 'all'; };
  position.parentNode.insertBefore(link, position);
}

Get a file name from a path

I implemented a function that might meet your needs. It is based on string_view's constexpr function find_last_of (since c++17) which can be calculated at compile time

constexpr const char* base_filename(const char* p) {
    const size_t i = std::string_view(p).find_last_of('/');
    return std::string_view::npos == i ? p : p + i + 1 ;
}

//in the file you used this function
base_filename(__FILE__);

How do I use regex in a SQLite query?

If you are using php you can add any function to your sql statement by using: SQLite3::createFunction. In PDO you can use PDO::sqliteCreateFunction and implement the preg_match function within your statement:

See how its done by Havalite (RegExp in SqLite using Php)

Exception: Can't bind to 'ngFor' since it isn't a known native property

I forgot to annotate my component with "@Input" (Doh!)

book-list.component.html (Offending code):

<app-book-item
  *ngFor="let book of book$ | async"
  [book]="book">  <-- Can't bind to 'book' since it isn't a known property of 'app-book-item'
</app-book-item>

Corrected version of book-item.component.ts:

import { Component, OnInit, Input } from '@angular/core';

import { Book } from '../model/book';
import { BookService } from '../services/book.service';

@Component({
  selector: 'app-book-item',
  templateUrl: './book-item.component.html',
  styleUrls: ['./book-item.component.css']
})
export class BookItemComponent implements OnInit {

  @Input()
  public book: Book;

  constructor(private bookService: BookService)  { }

  ngOnInit() {}

}

javascript password generator

If you have lodash >= 4.0 in place there is a more elegant way of doing it

var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
  return _.sampleSize(chars, length).join('');
}

How to delete duplicates on a MySQL table?

After running into this issue myself, on a huge database, I wasn't completely impressed with the performance of any of the other answers. I want to keep only the latest duplicate row, and delete the rest.

In a one-query statement, without a temp table, this worked best for me,

DELETE e.*
FROM employee e
WHERE id IN
 (SELECT id
   FROM (SELECT MIN(id) as id
          FROM employee e2
          GROUP BY first_name, last_name
          HAVING COUNT(*) > 1) x);

The only caveat is that I have to run the query multiple times, but even with that, I found it worked better for me than the other options.

Storing Python dictionaries

If you're after serialization, but won't need the data in other programs, I strongly recommend the shelve module. Think of it as a persistent dictionary.

myData = shelve.open('/path/to/file')

# Check for values.
keyVar in myData

# Set values
myData[anotherKey] = someValue

# Save the data for future use.
myData.close()

How to check if dropdown is disabled?

The legacy solution, before 1.6, was to use .attr and handle the returned value as a bool. The main problem is that the returned type of .attr has changed to string, and therefore the comparison with == true is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).

With 1.6 .prop was introduced, which returns a bool.

Nevertheless, I suggest to use .is(), as the returned type is intrinsically bool, like:

$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');

Furthermore .is() is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last'), .is(':visible'), ... please see documentation on selectors).

How do I update Homebrew?

  • cd /usr/local
  • git status
  • Discard all the changes (unless you actually want to try to commit to Homebrew - you probably don't)
  • git status til it's clean
  • brew update

I got error "The DELETE statement conflicted with the REFERENCE constraint"

To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.

To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

Last non-empty cell in a column

Here is another option: =OFFSET($A$1;COUNTA(A:A)-1;0)

How to center a button within a div?

_x000D_
_x000D_
div {
    text-align : center;
}
button {
    width: 50%;
    margin: 1rem auto;
}
_x000D_
<div style="width:100%; height:100%; border: 1px solid">
  <button type="button">hello</button>
</div>
_x000D_
_x000D_
_x000D_

This is what I mostly do.
I think bootstrap also uses this in "mx-auto".

Send multiple checkbox data to PHP via jQuery ajax()

var myCheckboxes = new Array();
$("input:checked").each(function() {
   data['myCheckboxes[]'].push($(this).val());
});

You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push

From a Sybase Database, how I can get table description ( field names and types)?

For Sybase ASE, sp_columns table_name will return all the table metadata you are looking for.

How do I vertically center text with CSS?

Absolute Positioning and Stretching

As with the method above this one begins by setting positioning on the parent and child elements as relative and absolute respectively. From there things differ.

In the code below I’ve once again used this method to center the child both horizontally and vertically, though you can use the method for vertical centering only.

HTML

<div id="parent">
    <div id="child">Content here</div>
</div>

CSS

#parent {position: relative;}
#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

The idea with this method is to try to get the child element to stretch to all four edges by setting the top, bottom, right, and left vales to 0. Because our child element is smaller than our parent elements it can’t reach all four edges.

Setting auto as the margin on all four sides however causes opposite margins to be equal and displays our child div in the center of the parent div.

Unfortunately the above won’t work in Internet Explorer 7 and below, and like the previous method the content inside the child div can grow too large, causing it to be hidden.

Capture Image from Camera and Display in Activity

Here you can open camera or gallery and set the selected image into imageview

private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView;  // imageview
private int GALLERY = 1, CAMERA = 2;

Add permissions in manifest

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

In onCreate()

    requestMultiplePermissions(); // check permission 

    circleImageView = findViewById(R.id.profile_image);
    circleImageView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showPictureDialog();
        }
    });

Show options dialog box (to select image from camera or gallery)

private void showPictureDialog() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                        case 1:
                            takePhotoFromCamera();
                            break;
                    }
                }
            });
    pictureDialog.show();
}

Get photo from Gallery

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY);
}

Get photo from Camera

private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);
}

Once the image is get selected or captured then ,

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                String path = saveImage(bitmap);
                Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
                circleImageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
            }
        }

    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        circleImageView.setImageBitmap(thumbnail);
        saveImage(thumbnail);
        Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
    }
}

Now its time to store the picture

public String saveImage(Bitmap myBitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
    if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.
        wallpaperDirectory.mkdirs();
    }

    try {
        File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        MediaScannerConnection.scanFile(this,
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);
        fo.close();
        Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

        return f.getAbsolutePath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return "";
}

Request permission

    private void requestMultiplePermissions() {
    Dexter.withActivity(this)
            .withPermissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                        Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                    }

                    if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
                        // show alert dialog navigating to Settings
                        //openSettingsDialog();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).
            withErrorListener(new PermissionRequestErrorListener() {
                @Override
                public void onError(DexterError error) {
                    Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                }
            })
            .onSameThread()
            .check();
}

Passing an integer by reference in Python

Not exactly passing a value directly, but using it as if it was passed.

x = 7
def my_method():
    nonlocal x
    x += 1
my_method()
print(x) # 8

Caveats:

  • nonlocal was introduced in python 3
  • If the enclosing scope is the global one, use global instead of nonlocal.

PHP date add 5 year to current date

Try this code and add next Days, Months and Years

// current month: Aug 2018
$n = 2;
for ($i = 0; $i <= $n; $i++){
   $d = strtotime("$i days");
   $x = strtotime("$i month");
   $y = strtotime("$i year");
   echo "Dates : ".$dates = date('d M Y', "+$d days");
   echo "<br>";
   echo "Months : ".$months = date('M Y', "+$x months");
   echo '<br>';
   echo "Years : ".$years = date('Y', "+$y years");
   echo '<br>';
}

Argument Exception "Item with Same Key has already been added"

Clear the dictionary before adding any items to it. I don't know how a dictionary of one object affects another's during assignment but I got the error after creating another object with the same key,value pairs.

NB: If you are going to add items in a loop just make sure you clear the dictionary before entering the loop.

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

Check if key exists in JSON object using jQuery

if you have an array

var subcategories=[{name:"test",desc:"test"}];

function hasCategory(nameStr) {
        for(let i=0;i<subcategories.length;i++){
            if(subcategories[i].name===nameStr){
                return true;
            }
        }
        return false;
    }

if you have an object

var category={name:"asd",test:""};

if(category.hasOwnProperty('name')){//or category.name!==undefined
   return true;
}else{
   return false;
}

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Get the name of an object's type

Here is a solution that I have come up with that solves the shortcomings of instanceof. It can check an object's types from cross-windows and cross-frames and doesn't have problems with primitive types.

function getType(o) {
    return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1];
}
function isInstance(obj, type) {
    var ret = false,
    isTypeAString = getType(type) == "String",
    functionConstructor, i, l, typeArray, context;
    if (!isTypeAString && getType(type) != "Function") {
        throw new TypeError("type argument must be a string or function");
    }
    if (obj !== undefined && obj !== null && obj.constructor) {
        //get the Function constructor
        functionConstructor = obj.constructor;
        while (functionConstructor != functionConstructor.constructor) {
            functionConstructor = functionConstructor.constructor;
        }
        //get the object's window
        context = functionConstructor == Function ? self : functionConstructor("return window")();
        //get the constructor for the type
        if (isTypeAString) {
            //type is a string so we'll build the context (window.Array or window.some.Type)
            for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) {
                context = context[typeArray[i]];
            }
        } else {
            //type is a function so execute the function passing in the object's window
            //the return should be a constructor
            context = type(context);
        }
        //check if the object is an instance of the constructor
        if (context) {
            ret = obj instanceof context;
            if (!ret && (type == "Number" || type == "String" || type == "Boolean")) {
                ret = obj.constructor == context
            }
        }
    }
    return ret;
}

isInstance requires two parameters: an object and a type. The real trick to how it works is that it checks if the object is from the same window and if not gets the object's window.

Examples:

isInstance([], "Array"); //true
isInstance("some string", "String"); //true
isInstance(new Object(), "Object"); //true

function Animal() {}
function Dog() {}
Dog.prototype = new Animal();

isInstance(new Dog(), "Dog"); //true
isInstance(new Dog(), "Animal"); //true
isInstance(new Dog(), "Object"); //true
isInstance(new Animal(), "Dog"); //false

The type argument can also be a callback function which returns a constructor. The callback function will receive one parameter which is the window of the provided object.

Examples:

//"Arguments" type check
var args = (function() {
    return arguments;
}());

isInstance(args, function(w) {
    return w.Function("return arguments.constructor")();
}); //true

//"NodeList" type check
var nl = document.getElementsByTagName("*");

isInstance(nl, function(w) {
    return w.document.getElementsByTagName("bs").constructor;
}); //true

One thing to keep in mind is that IE < 9 does not provide the constructor on all objects so the above test for NodeList would return false and also a isInstance(alert, "Function") would return false.

TypeError: 'float' object not iterable

use

range(count)

int and float are not iterable

How to validate a date?

My function returns true if is a valid date otherwise returns false :D

_x000D_
_x000D_
function isDate  (day, month, year){_x000D_
 if(day == 0 ){_x000D_
  return false;_x000D_
 }_x000D_
 switch(month){_x000D_
  case 1: case 3: case 5: case 7: case 8: case 10: case 12:_x000D_
   if(day > 31)_x000D_
    return false;_x000D_
   return true;_x000D_
  case 2:_x000D_
   if (year % 4 == 0)_x000D_
    if(day > 29){_x000D_
     return false;_x000D_
    }_x000D_
    else{_x000D_
     return true;_x000D_
    }_x000D_
   if(day > 28){_x000D_
    return false;_x000D_
   }_x000D_
   return true;_x000D_
  case 4: case 6: case 9: case 11:_x000D_
   if(day > 30){_x000D_
    return false;_x000D_
   }_x000D_
   return true;_x000D_
  default:_x000D_
   return false;_x000D_
 }_x000D_
}_x000D_
_x000D_
console.log(isDate(30, 5, 2017));_x000D_
console.log(isDate(29, 2, 2016));_x000D_
console.log(isDate(29, 2, 2015));
_x000D_
_x000D_
_x000D_

How can I convert a long to int in Java?

For small values, casting is enough:

long l = 42;
int i = (int) l;

However, a long can hold more information than an int, so it's not possible to perfectly convert from long to int, in the general case. If the long holds a number less than or equal to Integer.MAX_VALUE you can convert it by casting without losing any information.

For example, the following sample code:

System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );

long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);

int y = (int) x;
System.out.println("int y=" + y);

produces the following output on my machine:

largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648

Notice the negative sign on y. Because x held a value one larger than Integer.MAX_VALUE, int y was unable to hold it. In this case, it wrapped around to the negative numbers.

If you wanted to handle this case yourself, you might do something like:

if ( x > (long)Integer.MAX_VALUE ) {
    // x is too big to convert, throw an exception or something useful
}
else {
    y = (int)x;
}

All of this assumes positive numbers. For negative numbers, use MIN_VALUE instead of MAX_VALUE.