Programs & Examples On #Google caja

Caja is a tool for safely embedding active Web content including HTML, JavaScript, and CSS.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.

When do you use map vs flatMap in RxJava?

I just wanted to add that with flatMap, you don't really need to use your own custom Observable inside the function and you can rely on standard factory methods/operators:

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(final File file) {
        try {
            String json = new Gson().toJson(new FileReader(file), Object.class);
            return Observable.just(json);
        } catch (FileNotFoundException ex) {
            return Observable.<String>error(ex);
        }
    }
});

Generally, you should avoid throwing (Runtime-) exceptions from onXXX methods and callbacks if possible, even though we placed as many safeguards as we could in RxJava.

Origin <origin> is not allowed by Access-Control-Allow-Origin

In case anyone searching for the solution , if you are using express here is the quick solution .

const express = require('express')
const cors = require('cors')
const app = express()

1) install cors using npm npm install cors --save

2) import it [require ] const cors = require('cors')

3) use it as middleware app.use(cors())

for details insatll and usage of cors . That is it, hopefully it works.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.

Jquery bind double click and single click separately

var singleClickTimer = 0; //define a var to hold timer event in parent scope
jqueryElem.click(function(e){ //using jquery click handler
    if (e.detail == 1) { //ensure this is the first click
        singleClickTimer = setTimeout(function(){ //create a timer
            alert('single'); //run your single click code
        },250); //250 or 1/4th second is about right
    }
});

jqueryElem.dblclick(function(e){ //using jquery dblclick handler
    clearTimeout(singleClickTimer); //cancel the single click
    alert('double'); //run your double click code
});

What type of hash does WordPress use?

By default wordpress uses MD5. You can upgrade it to blowfish or extended DES.

http://frameworkgeek.com/support/what-hash-does-wordpress-use/

Oracle SQL - select within a select (on the same table!)

This is something I'd use the LAG function for:

SELECT eh.gc_staff_number,
       eh.start_date,
       LAG(eh.end_date) OVER (PARTITION BY eh.gc_staff_number
                                  ORDER BY eh.end_date) AS prev_end_date
  FROM EMPLOYMENT_HISTORY eh
 WHERE eh.current_flag = 'Y'

If you wanted to peek a row ahead, you'd use the LEAD function.

Compatibility:

To my knowledge, this is supported 9i+ but I haven't confirmed that 8i is supported like the documentation claims.

LEAD and LAG are finally ANSI, but only Oracle and PostgreSQL v8.4+ support them currently.

How to remove all leading zeroes in a string

Ajay Kumar offers the simplest echo +$numString; I use these:

echo round($val = "0005");
echo $val = 0005;
    //both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
    //output 648370000075845, no need to care about the other zeroes in the number
    //like with regex or comparative functions. Works w/wo single/double quotes

Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions. I saw that in php.net, don't remember where.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

To hide static cells in UITable:

  1. Add this method:

In your UITableView controller delegate class:

Objective-C:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if(cell == self.cellYouWantToHide)
        return 0; //set the hidden cell's height to 0

    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

Swift:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)

    if cell == self.cellYouWantToHide {
        return 0
    }

    return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

This method will get called for each cell in the UITable. Once it calls it for the cell you want to hide, we set its height to 0. We identify the target cell by creating an outlet for it:

  1. In the designer, create an outlet for the cell(s) you want to hide. The outlet for one such cell is called "cellYouWantToHide" above.
  2. Check "Clip Subviews" in the IB for the cells you want to hide. The cells you are hiding need to have ClipToBounds = YES. Otherwise the text will pile up in the UITableView.

How to track down access violation "at address 00000000"

It's probably because you are directly or indirectly through a library call accessing a NULL pointer. In this particular case, it looks like you've jumped to a NULL address, which is a b bit hairier.

In my experience, the easiest way to track these down are to run it with a debugger, and dump a stack trace.

Alternatively, you can do it "by hand" and add lots of logging until you can track down exactly which function (and possibly LOC) this violation occurred in.

Take a look at Stack Tracer, which might help you improve your debugging.

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

Package structure for a Java project?

The way i usually have my hierarchy of folder-

  • Project Name
    • src
    • bin
    • tests
    • libs
    • docs

What is difference between Errors and Exceptions?

In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.

How to show live preview in a small popup of linked page on mouse over on link?

I have done a little plugin to show a iframe window to preview a link. Still in beta version. Maybe it fits your case: https://github.com/Fischer-L/previewbox.

Why does javascript replace only first instance when using replace?

You need to set the g flag to replace globally:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

Otherwise only the first occurrence will be replaced.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

starting file download with JavaScript

In relation to the top answer I have a possible solution to the security risk.

<?php
     if(isset($_GET['path'])){
         if(in_array($_GET['path'], glob("*/*.*"))){
             header("Content-Type: application/octet-stream");
             header("Content-Disposition: attachment; filename=".$_GET['path']);
             readfile($_GET['path']);
         }
     }
?>

Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.

~Note: Javascript / HTML~

HTML:

<iframe id="download" style="display:none"></iframe>

and

<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">

JavaScript:

<script type="text/javascript">
    <!--
        function ChangeSource(path){
            document.getElementByID('download').src = 'path_to_php?path=' + document_path;
        }
    -->
</script>

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()

if (authUserList != null && _list.Count() > 0)
    _list = _list.Where(l => authUserList.Contains(l.CreateUserId));

Is there any simple way to convert .xls file to .csv file? (Excel)

I integrate the @mattmc3 aswer. If you want to convert a xlsx file you should use this connection string (the string provided by matt works for xls formats, not xlsx):

var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO\"", excelFilePath);

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How do I add space between items in an ASP.NET RadioButtonList

Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.

Preferably you do this by setting the class. Add the CssClass="myrblclass" attribute to your list declaration.

You can also add attributes to the items programmatically, which will come out the other side.

rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")

This may be better for you since you can add that attribute for all but the last one.

Renaming files using node.js

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

How to add minutes to my Date

In order to avoid any dependency you can use java.util.Calendar as follow:

    Calendar now = Calendar.getInstance();
    now.add(Calendar.MINUTE, 10);
    Date teenMinutesFromNow = now.getTime();

In Java 8 we have new API:

    LocalDateTime dateTime = LocalDateTime.now().plus(Duration.of(10, ChronoUnit.MINUTES));
    Date tmfn = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());

How to change the project in GCP using CLI commands

add this below script in ~/.bashrc and do please replace project name(projectname) with whatever the name you needed

function s() {
        array=($(gcloud projects list | awk /projectname/'{print $1}'))
        for i in "${!array[@]}";do printf "%s=%s\n" "$i" "${array[$i]}";done
        echo -e "\nenter the number to switch project:\c"
        read project
        [ ${array[${project}]} ] || { echo "project not exists"; exit 2; }
        printf "\n**** Running: gcloud config set project ${array[${project}]} *****\n\n"
        eval "gcloud config set project ${array[${project}]}"
}

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

Hidden Features of C#?

Object.ReferenceEquals Method

Determines whether the specified Object instances are the same instance.

Parameters:

  • objA: System.Object - The first Object to compare.
  • objB: System.Object - The second Object to compare.

Example:

 object o = null;
 object p = null;
 object q = new Object();

 Console.WriteLine(Object.ReferenceEquals(o, p));
 p = q;
 Console.WriteLine(Object.ReferenceEquals(p, q));
 Console.WriteLine(Object.ReferenceEquals(o, p));

Difference to "==" and ".Equals":

Basically, Equals() tests of object A has the same content as object B.

The method System.Object.ReferenceEquals() always compares references. Although a class can provide its own behavior for the equality operator (below), that re-defined operator isn't invoked if the operator is called via a reference to System.Object.

For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string.

See also this answer to another question ("How do I check for nulls in an ‘==’ operator overload without infinite recursion?").

Check if a column contains text using SQL

Leaving database modeling issues aside. I think you can try

SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0

But ISNUMERIC returns 1 for any value that seems numeric including things like -1.0e5

If you want to exclude digit-only studentids, try something like

SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

pros and cons between os.path.exists vs os.path.isdir

os.path.exists(path) Returns True if path refers to an existing path. An existing path can be regular files (http://en.wikipedia.org/wiki/Unix_file_types#Regular_file), but also special files (e.g. a directory). So in essence this function returns true if the path provided exists in the filesystem in whatever form (notwithstanding a few exceptions such as broken symlinks).

os.path.isdir(path) in turn will only return true when the path points to a directory

How do I pass a string into subprocess.Popen (using the stdin argument)?

I figured out this workaround:

>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()

Is there a better one?

"Large data" workflows using pandas

As noted by others, after some years an 'out-of-core' pandas equivalent has emerged: dask. Though dask is not a drop-in replacement of pandas and all of its functionality it stands out for several reasons:

Dask is a flexible parallel computing library for analytic computing that is optimized for dynamic task scheduling for interactive computational workloads of “Big Data” collections like parallel arrays, dataframes, and lists that extend common interfaces like NumPy, Pandas, or Python iterators to larger-than-memory or distributed environments and scales from laptops to clusters.

Dask emphasizes the following virtues:

  • Familiar: Provides parallelized NumPy array and Pandas DataFrame objects
  • Flexible: Provides a task scheduling interface for more custom workloads and integration with other projects.
  • Native: Enables distributed computing in Pure Python with access to the PyData stack.
  • Fast: Operates with low overhead, low latency, and minimal serialization necessary for fast numerical algorithms
  • Scales up: Runs resiliently on clusters with 1000s of cores Scales down: Trivial to set up and run on a laptop in a single process
  • Responsive: Designed with interactive computing in mind it provides rapid feedback and diagnostics to aid humans

and to add a simple code sample:

import dask.dataframe as dd
df = dd.read_csv('2015-*-*.csv')
df.groupby(df.user_id).value.mean().compute()

replaces some pandas code like this:

import pandas as pd
df = pd.read_csv('2015-01-01.csv')
df.groupby(df.user_id).value.mean()

and, especially noteworthy, provides through the concurrent.futures interface a general infrastructure for the submission of custom tasks:

from dask.distributed import Client
client = Client('scheduler:port')

futures = []
for fn in filenames:
    future = client.submit(load, fn)
    futures.append(future)

summary = client.submit(summarize, futures)
summary.result()

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

How do I set the default page of my application in IIS7?

Just go to web.config file and add following

<system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="Path of your Page" />
      </files>
    </defaultDocument>
</system.webServer>

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

Proxy Basic Authentication in C#: HTTP 407 error

here is the correct way of using proxy along with creds..

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = request.Proxy;                    
if (proxy != null)
{
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
    Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the 
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;

Thanks everyone for help... :)

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

EXC_I386_GPFLT is surely referring to "General Protection fault", which is the x86's way to tell you that "you did something that you are not allowed to do". It typically DOESN'T mean that you access out of memory bounds, but it could be that your code is going out of bounds and causing bad code/data to be used in a way that makes for an protection violation of some sort.

Unfortunately it can be hard to figure out exactly what the problem is without more context, there are 27 different causes listed in my AMD64 Programmer's Manual, Vol 2 from 2005 - by all accounts, it is likely that 8 years later would have added a few more.

If it is a 64-bit system, a plausible scenario is that your code is using a "non-canonical pointer" - meaning that a 64-bit address is formed in such a way that the upper 16 bits of the address aren't all copies of the top of the lower 48 bits (in other words, the top 16 bits of an address should all be 0 or all 1, based on the bit just below 16 bits). This rule is in place to guarantee that the architecture can "safely expand the number of valid bits in the address range". This would indicate that the code is either overwriting some pointer data with other stuff, or going out of bounds when reading some pointer value.

Another likely causes is unaligned access with an SSE register - in other word, reading a 16-byte SSE register from an address that isn't 16-byte aligned.

There are, as I said, many other possible reasons, but most of those involve things that "normal" code wouldn't be doing in a 32- or 64-bit OS (such as loading segment registers with invalid selector index or writing to MSR's (model specific registers)).

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

How to allow only one radio button to be checked?

They need to all have the same name.

Validating with an XML schema in Python

There are two ways(actually there are more) that you could do this.
1. using lxml
pip install lxml

from lxml import etree, objectify
from lxml.etree import XMLSyntaxError

def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):
    try:
        schema = etree.XMLSchema(file=xsd_file)
        parser = objectify.makeparser(schema=schema)
        objectify.fromstring(some_xml_string, parser)
        print "YEAH!, my xml file has validated"
    except XMLSyntaxError:
        #handle exception here
        print "Oh NO!, my xml file does not validate"
        pass

xml_file = open('my_xml_file.xml', 'r')
xml_string = xml_file.read()
xml_file.close()

xml_validator(xml_string, '/path/to/my_schema_file.xsd')
  1. Use xmllint from the commandline. xmllint comes installed in many linux distributions.

>> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml

Cron and virtualenv

This is a solution that has worked well for me.

source /root/miniconda3/etc/profile.d/conda.sh && \
conda activate <your_env> && \
python <your_application> &

I am using miniconda with Conda version 4.7.12 on a Ubuntu 18.04.3 LTS.

I am able to place the above inside a script and run it via crontab as well without any trouble.

Java Date vs Calendar

tl;dr

advise the current "best practice" around Date and Calendar

is it best to always favour Calendar over Date

Avoid these legacy classes entirely. Use java.time classes instead.

  • For a moment in UTC, use Instant
    (the modern equivalent of Date)
  • For a moment in a particular time zone, use ZonedDateTime
    (the modern equivalent of GregorianCalendar)
  • For a moment in a particular offset-from-UTC, use OffsetDateTime
    (no equivalent in legacy classes)
  • For a date-time (not a moment) with unknown time zone or offset, use LocalDateTime
    (no equivalent in legacy classes)

Table of all date-time types in Java, both modern and legacy

Details

The Answer by Ortomala Lokni is right to suggest using the modern java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.). But that Answer suggests the wrong class as equivalent (see my comment on that Answer).

Using java.time

The java.time classes are a vast improvement over the legacy date-time classes, night-and-day difference. The old classes are poorly-designed, confusing, and troublesome. You should avoid the old classes whenever possible. But when you need to convert to/from the old/new, you can do so by calling new methods add to the old classes.

For much more information on conversion, see my Answer and nifty diagram to another Question, Convert java.util.Date to what “java.time” type?.

Searching Stack Overflow gives many hundreds of example Questions and Answers on using java.time. But here is a quick synopsis.

Instant

Get the current moment with an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();

ZonedDateTime

To see that same simultaneous moment through the lens of some particular region’s wall-clock time, apply a time zone (ZoneId) to get a ZonedDateTime.

Time zone

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();

Offset

A time zone is a region’s history of changes in its offset-from-UTC. But sometimes you are given only an offset without the full zone. In that case, use the OffsetDateTime class.

ZoneOffset offset = ZoneOffset.parse( "+05:30" );
OffsetDateTime odt = instant.atOffset( offset );

Use of a time zone is preferable over use of a mere offset.

LocalDateTime

The “Local” in the Local… classes means any locality, not a particular locality. So the name can be counter-intuitive.

LocalDateTime, LocalDate, and LocalTime purposely lack any information about offset or time zone. So they do not represent actual moments, they are not points on the timeline. When in doubt or in confusion, use ZonedDateTime rather than LocalDateTime. Search Stack Overflow for much more discussion.

Strings

Do not conflate date-time objects with strings that represent their value. You can parse a string to get a date-time object, and you can generate a string from a date-time object. But the string is never the date-time itself.

Learn about standard ISO 8601 formats, used by default in the java.time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to display Toast in Android?

This worked for me:

Toast.makeText(getBaseContext(), "your text here" , Toast.LENGTH_SHORT ).show();

Set NOW() as Default Value for datetime datatype?

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

it should work for updates too

Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

Submit form and stay on same page?

When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

How to call code behind server method from a client side JavaScript function?

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

aspx code:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}

Properties private set;

This is normally the case then the ID is not a natural part of the entity, but a database artifact that needs be abstracted away.

It is a design decision - to only allow setting the ID during construction or through method invocation, so it is managed internally by the class.

You can write a setter yourself, assuming you have a backing field:

private int Id = 0;
public void SetId (int id)
{
  this.Id = id;
}

Or through a constructor:

private int Id = 0;
public Person (int id)
{
  this.Id = id;
}

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

Navigation Drawer (Google+ vs. YouTube)

Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:

https://github.com/jaredsburrows/RibbonMenu

What's the Purpose

  • Ease of Access: Allow easy access to a menu that slides in and out
  • Ease of Implementation: Update the same screen using minimal amount of code
  • Independency: Does not require support libraries such as ActionBarSherlock
  • Customization: Easy to change colors and menus

What's New

  • Changed the sliding animation to match Facebook and Google+ apps
  • Added standard ActionBar (you can chose to use ActionBarSherlock)
  • Used menuitem to open the Menu
  • Added ability to update ListView on main Activity
  • Added 2 ListViews to the Menu, similiar to Facebook and Google+ apps
  • Added a AutoCompleteTextView and a Button as well to show examples of implemenation
  • Added method to allow users to hit the 'back button' to hide the menu when it is open
  • Allows users to interact with background(main ListView) and the menu at the same time unlike the Facebook and Google+ apps!

ActionBar with Menu out

ActionBar with Menu out

ActionBar with Menu out and search selected

ActionBar with Menu out and search selected

Is it possible to get all arguments of a function as single object inside that function?

Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.

How do you check "if not null" with Eloquent?

Eloquent has a method for that (Laravel 4.*/5.*);

Model::whereNotNull('sent_at')

Laravel 3:

Model::where_not_null('sent_at')

Compare two files and write it to "match" and "nomatch" files

Since 12,200 people have looked at this question and not got an answer:

DFSORT and SyncSort are the predominant Mainframe sorting products. Their control cards have many similarities, and some differences.

JOINKEYS FILE=F1,FIELDS=(key1startpos,7,A)              
JOINKEYS FILE=F2,FIELDS=(key2startpos,7,A)              
JOIN UNPAIRED,F1,F2
REFORMAT FIELDS=(F1:1,5200,F2:1,5200)                         
SORT FIELDS=COPY    

A "JOINKEYS" is made of three Tasks. Sub-Task 1 is the first JOINKEYS. Sub-Task 2 is the second JOINKEYS. The Main Task follows and is where the joined data is processed. In the example above it is a simple COPY operation. The joined data will simply be written to SORTOUT.

The JOIN statement defines that as well as matched records, UNPAIRED F1 and F2 records are to be presented to the Main Task.

The REFORMAT statement defines the record which will be presented to the Main Task. A more efficient example, imagining that three fields are required from F2, is:

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100)

Each of the fields on F2 is defined with a start position and a length.

The record which is then processed by the Main task is 5311 bytes long, and the fields from F2 can be referenced by 5201,10,5211,1,5212,100 with the F1 record being 1,5200.

A better way achieve the same thing is to reduce the size of F2 with JNF2CNTL.

//JNF2CNTL DD *
  INREC BUILD=(207,1,10,30,1,5100,100)

Some installations of SyncSort do not support JNF2CNTL, and even where supported (from Syncsort MFX for z/OS release 1.4.1.0 onwards), it is not documented by SyncSort. For users of 1.3.2 or 1.4.0 an update is available from SyncSort to provide JNFnCNTL support.

It should be noted that JOINKEYS by default SORTs the data, with option EQUALS. If the data for a JOINKEYS file is already in sequence, SORTED should be specified. For DFSORT NOSEQCHK can also be specified if sequence-checking is not required.

 JOINKEYS FILE=F1,FIELDS=(key1startpos,7,A),SORTED,NOSEQCHK

Although the request is strange, as the source file won't be able to be determined, all unmatched records are to go to a separate output file.

With DFSORT, there is a matching-marker, specified with ? in the REFORMAT:

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100,?)

This increases the length of the REFORMAT record by one byte. The ? can be specified anywhere on the REFORMAT record, and need not be specified. The ? is resolved by DFSORT to: B, data sourced from Both files; 1, unmatched record from F1; 2, unmatched record from F2.

SyncSort does not have the match marker. The absence or presence of data on the REFORMAT record has to be determined by values. Pick a byte on both input records which cannot contain a particular value (for instance, within a number, decide on a non-numeric value). Then specify that value as the FILL character on the REFORMAT.

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100),FILL=C'$'

If position 1 on F1 cannot naturally have "$" and position 20 on F2 cannot either, then those two positions can be used to establish the result of the match. The entire record can be tested if necessary, but sucks up more CPU time.

The apparent requirement is for all unmatched records, from either F1 or F2, to be written to one file. This will require a REFORMAT statement which includes both records in their entirety:

DFSORT, output unmatched records:

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200,?)

  OUTFIL FNAMES=NOMATCH,INCLUDE=(10401,1,SS,EQ,C'1,2'),
        IFTHEN=(WHEN=(10401,1,CH,EQ,C'1'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

SyncSort, output unmatched records:

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200),FILL=C'$'

  OUTFIL FNAMES=NOMATCH,INCLUDE=(1,1,CH,EQ,C'$',
                          OR,5220,1,CH,EQ,C'$'),
        IFTHEN=(WHEN=(1,1,CH,EQ,C'$'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

The coding for SyncSort will also work with DFSORT.

To get the matched records written is easy.

  OUTFIL FNAMES=MATCH,SAVE

SAVE ensures that all records not written by another OUTFIL will be written here.

There is some reformatting required, to mainly output data from F1, but to select some fields from F2. This will work for either DFSORT or SyncSort:

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

The whole thing, with arbitrary starts and lengths is:

DFSORT

  JOINKEYS FILE=F1,FIELDS=(1,7,A)              
  JOINKEYS FILE=F2,FIELDS=(20,7,A)    

  JOIN UNPAIRED,F1,F2

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200,?)                         

  SORT FIELDS=COPY    

  OUTFIL FNAMES=NOMATCH,INCLUDE=(10401,1,SS,EQ,C'1,2'),
        IFTHEN=(WHEN=(10401,1,CH,EQ,C'1'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

SyncSort

  JOINKEYS FILE=F1,FIELDS=(1,7,A)              
  JOINKEYS FILE=F2,FIELDS=(20,7,A)              

  JOIN UNPAIRED,F1,F2

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200),FILL=C'$'                         

  SORT FIELDS=COPY    

  OUTFIL FNAMES=NOMATCH,INCLUDE=(1,1,CH,EQ,C'$',
                          OR,5220,1,CH,EQ,C'$'),
        IFTHEN=(WHEN=(1,1,CH,EQ,C'$'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

How to copy commits from one branch to another?

git cherry-pick : Apply the changes introduced by some existing commits

Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick operations.

When we use cherry-pick, we should add commits on branch B in the same chronological order that the commits appear in Branch A.

cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated

git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z

Example of workflow :

enter image description here

We can use cherry-pick with options

-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.

-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.

Here an interesting article concerning cherry-pick.

Request Monitoring in Chrome

In the step 5 of Phil, "Resources" is no longer available in the new version of the Chrome. You need to click the page icon just beside the Ajax page listed in the bottom pane with the columns of Name, Method, Status, ...

Then it will show you more panels where you will find the error messages.

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

How do I scroll to an element within an overflowed Div?

The accepted answer only works with direct children of the scrollable element, while the other answers didn't centered the child in the scrollable element.

Example HTML:

<div class="scrollable-box">
    <div class="row">
        <div class="scrollable-item">
            Child 1
        </div>
        <div class="scrollable-item">
            Child 2
        </div>
        <div class="scrollable-item">
            Child 3
        </div>
        <div class="scrollable-item">
            Child 4
        </div>
        <div class="scrollable-item">
            Child 5
        </div>
        <div class="scrollable-item">
            Child 6
        </div>
        <div class="scrollable-item">
            Child 7
        </div>
        <div class="scrollable-item">
            Child 8
        </div>
        <div class="scrollable-item">
            Child 9
        </div>
        <div class="scrollable-item">
            Child 10
        </div>
        <div class="scrollable-item">
            Child 11
        </div>
        <div class="scrollable-item">
            Child 12
        </div>
        <div class="scrollable-item">
            Child 13
        </div>
        <div class="scrollable-item">
            Child 14
        </div>
        <div class="scrollable-item">
            Child 15
        </div>
        <div class="scrollable-item">
            Child 16
        </div>
    </div>
</div>

<style>
.scrollable-box {
    width: 800px;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    border: 1px solid #444;
}
.scrollable-item {
    font-size: 20px;
    padding: 10px;
    text-align: center;
}
</style>

Build a small jQuery plugin:

$.fn.scrollDivToElement = function(childSel) {
    if (! this.length) return this;

    return this.each(function() {
        let parentEl = $(this);
        let childEl = parentEl.find(childSel);

        if (childEl.length > 0) {
            parentEl.scrollTop(
                parentEl.scrollTop() - parentEl.offset().top + childEl.offset().top - (parentEl.outerHeight() / 2) + (childEl.outerHeight() / 2)
            );
        }
    });
};

Usage:

$('.scrollable-box').scrollDivToElement('.scrollable-item:eq(12)');

Explanation:

  1. parentEl.scrollTop(...) sets current vertical position of the scroll bar.

  2. parentEl.scrollTop() gets the current vertical position of the scroll bar.

  3. parentEl.offset().top gets the current coordinates of the parentEl relative to the document.

  4. childEl.offset().top gets the current coordinates of the childEl relative to the document.

  5. parentEl.outerHeight() / 2 gets the outer height divided in half (because we want it centered) of the child element.

  6. when used:

$(parent).scrollDivToElement(child);

The parent is the scrollable div and it can be a string or a jQuery object of the DOM element.
The child is any child that you want to scroll to and it can be a string or a jQuery object of the DOM element.

Codepen demo

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Rows("2:2").Select
ActiveWindow.FreezePanes = True

This is the easiest way to freeze the top row. The rule for FreezePanes is it will freeze the upper left corner from the cell you selected. For example, if you highlight C10, it will freeze between columns B and C, rows 9 and 10. So when you highlight Row 2, it actually freeze between Rows 1 and 2 which is the top row.

Also, the .SplitColumn or .SplitRow will split your window once you unfreeze it which is not the way I like.

Reliable way for a Bash script to get the full path to itself

I'm surprised that the realpath command hasn't been mentioned here. My understanding is that it is widely portable / ported.

Your initial solution becomes:

SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`

And to leave symbolic links unresolved per your preference:

SCRIPT=`realpath -s $0`
SCRIPTPATH=`dirname $SCRIPT`

How do I get an element to scroll into view, using jQuery?

My UI has a vertical scrolling list of thumbs within a thumbbar The goal was to make the current thumb right in the center of the thumbbar. I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.

markup:

<ul id='thumbbar'>
    <li id='thumbbar-123'></li>
    <li id='thumbbar-124'></li>
    <li id='thumbbar-125'></li>
</ul>

jquery:

// scroll the current thumb bar thumb into view
heightbar   = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar   = $('#thumbbar').scrollTop();


$('#thumbbar').animate({
    scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});

pandas: best way to select all columns whose names start with X

Now that pandas' indexes support string operations, arguably the simplest and best way to select columns beginning with 'foo' is just:

df.loc[:, df.columns.str.startswith('foo')]

Alternatively, you can filter column (or row) labels with df.filter(). To specify a regular expression to match the names beginning with foo.:

>>> df.filter(regex=r'^foo\.', axis=1)
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

To select only the required rows (containing a 1) and the columns, you can use loc, selecting the columns using filter (or any other method) and the rows using any:

>>> df.loc[(df == 1).any(axis=1), df.filter(regex=r'^foo\.', axis=1).columns]
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
5     6.8         1             0        5          0

How to easily resize/optimize an image size with iOS?

Best way to scale images without losing the aspect ratio (i.e. without stretching the imgage) is to use this method:

//to scale images without changing aspect ratio
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {

    float width = newSize.width;
    float height = newSize.height;

    UIGraphicsBeginImageContext(newSize);
    CGRect rect = CGRectMake(0, 0, width, height);

    float widthRatio = image.size.width / width;
    float heightRatio = image.size.height / height;
    float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;

    width = image.size.width / divisor;
    height = image.size.height / divisor;

    rect.size.width  = width;
    rect.size.height = height;

    //indent in case of width or height difference
    float offset = (width - height) / 2;
    if (offset > 0) {
        rect.origin.y = offset;
    }
    else {
        rect.origin.x = -offset;
    }

    [image drawInRect: rect];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return smallImage;

}

Add this method to your Utility class so you can use it throughout your project, and access it like so:

xyzImageView.image = [Utility scaleImage:yourUIImage toSize:xyzImageView.frame.size];

This method takes care of scaling while maintaining aspect ratio. It also adds indents to the image in case the scaled down image has more width than height (or vice versa).

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

Change the Arrow buttons in Slick slider

The Best way i Found to do that is this. You can remove my HTML and place yours there.

$('.home-banner-slider').slick({
    dots: false,
    infinite: true,
    autoplay: true,
    autoplaySpeed: 3000,
    speed: 300,
    slidesToScroll: 1,
    arrows: true,
    prevArrow: '<div class="slick-prev"><i class="fa fa-angle-left" aria-hidden="true"></i></div>',
    nextArrow: '<div class="slick-next"><i class="fa fa-angle-right" aria-hidden="true"></i></div>'
});

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Finally I solve the issues using below code. This type of error will happen when there is a mismatch between In/Out parameter as declare in procedure and in java code declareParameters. Here we need to defined oracle return tab

public class ManualSaleStoredProcedureDao {

private SimpleJdbcCall getAllSytemUsers;

public List<SystemUser> getAllSytemUsers(String clientCode) {

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("pi_client_code", clientCode);
    Map<String, Object> result = getAllSytemUsers.execute(in);
    @SuppressWarnings("unchecked")
    List<SystemUser> systemUsers = (List<SystemUser>) result
            .get(VSCConstants.GET_SYSTEM_USER_OUT_PARAM1);
    return systemUsers;

}

public void setDataSource(DataSource dataSource) {

    getAllSytemUsers = new SimpleJdbcCall(dataSource)
            .withSchemaName(VSCConstants.SCHEMA)
            .withProcedureName(VSCConstants.GET_SYSTEM_USER_PROC_NAME)
            .declareParameters(
                    new SqlParameter(
                            "pi_client_code",
                            OracleTypes.NUMBER,
                            "pi_client_code"),
                    new SqlInOutParameter(
                            "po_system_users",
                            OracleTypes.ARRAY,
                            "T_SYSTEM_USER_TAB",
                            new OracleSystemUser()));

}

How do I get the XML SOAP request of an WCF Web service request?

OperationContext.Current.RequestContext.RequestMessage 

this context is accesible server side during processing of request. This doesn`t works for one-way operations

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

PHP Checking if the current date is before or after a set date

I have used this one and it served the purpose:

if($date < date("Y-m-d") ) {
                echo "Date is in the past";}

BR

Decoding base64 in batch

Here's a batch file, called base64encode.bat, that encodes base64.

@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con 
(
  set base64tmp=base64.tmp
  certutil -encode "%1" %base64tmp% > nul
  findstr /v /c:- %base64tmp%
  erase %base64tmp%
) > %base64out%

How do I set the version information for an existing .exe, .dll?

verpatch is good, but doesn't handle unicode characters...
try ResourceLib

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

Difference between DOMContentLoaded and load events

Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.

// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);

function doStuff(){
    //
}
if(isIE){
    // play it safe, very few users, exec ur JS when all resources are loaded
    window.onload=function(){doStuff();}
} else {
    // add event listener to trigger your function when DOMContentLoaded
    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',doStuff);
    } else {
        // DOMContentLoaded already loaded, so better trigger your function
        doStuff();
    }
}

How to download a file from a URL in C#?

Try using this:

private void downloadFile(string url)
{
     string file = System.IO.Path.GetFileName(url);
     WebClient cln = new WebClient();
     cln.DownloadFile(url, file);
}

encapsulation vs abstraction real world example

Abstraction Means We focus on the essential qualities of some thing rather than one specific example and we automatically discard what is unimportant or irrelevant.

Example We are writing a bank account class,essential qualities of bank account are Opening date, Account title,Account number,Balance etc...

Encapsulation Means the idea of capsulation or surrounding some thing not just to keep the content together but also to protect and restrict form accessing out side.Along with secrecy It's about reducing dependencies between different parts of the application.

Example In our Bank account class Someone accessing the attribute of Balance and trying to change it ,Attempt can be successful if there is no encapsulation.

What is the correct syntax of ng-include?

You have to single quote your src string inside of the double quotes:

<div ng-include src="'views/sidepanel.html'"></div>

Source

Stopping an Android app from console

you can use the following from the device console: pm disable com.my.app.package which will kill it. Then use pm enable com.my.app.package so that you can launch it again.

HTML Mobile -forcing the soft keyboard to hide

I am fighting the soft keyboard on the Honeywell Dolphin 70e with Android 4.0.3. I don't need the keyboard because the input comes from the builtin barcode reader through the 'scanwedge', set to generate key events.

What I found was that the trick described in the earlier answers of:

input.blur();
input.focus();

works, but only once, right at page initialization. It puts the focus in the input element without showing the soft keyboard. It does NOT work later, e.g. after a TAB character in the suffix of the barcode causes the onblur or oninput event on the input element.

To read and process lots of barcodes, you may use a different postfix than TAB (9), e.g. 8, which is not interpreted by the browser. In the input.keydown event, use e.keyCode == 8 to detect a complete barcode to be processed.

This way, you initialize the page with focus in the input element, with keyboard hidden, all barcodes go to the input element, and the focus never leaves that element. Of course, the page cannot have other input elements (like buttons), because then you will not be able to return to the barcode input element with the soft keyboard hidden.

Perhaps reloading the page after a button click may be able to hide the keyboard. So use ajax for fast processing of barcodes, and use a regular asp.net button with PostBack to process a button click and reload the page to return focus to the barcode input with the keyboard hidden.

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

Checking if my Windows application is running

Enter a guid in your assembly data. Add this guid to the registry. Enter a reg key where the application read it's own name and add the name as value there.

The other task watcher read the reg key and knows the app name.

How do I add a new column to a Spark DataFrame (using PySpark)?

To add a column using a UDF:

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

from pyspark.sql.functions import udf
from pyspark.sql.types import *

def valueToCategory(value):
   if   value == 1: return 'cat1'
   elif value == 2: return 'cat2'
   ...
   else: return 'n/a'

# NOTE: it seems that calls to udf() must be after SparkContext() is called
udfValueToCategory = udf(valueToCategory, StringType())
df_with_cat = df.withColumn("category", udfValueToCategory("x1"))
df_with_cat.show()

## +---+---+-----+---------+
## | x1| x2|   x3| category|
## +---+---+-----+---------+
## |  1|  a| 23.0|     cat1|
## |  3|  B|-23.0|      n/a|
## +---+---+-----+---------+

Bootstrap button - remove outline on Chrome OS X

you can put this tag into your html.

<button class='btn btn-primary' onfocus='this.blur'>
     Button Text
</button>

I used on focus because onclick still displayed the glow for a microsecond and made a horrible looking flash in terms of using it. This seemed to get rid after all the css methods failed.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

You have to enable the features in Add/Remove Programs section of your Control Panel. Select "Turn Windows features on or off"

Can you split a stream into two streams?

A collector can be used for this.

  • For two categories, use Collectors.partitioningBy() factory.

This will create a Map from Boolean to List, and put items in one or the other list based on a Predicate.

Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output.

Also, no need for the iterator, not even in the heads-only example you provided.

  • Binary splitting looks like this:
Random r = new Random();

Map<Boolean, List<String>> groups = stream
    .collect(Collectors.partitioningBy(x -> r.nextBoolean()));

System.out.println(groups.get(false).size());
System.out.println(groups.get(true).size());
  • For more categories, use a Collectors.groupingBy() factory.
Map<Object, List<String>> groups = stream
    .collect(Collectors.groupingBy(x -> r.nextInt(3)));
System.out.println(groups.get(0).size());
System.out.println(groups.get(1).size());
System.out.println(groups.get(2).size());

In case the streams are not Stream, but one of the primitive streams like IntStream, then this .collect(Collectors) method is not available. You'll have to do it the manual way without a collector factory. It's implementation looks like this:

[Example 2.0 since 2020-04-16]

    IntStream    intStream = IntStream.iterate(0, i -> i + 1).limit(100000).parallel();
    IntPredicate predicate = ignored -> r.nextBoolean();

    Map<Boolean, List<Integer>> groups = intStream.collect(
            () -> Map.of(false, new ArrayList<>(100000),
                         true , new ArrayList<>(100000)),
            (map, value) -> map.get(predicate.test(value)).add(value),
            (map1, map2) -> {
                map1.get(false).addAll(map2.get(false));
                map1.get(true ).addAll(map2.get(true ));
            });

In this example I initialize the ArrayLists with the full size of the initial collection (if this is known at all). This prevents resize events even in the worst-case scenario, but can potentially gobble up 2*N*T space (N = initial number of elements, T = number of threads). To trade-off space for speed, you can leave it out or use your best educated guess, like the expected highest number of elements in one partition (typically just over N/2 for a balanced split).

I hope I don't offend anyone by using a Java 9 method. For the Java 8 version, look at the edit history.

Assign multiple values to array in C

Although in your case, just plain initialization will do, there's a trick to wrap the array into a struct (which can be initialized after declaration).

For example:

struct foo {
  GLfloat arr[10];
};
...
struct foo foo;
foo = (struct foo) { .arr = {1.0, ... } };

How do I create a GUI for a windows application using C++?

If you want to learn about win32, WTL http://wtl.sourceforge.net/ is the pretty lightweight equivalent to MFC, but you have to love template to use it.

If you want something simple MFC is already integrated with VS, also it has a large base of extra code and workarounds of know bugs in the net already.

Also Qt is really great framework it have a nice set of tools, dialog editor, themes, and a lot of other stuff, plus your application will be ready to be cross platform, although it will require some time to get accustomed.

You also have Gtk, wxWindow, and you will have no problems if you have already used it on linux.

How can I apply a function to every row/column of a matrix in MATLAB?

Adding to the evolving nature of the answer to this question, starting with r2016b, MATLAB will implicitly expand singleton dimensions, removing the need for bsxfun in many cases.

From the r2016b release notes:

Implicit Expansion: Apply element-wise operations and functions to arrays with automatic expansion of dimensions of length 1

Implicit expansion is a generalization of scalar expansion. With scalar expansion, a scalar expands to be the same size as another array to facilitate element-wise operations. With implicit expansion, the element-wise operators and functions listed here can implicitly expand their inputs to be the same size, as long as the arrays have compatible sizes. Two arrays have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. See Compatible Array Sizes for Basic Operations and Array vs. Matrix Operations for more information.

Element-wise arithmetic operators — +, -, .*, .^, ./, .\

Relational operators — <, <=, >, >=, ==, ~=

Logical operators — &, |, xor

Bit-wise functions — bitand, bitor, bitxor

Elementary math functions — max, min, mod, rem, hypot, atan2, atan2d

For example, you can calculate the mean of each column in a matrix A, and then subtract the vector of mean values from each column with A - mean(A).

Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed, better memory usage, and improved readability of code.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How do I test axios in Jest?

I've done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

How do I install Python libraries in wheel format?

You don't need to download exclusively from the website. Just make sure you have pip (which you probably will if you have python installed). Just open your Command Prompt (CMD) and run the command:

pip install pygame

It will automatically download the correct whl version of pygame compatible with your configuration of PC. Make sure you remember the version which appears while "downloading" as this is the compatible version of .whl packages you shall be looking for in the future.

Create a jTDS connection string

Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.

Follow these steps to make sure:

  • Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
  • Expand "SQL Server Network Configuration"
  • Go in "Protocols for SQLEXPRESS"
  • Enable TCP/IP

If you have any problem, check this blog post for details, as it contains screenshots and much more info.

Also check if the "SQL Server Browser" windows service is activated and running:

  • Go to Control Panel -> Administrative Tools -> Services
  • Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
  • Start it.

That's it.

After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.

Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JtdsSqlExpressInstanceConnect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        ResultSet rs = null;
        String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
        String driver = "net.sourceforge.jtds.jdbc.Driver";
        String userName = "user";
        String password = "password";
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Connected to the database!!! Getting table list...");
            DatabaseMetaData dbm = conn.getMetaData();
            rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
            while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
            rs.close();
        }
    }
}

And if you use Maven, add this to your pom.xml:

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.2.4</version>
</dependency>

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

How do I install Eclipse Marketplace in Eclipse Classic?

This is how i managed to install the thing in my indigo

  1. Help->Install New Software
  2. add this 'http://download.eclipse.org/mpc/indigo/" to the work with field
  3. Press enter key
  4. choose the marketplace.

follow the steps

pip not working in Python Installation in Windows 10

You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator. It's worked for me.

Could not find method compile() for arguments Gradle

Hope Below steps will help

Add the dependency to your project-level build.gradle:

classpath 'com.google.gms:google-services:3.0.0'

Add the plugin to your app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

app-level build.gradle:

dependencies {
        compile 'com.google.android.gms:play-services-auth:9.8.0'
}

Swapping pointers in C (char, int)

The first thing you need to understand is that when you pass something to a function, that something is copied to the function's arguments.

Suppose you have the following:

void swap1(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    assert(a == 17);
    assert(b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap1(x, y);
assert(x == 42);
assert(y == 17);
// no, they're not swapped!

The original variables will not be swapped, because their values are copied into the function's arguments. The function then proceeds to swap the values of those arguments, and then returns. The original values are not changed, because the function only swaps its own private copies.

Now how do we work around this? The function needs a way to refer to the original variables, not copies of their values. How can we refer to other variables in C? Using pointers.

If we pass pointers to our variables into the function, the function can swap the values in our variables, instead of its own argument copies.

void swap2(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap2(&x, &y); // give the function pointers to our variables
assert(x == 17);
assert(y == 42);
// yes, they're swapped!

Notice how inside the function we're not assigning to the pointers, but assigning to what they point to. And the pointers point to our variables x and y. The function is changing directly the values stored in our variables through the pointers we give it. And that's exactly what we needed.

Now what happens if we have two pointer variables and want to swap the pointers themselves (as opposed to the values they point to)? If we pass pointers, the pointers will simply be copied (not the values they point to) to the arguments.

void swap3(int* a, int* b) {
    int* temp = a;
    a = b;
    b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}
void swap4(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap3(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 42);
assert(y == 17);
// Didn't swap anything!
swap4(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 17);
assert(y == 42);
// Swapped the stored values instead!

The function swap3 only swaps its own private copies of our pointers that it gets in its arguments. It's the same issue we had with swap1. And swap4 is changing the values our variables point to, not the pointers! We're giving the function a means to refer to the variables x and y but we want them to refer to xp and yp.

How do we do that? We pass it their addresses!

void swap5(int** a, int** b) {
    int* temp = *a;
    *a = *b;
    *b = temp;
    assert(**a == 17);
    assert(**b == 42);
    // they're swapped!
}


int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap5(&xp, &yp);
assert(xp == &y);
assert(yp == &x);
assert(x == 42);
assert(y == 17);
// swapped only the pointers variables

This way it swaps our pointer variables (notice how xp now points to y) but not the values they point to. We gave it a way to refer to our pointer variables, so it can change them!

By now it should be easy to understand how to swap two strings in the form of char* variables. The swap function needs to receive pointers to char*.

void swapStrings(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
    assert(strcmp(*a, "world") == 0);
    assert(strcmp(*b, "Hello") == 0);
}

char* x = "Hello";
char* y = "world";
swapStrings(&x, &y);
assert(strcmp(x, "world") == 0);
assert(strcmp(y, "Hello") == 0);

Where is SQL Server Management Studio 2012?

You can get SSMS Express tools from here or full SQL Server Eval tools from here. MSDN/TechNet Downloads is currently the only place to get RTM versions (non-eval) of the SSMS 2012 toolset.

Note the first link now(dec 2017) points to 'Microsoft® SQL Server® 2012 Service Pack 2 (SP2) Express'. ssms 2014 and 2017 are still available.

CSS text-overflow in a table cell?

I solved this using an absolutely positioned div inside the cell (relative).

td {
    position: relative;
}
td > div {
    position: absolute;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;        
}

That's it. Then you can either add a top: value to the div or vertically center it:

td > div {      
    top: 0;
    bottom: 0;
    margin: auto 0;
    height: 1.5em; // = line height 
}

To get some space on the right side, you can reduce the max-width a little.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

Check if record exists from controller in Rails

business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end

How to rename array keys in PHP?

class DataHelper{

    private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
        foreach ($map as $old => $new) {
            $old = preg_replace('/([\.]{1}+)$/', '', trim($old));
            if ($new) {
                if (!is_array($new)) {
                    $array[$new] = $array[$old];
                    $storage[$level][$old] = $new;
                    unset($array[$old]);
                } else {
                    if (isset($array[$old])) {
                        static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
                    } else if (isset($array[$storage[$level][$old]])) {
                        static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
                    }
                }
            }
        }
    }

    /**
     * Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
     * @param type $map
     * @param type $array
    */
    public static function renameArrayKeys($map = [], &$array = [])
    {
        $storage = [];
        static::__renameArrayKeysRecursive($map, $array, 0, $storage);
        unset($storage);
    }
}

Use:

DataHelper::renameArrayKeys([
    'a' => 'b',
    'abc.' => [
       'abcd' => 'dcba'
    ]
], $yourArray);

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange.

UsedRange is highly unreliable as shown HERE

To find the last column which has data, use .Find and then subtract from it.

With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastCol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    Else
        lastCol = 1
    End If
End With

If lastCol > 8 Then
    'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8

    'The above becomes

    Debug.Print lastCol - 8
End If

Apply multiple functions to multiple groupby columns

New in version 0.25.0.

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
    In [79]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
       ....:                         'height': [9.1, 6.0, 9.5, 34.0],
       ....:                         'weight': [7.9, 7.5, 9.9, 198.0]})
       ....: 

    In [80]: animals
    Out[80]: 
      kind  height  weight
    0  cat     9.1     7.9
    1  dog     6.0     7.5
    2  cat     9.5     9.9
    3  dog    34.0   198.0

    In [81]: animals.groupby("kind").agg(
       ....:     min_height=pd.NamedAgg(column='height', aggfunc='min'),
       ....:     max_height=pd.NamedAgg(column='height', aggfunc='max'),
       ....:     average_weight=pd.NamedAgg(column='weight', aggfunc=np.mean),
       ....: )
       ....: 
    Out[81]: 
          min_height  max_height  average_weight
    kind                                        
    cat          9.1         9.5            8.90
    dog          6.0        34.0          102.75

pandas.NamedAgg is just a namedtuple. Plain tuples are allowed as well.

    In [82]: animals.groupby("kind").agg(
       ....:     min_height=('height', 'min'),
       ....:     max_height=('height', 'max'),
       ....:     average_weight=('weight', np.mean),
       ....: )
       ....: 
    Out[82]: 
          min_height  max_height  average_weight
    kind                                        
    cat          9.1         9.5            8.90
    dog          6.0        34.0          102.75

Additional keyword arguments are not passed through to the aggregation functions. Only pairs of (column, aggfunc) should be passed as **kwargs. If your aggregation functions requires additional arguments, partially apply them with functools.partial().

Named aggregation is also valid for Series groupby aggregations. In this case there’s no column selection, so the values are just the functions.

    In [84]: animals.groupby("kind").height.agg(
       ....:     min_height='min',
       ....:     max_height='max',
       ....: )
       ....: 
    Out[84]: 
          min_height  max_height
    kind                        
    cat          9.1         9.5
    dog          6.0        34.0

How to count the number of true elements in a NumPy bool array

That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

change html input type by JS?

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

How do I collapse sections of code in Visual Studio Code for Windows?

Code folding controls inside the editor to expand nodes of XML-structured documents and source code in VsCode

No technical tips here, just simple adjustments of the preferences of VsCode.

I managed to show code folding controls always in VsCode by going to Preferences and searching for 'folding'. Now just select to always show these controls. This works with the Typescript code and HTML of templates in the Angular 8 solution I tested it with.

This was tested with VsCode Insiders 1.37.0 running on a Windows 10 OS.

Show code folding controls always in VsCode

JavaScript file upload size validation

If you're using jQuery Validation, you could write something like this:

$.validator.addMethod(
    "maxfilesize",
    function (value, element) {
        if (this.optional(element) || ! element.files || ! element.files[0]) {
            return true;
        } else {
            return element.files[0].size <= 1024 * 1024 * 2;
        }
    },
    'The file size can not exceed 2MiB.'
);

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

This happens whenever you are trying to load a fragment but the activity has changed its state to onPause().This happens for example when you try to fetch data and load it to the activity but by the time the user has clicked some button and has moved to next activity.

You can solve this in two ways

You can use transaction.commitAllowingStateLoss() instead of transaction.commit() to load fragment but you may end up losing commit operation that is done.

or

Make sure that activity is in resume and not going to pause state when loading a fragment. Create a boolean and check if activity is not going to onPause() state.

@Override
public void onResume() {
    super.onResume();
    mIsResumed = true;
}

@Override
public void onPause() {
    mIsResumed = false;
    super.onPause();
}

then while loading fragment check if activity is present and load only when activity is foreground.

if(mIsResumed){
 //load the fragment
}

Python Tkinter clearing a frame

For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.

import tkinter as tk
from tkinter import *
root = tk.Tk()

frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")

lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)

def clearFrame():
    # destroy all widgets from frame
    for widget in frame.winfo_children():
       widget.destroy()
    
    # this will clear frame and frame will be empty
    # if you want to hide the empty panel then
    frame.pack_forget()

frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)

# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()

How can I scan barcodes on iOS?

The iPhone 4 camera is more than capabale of doing barcodes. The zebra crossing barcode library has a fork on github zxing-iphone. It's open-source.

Unique Key constraints for multiple columns in Entity Framework

Completing @chuck answer for using composite indices with foreign keys.

You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.

For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:

class Company
{
    public Guid Id { get; set; }
}

class Employee
{
    public Guid Id { get; set; }
    [Required]
    public String Name { get; set; }
    public Company Company  { get; set; }
    [Required]
    public Guid CompanyId { get; set; }
}

Now the mapping of the Employee class:

class EmployeeMap : EntityTypeConfiguration<Employee>
{
    public EmployeeMap ()
    {
        ToTable("Employee");

        Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(p => p.Name)
            .HasUniqueIndexAnnotation("UK_Employee_Name_Company", 0);
        Property(p => p.CompanyId )
            .HasUniqueIndexAnnotation("UK_Employee_Name_Company", 1);
        HasRequired(p => p.Company)
            .WithMany()
            .HasForeignKey(p => p.CompanyId)
            .WillCascadeOnDelete(false);
    }
}

Note that I also used @niaher extension for unique index annotation.

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

Change Twitter Bootstrap Tooltip content on click

Change the text by altering the text in the element directly. (does not update the tooltip position).

$('.tooltip-inner', $element.next()).html(newHtml);
$('.tooltip-inner', $element.next()).text(newText);

Change the text by destroying the old tooltip, then creating and showing a new one. (Causes the old one to fade out and the new one to fade in)

$element
.tooltip('destroy')
.tooltip({
    // Repeat previous options.
    title: newText,
})
.tooltip('show');

I'm using the top method to both animate the "Saving." message (using &nbsp so the tooltip does not change in size) and to change the text to "Done." (plus padding) when the request completes.

$element.tooltip({
  placement: 'left',
  title: 'Saving...',
  trigger: 'manual',
}).tooltip('show');

var parent = $element.parent();
var interval_id = setInterval(function(){
    var text = $('.tooltip-inner', parent).html();
    switch(text) {
    case 'Saving.&nbsp;&nbsp;': text = 'Saving..&nbsp;'; break;
    case 'Saving..&nbsp;': text = 'Saving...'; break;
    case 'Saving...': text = 'Saving.&nbsp;&nbsp;'; break;
    }
    $('.tooltip-inner', parent).html(text);
}, 250);

send_request( function(){
    // When the request is complete
    clearInterval(interval_id);
    $('.tooltip-inner', parent).html('Done.&nbsp;&nbsp;&nbsp;&nbsp;');
    setTimeout(function() {
        $element.tooltip('hide');
    }, 1500 /* Show "Done." for a bit */);
});

What is the difference between the HashMap and Map objects in Java?

Map is an interface that HashMap implements. The difference is that in the second implementation your reference to the HashMap will only allow the use of functions defined in the Map interface, while the first will allow the use of any public functions in HashMap (which includes the Map interface).

It will probably make more sense if you read Sun's interface tutorial

How can I start InternetExplorerDriver using Selenium WebDriver

static WebDriver driver;
System.setProperty("webdriver.ie.driver","C:\\(Path)\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("EnterURLHere");          
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

state machines tutorials

Unfortunately, most of the articles on state machines are written for C++ or other languages that have direct support for polymorphism as it's nice to model the states in an FSM implementation as classes that derive from an abstract state class.

However, it's pretty easy to implement state machines in C using either switch statements to dispatch events to states (for simple FSMs, they pretty much code right up) or using tables to map events to state transitions.

There are a couple of simple, but decent articles on a basic framework for state machines in C here:

Edit: Site "under maintenance", web archive links:

switch statement-based state machines often use a set of macros to 'hide' the mechanics of the switch statement (or use a set of if/then/else statements instead of a switch) and make what amounts to a "FSM language" for describing the state machine in C source. I personally prefer the table-based approach, but these certainly have merit, are widely used, and can be effective especially for simpler FSMs.

One such framework is outlined by Steve Rabin in "Game Programming Gems" Chapter 3.0 (Designing a General Robust AI Engine).

A similar set of macros is discussed here:

If you're also interested in C++ state machine implementations there's a lot more that can be found. I'll post pointers if you're interested.

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

How to add button tint programmatically

If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:

myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))

You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:

fun MaterialButton.changeColor(color: Int) {
    this.background.setTintList(ContextCompat.getColorStateList(context, color))
}

Then, you can use your function everywhere like this:

myButton.changeColor(R.color.myColor)

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

Change this:

SET @ActualWeightDIMS= @Actual_Dims_Lenght + 'x' + 
    @Actual_Dims_Width + 'x' + @Actual_Dims_Height;

To this:

SET @ActualWeightDIMS= CAST(@Actual_Dims_Lenght as varchar(3)) + 'x' + 
    CAST(@Actual_Dims_Width as varchar(3)) + 'x' + 
    CAST(@Actual_Dims_Height as varchar(3));

Change this:

SET @ActualWeightDIMS = @ActualWeight;

To this:

SET @ActualWeightDIMS = CAST(@ActualWeight as varchar(50));

You need to use CAST. Learn all about CAST and CONVERT here, because data types are important!

Remove '\' char from string c#

line = line.Replace("\\", "");

npm throws error without sudo

ISSUE: You (the user) don't have the right set of permissions for the directory.

The instant way out is to run the npm install using sudo, but this may give you the same error, or improper installation.

AND changing directory ownership is not a good option, a temporary patch.


Solution/Suggestion: Change npm's Default Directory (from official docs)

Back-up your computer before moving forward.

(optional) In case you have a erroneous installation, first uninstall it:

npm uninstall <package-name>  # use sudo if you used it while installation
npm cache verify  # or, npm cache clean for npm version below 5.x.x 
  1. Make a directory for global installations:

    mkdir ~/.npm-global

  2. Configure npm to use the new directory path:

    npm config set prefix '~/.npm-global'

  3. Open or create a ~/.profile or ~/.bash_profile file and add this line:

    export PATH=~/.npm-global/bin:$PATH

  4. Back on the command line, update your system variables, or restart the terminal:

    source ~/.profile

  5. (optional) Test: Download a package globally without using sudo.

    npm install -g jshint

if else statement in AngularJS templates

Ternary is the most clear way of doing this.

<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>

Passing arguments to angularjs filters

You can simply do like this In Template

<span ng-cloak>{{amount |firstFiler:'firstArgument':'secondArgument' }}</span>

In filter

angular.module("app")
.filter("firstFiler",function(){

    console.log("filter loads");
    return function(items, firstArgument,secondArgument){
        console.log("item is ",items); // it is value upon which you have to filter
        console.log("firstArgument is ",firstArgument);
        console.log("secondArgument ",secondArgument);

        return "hello";
    }
    });

Dynamic button click event handler

Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):

   Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    If sender.name = "radioFit_Components" And sender.visible Then
        If sender.checked Then
            For Each ctrl As Control In TabControl1.SelectedTab.Controls
                Select Case ctrl.Name
                    Case "embChartSSE_Components"
                        ctrl.BringToFront()
                    Case "embChartSSE_Fit_Curve"
                        ctrl.SendToBack()
                    Case "dgvFit_Components"
                        ctrl.BringToFront()
                End Select
            Next

        End If
    End If

End Sub

This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.

What is the best way to get the minimum or maximum value from an Array of numbers?

There isn't any reliable way to get the minimum/maximum without testing every value. You don't want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

python request with authentication (access_token)

I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN

header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

Coarse-grained vs fine-grained

Coarse-grained granularity does not always mean bigger components, if you go by literally meaning of the word coarse, it means harsh, or not appropriate. e.g. In software projects management, if you breakdown a small system into few components, which are equal in size, but varies in complexities and features, this could lead to a coarse-grained granularity. In reverse, for a fine-grained breakdown, you would divide the components based on their cohesiveness of the functionalities each component is providing.

Remove last 3 characters of string or number in javascript

Remove last 3 characters of a string

var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'

Remove last 3 digits of a number

var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995

Fill formula down till last row in column

For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.

Range("tablename[columnname]").Formula = "=G3&"",""&L3"

Making it a true one liner. Hope it helps someone!

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

URL to load resources from the classpath in Java

I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:

CustomURLScheme.java:
/*
 * The CustomURLScheme class has a static method for adding cutom protocol
 * handlers without getting bogged down with other class loaders and having to
 * call setURLStreamHandlerFactory before the next guy...
 */
package com.cybernostics.lib.net.customurl;

import java.net.URLStreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Allows you to add your own URL handler without running into problems
 * of race conditions with setURLStream handler.
 * 
 * To add your custom protocol eg myprot://blahblah:
 * 
 * 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
 * 2) Create a subclass of URLStreamHandler called Handler in this package
 * 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
 * @author jasonw
 */
public class CustomURLScheme
{

    // this is the package name required to implelent a Handler class
    private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );

    /**
     * Call this method with your handlerclass
     * @param handlerClass
     * @throws Exception 
     */
    public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
    {
        if ( handlerClass.getSimpleName().equals( "Handler" ) )
        {
            String pkgName = handlerClass.getPackage().getName();
            Matcher m = packagePattern.matcher( pkgName );

            if ( m.matches() )
            {
                String protocolPackage = m.group( 1 );
                add( protocolPackage );
            }
            else
            {
                throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
            }

        }
        else
        {
            throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
        }
    }

    private static void add( String handlerPackage )
    {
        // this property controls where java looks for
        // stream handlers - always uses current value.
        final String key = "java.protocol.handler.pkgs";

        String newValue = handlerPackage;
        if ( System.getProperty( key ) != null )
        {
            final String previousValue = System.getProperty( key );
            newValue += "|" + previousValue;
        }
        System.setProperty( key, newValue );
    }
}


CustomURLHandlerException.java:
/*
 * Exception if you get things mixed up creating a custom url protocol
 */
package com.cybernostics.lib.net.customurl;

/**
 *
 * @author jasonw
 */
public class CustomURLHandlerException extends Exception
{

    public CustomURLHandlerException(String msg )
    {
        super( msg );
    }

}

Python: fastest way to create a list of n lists

The probably only way which is marginally faster than

d = [[] for x in xrange(n)]

is

from itertools import repeat
d = [[] for i in repeat(None, n)]

It does not have to create a new int object in every iteration and is about 15 % faster on my machine.

Edit: Using NumPy, you can avoid the Python loop using

d = numpy.empty((n, 0)).tolist()

but this is actually 2.5 times slower than the list comprehension.

jQuery callback for multiple ajax calls

$.ajax({type:'POST', url:'www.naver.com', dataType:'text', async:false,
    complete:function(xhr, textStatus){},
    error:function(xhr, textStatus){},
    success:function( data ){
        $.ajax({type:'POST', 
            ....
            ....
            success:function(data){
                $.ajax({type:'POST',
                    ....
                    ....
            }
        }
    });

I'm sorry but I can't explain what I worte cuz I'm a Korean who can't speak even a word in english. but I think you can easily understand it.

How to call a REST web service API from JavaScript?

Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.

We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function () {
  // Begin accessing JSON data here
  }
}

// Send request
request.send()

How do I convert a Swift Array to a String?

A separator can be a bad idea for some languages like Hebrew or Japanese. Try this:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

For other data types respectively:

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

Git merge master into feature branch

How do we merge the master branch into the feature branch? Easy:

git checkout feature1
git merge master

There is no point in forcing a fast forward merge here, as it cannot be done. You committed both into the feature branch and the master branch. Fast forward is impossible now.

Have a look at GitFlow. It is a branching model for git that can be followed, and you unconsciously already did. It also is an extension to Git which adds some commands for the new workflow steps that do things automatically which you would otherwise need to do manually.

So what did you do right in your workflow? You have two branches to work with, your feature1 branch is basically the "develop" branch in the GitFlow model.

You created a hotfix branch from master and merged it back. And now you are stuck.

The GitFlow model asks you to merge the hotfix also to the development branch, which is "feature1" in your case.

So the real answer would be:

git checkout feature1
git merge --no-ff hotfix1

This adds all the changes that were made inside the hotfix to the feature branch, but only those changes. They might conflict with other development changes in the branch, but they will not conflict with the master branch should you merge the feature branch back to master eventually.

Be very careful with rebasing. Only rebase if the changes you did stayed local to your repository, e.g. you did not push any branches to some other repository. Rebasing is a great tool for you to arrange your local commits into a useful order before pushing it out into the world, but rebasing afterwards will mess up things for the git beginners like you.

Prevent wrapping of span or div

It works with just this:

.slideContainer {
    white-space: nowrap;
}
.slide { 
    display: inline-block;
    width: 600px;
    white-space: normal;
}

I did originally have float : left; and that prevented it from working correctly.

Thanks for posting this solution.

Could not find an implementation of the query pattern

I had the same error as described by title, but for me it was simply installing Microsoft access 12.0 oledb redistributable to use with LinqToExcel.

jQuery click / toggle between two functions

I used this to create a toggle effect between two functions.

var x = false;
$(element).on('click', function(){
 if (!x){
  //function
  x = true;
 }
 else {
  //function
  x = false;
 }
});

Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

SET NOCOUNT ON usage

I know it's pretty old question. but just for update.

Best way to use "SET NOCOUNT ON" is to put it up as a first statement in your SP and setting it OFF again just before the last SELECT statement.

Most pythonic way to delete a file which may not exist

In the spirit of Andy Jones' answer, how about an authentic ternary operation:

os.remove(fn) if os.path.exists(fn) else None

Why I cannot cout a string?

If you are using linux system then you need to add

using namespace std;

Below headers

If windows then make sure you put headers correctly #include<iostream.h>

#include<string.h>

Refer this it work perfectly.

#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";
                                       // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

   std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     
// get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If you are using this in chrome/chromium browser(ex: in Ubuntu 14.04), You can use one of the below command to tackle this issue.

ThinkPad-T430:~$ google-chrome --allow-file-access-from-files
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files fileName.html

ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files fileName.html

This will allow you to load the file in chrome or chromium. If you have to do the same operation for windows you can add this switch in properties of the chrome shortcut or run it from cmd with the flag. This operation is not allowed in Chrome, Opera, Internet Explorer by default. By default it works only in firefox and safari. Hence using this command will help you.

Alternately you can also host it on any web server (Example:Tomcat-java,NodeJS-JS,Tornado-Python, etc) based on what language you are comfortable with. This will work from any browser.

Sample random rows in dataframe

I'm new in R, but I was using this easy method that works for me:

sample_of_diamonds <- diamonds[sample(nrow(diamonds),100),]

PS: Feel free to note if it has some drawback I'm not thinking about.

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

Double precision - decimal places

IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.

An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.

Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.

Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.

Vue.js getting an element within a component

you can access the children of a vuejs component with this.$children. if you want to use the query selector on the current component instance then this.$el.querySelector(...)

just doing a simple console.log(this) will show you all the properties of a vue component instance.

additionally if you know the element you want to access in your component, you can add the v-el:uniquename directive to it and access it via this.$els.uniquename

Build fat static library (device + simulator) using Xcode and SDK 4+

There is a command-line utility xcodebuild and you can run shell command within xcode. So, if you don't mind using custom script, this script may help you.

#Configurations.
#This script designed for Mac OS X command-line, so does not use Xcode build variables.
#But you can use it freely if you want.

TARGET=sns
ACTION="clean build"
FILE_NAME=libsns.a

DEVICE=iphoneos3.2
SIMULATOR=iphonesimulator3.2






#Build for all platforms/configurations.

xcodebuild -configuration Debug -target ${TARGET} -sdk ${DEVICE} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Debug -target ${TARGET} -sdk ${SIMULATOR} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Release -target ${TARGET} -sdk ${DEVICE} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Release -target ${TARGET} -sdk ${SIMULATOR} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO







#Merge all platform binaries as a fat binary for each configurations.

DEBUG_DEVICE_DIR=${SYMROOT}/Debug-iphoneos
DEBUG_SIMULATOR_DIR=${SYMROOT}/Debug-iphonesimulator
DEBUG_UNIVERSAL_DIR=${SYMROOT}/Debug-universal

RELEASE_DEVICE_DIR=${SYMROOT}/Release-iphoneos
RELEASE_SIMULATOR_DIR=${SYMROOT}/Release-iphonesimulator
RELEASE_UNIVERSAL_DIR=${SYMROOT}/Release-universal

rm -rf "${DEBUG_UNIVERSAL_DIR}"
rm -rf "${RELEASE_UNIVERSAL_DIR}"
mkdir "${DEBUG_UNIVERSAL_DIR}"
mkdir "${RELEASE_UNIVERSAL_DIR}"

lipo -create -output "${DEBUG_UNIVERSAL_DIR}/${FILE_NAME}" "${DEBUG_DEVICE_DIR}/${FILE_NAME}" "${DEBUG_SIMULATOR_DIR}/${FILE_NAME}"
lipo -create -output "${RELEASE_UNIVERSAL_DIR}/${FILE_NAME}" "${RELEASE_DEVICE_DIR}/${FILE_NAME}" "${RELEASE_SIMULATOR_DIR}/${FILE_NAME}"

Maybe looks inefficient(I'm not good at shell script), but easy to understand. I configured a new target running only this script. The script is designed for command-line but not tested in :)

The core concept is xcodebuild and lipo.

I tried many configurations within Xcode UI, but nothing worked. Because this is a kind of batch processing, so command-line design is more suitable, so Apple removed batch build feature from Xcode gradually. So I don't expect they offer UI based batch build feature in future.

How do I count columns of a table

Simply use mysql_fetch_assoc and count the array using count() function

Why would an Enum implement an Interface?

Most common usage for this would be to merge the values of two enums into one group and treat them similarly. For example, see how to join Fruits and Vegatables.

Git: "Corrupt loose object"

I just experienced this - my machine crashed whilst writing to the Git repo, and it became corrupted. I fixed it as follows.

I started with looking at how many commits I had not pushed to the remote repo, thus:

gitk &

If you don't use this tool it is very handy - available on all operating systems as far as I know. This indicated that my remote was missing two commits. I therefore clicked on the label indicating the latest remote commit (usually this will be /remotes/origin/master) to get the hash (the hash is 40 chars long, but for brevity I am using 10 here - this usually works anyway).

Here it is:

14c0fcc9b3

I then click on the following commit (i.e. the first one that the remote does not have) and get the hash there:

04d44c3298

I then use both of these to make a patch for this commit:

git diff 14c0fcc9b3 04d44c3298 > 1.patch

I then did likewise with the other missing commit, i.e. I used the hash of the commit before and the hash of the commit itself:

git diff 04d44c3298 fc1d4b0df7 > 2.patch

I then moved to a new directory, cloned the repo from the remote:

git clone [email protected]:username/repo.git

I then moved the patch files into the new folder, and applied them and committed them with their exact commit messages (these can be pasted from git log or the gitk window):

patch -p1 < 1.patch
git commit

patch -p1 < 2.patch
git commit

This restored things for me (and note there's probably a faster way to do it for a large number of commits). However I was keen to see if the tree in the corrupted repo can be repaired, and the answer is it can. With a repaired repo available as above, run this command in the broken folder:

git fsck 

You will get something like this:

error: object file .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d is empty
error: unable to find ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d
error: sha1 mismatch ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d

To do the repair, I would do this in the broken folder:

rm .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d
cp ../good-repo/.git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d

i.e. remove the corrupted file and replace it with a good one. You may have to do this several times. Finally there will be a point where you can run fsck without errors. You will probably have "dangling commit" and "dangling blob" lines in the report, these are a consequence of your rebases and amends in this folder, and are OK. The garbage collector will remove them in due course.

Thus (at least in my case) a corrupted tree does not mean unpushed commits are lost.

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I also encounter the same problem and I resolved it by checking if the camera is available:

BOOL cameraAvailableFlag = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (cameraAvailableFlag)
        [self performSelector:@selector(showcamera) withObject:nil afterDelay:0.3];

UTF-8: General? Bin? Unicode?

In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.

Here is the difference:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

Quoted from: http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

For more detailed explanation, please read the following post from MySQL forums: http://forums.mysql.com/read.php?103,187048,188748

As for utf8_bin: Both utf8_general_ci and utf8_unicode_ci perform case-insensitive comparison. In constrast, utf8_bin is case-sensitive (among other differences), because it compares the binary values of the characters.

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

Add/Delete table rows dynamically using JavaScript

Easy Javascript Add more Rows with delete functionality

Cheers !

<TABLE id="dataTable">
<tr><td>
               <INPUT TYPE=submit name=submit id=button class=btn_medium VALUE=\'Save\'  >
               <INPUT type="button" value="AddMore" onclick="addRow(\'dataTable\')" class="btn_medium"    /> 
</td></tr>

<TR>
<TD> 
                <input type="text" size="20" name="values[]"/> <br><small><font color="gray">Enter Title</font></small> 
</TD>
</TR>
</table>



<script>


function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell3 = row.insertCell(0);
       cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button"  class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);" /><br><small><font color="gray">Enter Title</font></small>';
  //cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button"  class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.innerHTML=\'\';" /><br><small><font color="gray">Enter Title</font></small>';       
}

</script>

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

Set EditText cursor color

you can use code below in layout

android:textCursorDrawable="@color/red"
        android:textColor="@color/black

jquery change button color onclick

You have to include the jquery framework in your document head from a cdn for example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Then you have to include a own script for example:

(function( $ ) {

  $(document).ready(function(){
      $('input').click(function() {
          $(this).css('background-color', 'green');
      }
  });


  $(window).load(function() { 
  });

})( jQuery );

This part is a mapping of the $ to jQuery, so actually it is jQuery('selector').function();

(function( $ ) {

})( jQuery );

Here you can find die api of jquery where all functions are listed with examples and explanation: http://api.jquery.com/

Monad in plain English? (For the OOP programmer with no FP background)

To respect fast readers, I start with precise definition first, continue with quick more "plain English" explanation, and then move to examples.

Here is a both concise and precise definition slightly reworded:

A monad (in computer science) is formally a map that:

  • sends every type X of some given programming language to a new type T(X) (called the "type of T-computations with values in X");

  • equipped with a rule for composing two functions of the form f:X->T(Y) and g:Y->T(Z) to a function g°f:X->T(Z);

  • in a way that is associative in the evident sense and unital with respect to a given unit function called pure_X:X->T(X), to be thought of as taking a value to the pure computation that simply returns that value.

So in simple words, a monad is a rule to pass from any type X to another type T(X), and a rule to pass from two functions f:X->T(Y) and g:Y->T(Z) (that you would like to compose but can't) to a new function h:X->T(Z). Which, however, is not the composition in strict mathematical sense. We are basically "bending" function's composition or re-defining how functions are composed.

Plus, we require the monad's rule of composing to satisfy the "obvious" mathematical axioms:

  • Associativity: Composing f with g and then with h (from outside) should be the same as composing g with h and then with f (from inside).
  • Unital property: Composing f with the identity function on either side should yield f.

Again, in simple words, we can't just go crazy re-defining our function composition as we like:

  • We first need the associativity to be able to compose several functions in a row e.g. f(g(h(k(x))), and not to worry about specifying the order composing function pairs. As the monad rule only prescribes how to compose a pair of functions, without that axiom, we would need to know which pair is composed first and so on. (Note that is different from the commutativity property that f composed with g were the same as g composed with f, which is not required).
  • And second, we need the unital property, which is simply to say that identities compose trivially the way we expect them. So we can safely refactor functions whenever those identities can be extracted.

So again in brief: A monad is the rule of type extension and composing functions satisfying the two axioms -- associativity and unital property.

In practical terms, you want the monad to be implemented for you by the language, compiler or framework that would take care of composing functions for you. So you can focus on writing your function's logic rather than worrying how their execution is implemented.

That is essentially it, in a nutshell.


Being professional mathematician, I prefer to avoid calling h the "composition" of f and g. Because mathematically, it isn't. Calling it the "composition" incorrectly presumes that h is the true mathematical composition, which it isn't. It is not even uniquely determined by f and g. Instead, it is the result of our monad's new "rule of composing" the functions. Which can be totally different from the actual mathematical composition even if the latter exists!


To make it less dry, let me try to illustrate it by example that I am annotating with small sections, so you can skip right to the point.

Exception throwing as Monad examples

Suppose we want to compose two functions:

f: x -> 1 / x
g: y -> 2 * y

But f(0) is not defined, so an exception e is thrown. Then how can you define the compositional value g(f(0))? Throw an exception again, of course! Maybe the same e. Maybe a new updated exception e1.

What precisely happens here? First, we need new exception value(s) (different or same). You can call them nothing or null or whatever but the essence remains the same -- they should be new values, e.g. it should not be a number in our example here. I prefer not to call them null to avoid confusion with how null can be implemented in any specific language. Equally I prefer to avoid nothing because it is often associated with null, which, in principle, is what null should do, however, that principle often gets bended for whatever practical reasons.

What is exception exactly?

This is a trivial matter for any experienced programmer but I'd like to drop few words just to extinguish any worm of confusion:

Exception is an object encapsulating information about how the invalid result of execution occurred.

This can range from throwing away any details and returning a single global value (like NaN or null) or generating a long log list or what exactly happened, send it to a database and replicating all over the distributed data storage layer ;)

The important difference between these two extreme examples of exception is that in the first case there are no side-effects. In the second there are. Which brings us to the (thousand-dollar) question:

Are exceptions allowed in pure functions?

Shorter answer: Yes, but only when they don't lead to side-effects.

Longer answer. To be pure, your function's output must be uniquely determined by its input. So we amend our function f by sending 0 to the new abstract value e that we call exception. We make sure that value e contains no outside information that is not uniquely determined by our input, which is x. So here is an example of exception without side-effect:

e = {
  type: error, 
  message: 'I got error trying to divide 1 by 0'
}

And here is one with side-effect:

e = {
  type: error, 
  message: 'Our committee to decide what is 1/0 is currently away'
}

Actually, it only has side-effects if that message can possibly change in the future. But if it is guaranteed to never change, that value becomes uniquely predictable, and so there is no side-effect.

To make it even sillier. A function returning 42 ever is clearly pure. But if someone crazy decides to make 42 a variable that value might change, the very same function stops being pure under the new conditions.

Note that I am using the object literal notation for simplicity to demonstrate the essence. Unfortunately things are messed-up in languages like JavaScript, where error is not a type that behaves the way we want here with respect to function composition, whereas actual types like null or NaN do not behave this way but rather go through the some artificial and not always intuitive type conversions.

Type extension

As we want to vary the message inside our exception, we are really declaring a new type E for the whole exception object and then That is what the maybe number does, apart from its confusing name, which is to be either of type number or of the new exception type E, so it is really the union number | E of number and E. In particular, it depends on how we want to construct E, which is neither suggested nor reflected in the name maybe number.

What is functional composition?

It is the mathematical operation taking functions f: X -> Y and g: Y -> Z and constructing their composition as function h: X -> Z satisfying h(x) = g(f(x)). The problem with this definition occurs when the result f(x) is not allowed as argument of g.

In mathematics those functions cannot be composed without extra work. The strictly mathematical solution for our above example of f and g is to remove 0 from the set of definition of f. With that new set of definition (new more restrictive type of x), f becomes composable with g.

However, it is not very practical in programming to restrict the set of definition of f like that. Instead, exceptions can be used.

Or as another approach, artificial values are created like NaN, undefined, null, Infinity etc. So you evaluate 1/0 to Infinity and 1/-0 to -Infinity. And then force the new value back into your expression instead of throwing exception. Leading to results you may or may not find predictable:

1/0                // => Infinity
parseInt(Infinity) // => NaN
NaN < 0            // => false
false + 1          // => 1

And we are back to regular numbers ready to move on ;)

JavaScript allows us to keep executing numerical expressions at any costs without throwing errors as in the above example. That means, it also allows to compose functions. Which is exactly what monad is about - it is a rule to compose functions satisfying the axioms as defined at the beginning of this answer.

But is the rule of composing function, arising from JavaScript's implementation for dealing with numerical errors, a monad?

To answer this question, all you need is to check the axioms (left as exercise as not part of the question here;).

Can throwing exception be used to construct a monad?

Indeed, a more useful monad would instead be the rule prescribing that if f throws exception for some x, so does its composition with any g. Plus make the exception E globally unique with only one possible value ever (terminal object in category theory). Now the two axioms are instantly checkable and we get a very useful monad. And the result is what is well-known as the maybe monad.

How to emulate a do-while loop in Python?

The built-in iter function does specifically that:

for x in iter(YOUR_FN, TERM_VAL):
    ...

E.g. (tested in Py2 and 3):

class Easy:
  X = 0
  @classmethod
  def com(cls):
    cls.X += 1
    return cls.X

for x in iter(Easy.com, 10):
  print(">>>", x)

If you want to give a condition to terminate instead of a value, you always can set an equality, and require that equality to be True.

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Change the color of a checked menu item in a navigation drawer

Step 1: Build a checked/unchecked selector:

selector.xml

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

Step 2: use the xml attribute app:itemTextColor within NavigationView widget for selecting the text color.

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/navigation_header_layout"
    app:itemTextColor="@drawable/selector"
    app:menu="@menu/navigation_menu" />

Step 3:
For some reason when you hit an item from the NavigationView menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();

    // remove all colors of the items to the `unchecked` state of the selector
    removeColor(mNavigationView);

    // check the selected item to change its color set by the `checked` state of the selector
    item.setChecked(true);

    switch (item.getItemId()) {
      case R.id.dashboard:
          ...
    }

    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

private void removeColor(NavigationView view) {
    for (int i = 0; i < view.getMenu().size(); i++) {
        MenuItem item = view.getMenu().getItem(i);
        item.setChecked(false);
    }
}

Step 4:
To change icon color, use the app:iconTint attribute in the NavigationView menu items, and set to the same selector.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/nav_account"
        android:checked="true"
        android:icon="@drawable/ic_person_black_24dp"
        android:title="My Account"
        app:iconTint="@drawable/selector" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="Settings"
        app:iconTint="@drawable/selector" />

    <item
        android:id="@+id/nav_logout"
        android:icon="@drawable/logout"
        android:title="Log Out"
        app:iconTint="@drawable/selector" />
</menu>

Result:

Singleton: How should it be used

Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.

Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static

C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.

Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.

So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.

no overload for matches delegate 'system.eventhandler'

You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e.

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

How to check for registry value using VbScript

This should work for you:

Dim oShell
Dim iValue

Set oShell = CreateObject("WScript.Shell")

iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

load jquery after the page is fully loaded

You can also use:

$(window).bind("load", function() { 
    // Your code here.
});

Playing .mp3 and .wav in Java?

you can play .wav only with java API:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

code:

AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

And play .mp3 with jLayer

jQuery & CSS - Remove/Add display:none

The only way to remove an inline "display:none" via jQuery's css-api is by resetting it with the empty string (null does NOT work btw!!).

According to the jQuery docu this is the general way to "remove" a once set inline style property.

$("#mydiv").css("display","");

or

$("#mydiv").css({display:""});

should do the trick properly.

IMHO there is a method missing in jQuery that could be called "unhide" or "reveal" which instead of just setting another inline style property unsets the display value properly as described above. Or maybe hide() should store the initial inline value and show() should restore that...

Upload a file to Amazon S3 with NodeJS

Uploading a file to AWS s3 and sending the url in response for accessing the file.

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. check this npm module here.

When you are sending the request, make sure the headers, have Content-Type is multipart/form-data. We are sending the file location in the response, which will give the url, but if you want to access that url, make the bucket public or else you will not be able to access it.

upload.router.js

const express = require('express');
const router = express.Router();
const AWS = require('aws-sdk');
const multer = require('multer');
const storage = multer.memoryStorage()
const upload = multer({storage: storage});

const s3Client = new AWS.S3({
    accessKeyId: 'your_access_key_id',
    secretAccessKey: 'your_secret_access_id',
    region :'ur region'
});

const uploadParams = {
         Bucket: 'ur_bucket_name', 
         Key: '', // pass key
         Body: null, // pass file body
};


router.post('/api/file/upload', upload.single("file"),(req,res) => {
    const params = uploadParams;

    uploadParams.Key = req.file.originalname;
    uploadParams.Body = req.file.buffer;

    s3Client.upload(params, (err, data) => {
        if (err) {
            res.status(500).json({error:"Error -> " + err});
        }
        res.json({message: 'File uploaded successfully','filename': 
        req.file.originalname, 'location': data.Location});
    });
});

module.exports = router;

app.js

const express = require('express');
const app = express();

const router = require('./app/routers/upload.router.js');
app.use('/', router);

// Create a Server
  const server = app.listen(8080, () => {
  console.log("App listening at 8080"); 
})

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

how do you view macro code in access?

Open the Access Database, you will see Table, Query, Report, Module & Macro.
This contains the macros which can be used to invoke common MS-Access actions in a sequence.

For custom VBA macro, press ALT+F11.

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

C++ for each, pulling from vector elements

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>

using namespace std;

int main() 
{
  int total = 0;

  vector<int> v(6);
  v[0] = 10; v[1] = 20; v[2] = 30;
  v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
    total += i;
  }

  cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.

How to empty (clear) the logcat buffer in Android

I give my solution for Mac:

  1. With your device connected to the USB port, open a terminal and go to the adb folder.
  2. Write: ./adb devices
  3. The terminal will show something like this: List of devices attached 36ac5997 device
  4. Take note of the serial number (36ac5997)
  5. Write: ./adb -s 36ac5997 to connect to the device
  6. Write: ./adb logcat

If at any time you want to clear the log, type ./adb logcat -c

Convert stdClass object to array in PHP

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text

Golang append an item to a slice

Try this, which I think makes it clear. the underlying array is changed but our slice is not, print just prints len() chars, by another slice to the cap(), you can see the changed array:

func main() {

  for i := 0; i < 7; i++ {
      a[i] = i
  }

  Test(a)

  fmt.Println(a) // prints [0..6]
  fmt.Println(a[:cap(a)] // prints [0..6,100]
}

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

How do I cancel form submission in submit button onclick event?

<input type='button' onclick='buttonClick()' />

<script>
function buttonClick(){
    //Validate Here
    document.getElementsByTagName('form')[0].submit();
}
</script>

Converting SVG to PNG using C#

To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.

    foreach(var child in svgDocument.Children)
    {
        SetFont(child);
    }

    public void SetFont(SvgElement element)
    {
        foreach(var child in element.Children)
        {
            SetFont(child); //Call this function again with the child, this will loop
                            //until the element has no more children
        }

        try
        {
            var svgText = (SvgText)parent; //try to cast the element as a SvgText
                                           //if it succeeds you can modify the font

            svgText.Font = new Font("Arial", 12.0f);
            svgText.FontSize = new SvgUnit(12.0f);
        }
        catch
        {

        }
    }

Let me know if there are questions.

Full width image with fixed height

Set the image's width to 100%, and the image's height will adjust itself:

<img style="width:100%;" id="image" src="...">

If you have a custom CSS, then:

HTML:

<img id="image" src="...">

CSS:

#image
{
    width: 100%;
}

Also, you could do File -> View Source next time, or maybe Google.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example

//In Model

public class MyModel
{  
   [Required]
    public string Name{ get; set; }
}

//In PartailView //PartailView.cshtml

@model MyModel

<div>
    <div>
      @Html.LabelFor(model=>model.Name)
    </div>
    <div>
        @Html.EditorFor(model=>model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

In Index.cshtml view

@model MyModel
<div id="targetId">
    @{Html.RenderPartial("PartialView",Model)}
</div>

@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
     <div>
        <input type="submit" value="Add Unit" />
    </div>
}

In Controller

public ActionResult Index()
{
  return View(new MyModel());
}


public string AddName(MyModel model)
{
   string HtmlString = RenderPartialViewToString("PartailView",model);
   return HtmlString;
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

Spring - download response as a file

I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.

  1. IF server is sending blob in the response, then our client should be able to produce it.

  2. As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.

  3. Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.

_x000D_
_x000D_
controller.js_x000D_
//this function is in controller, which will be trigered on download button hit. _x000D_
_x000D_
  $scope.downloadSampleFile = function() {_x000D_
//create sample hidden link in document, to accept Blob returned in the response from back end_x000D_
    _x000D_
  var downloadLink = document.createElement("a");_x000D_
_x000D_
  document.body.appendChild(downloadLink);_x000D_
  downloadLink.style = "display: none";_x000D_
_x000D_
//This service is written Below how does it work, by aceepting necessary params_x000D_
  downloadFile.downloadfile(data).then(function (result) {_x000D_
_x000D_
   var fName = result.filename;_x000D_
   var file = new Blob([result.data], {type: 'application/*'});_x000D_
   var fileURL = (window.URL || window.webkitURL).createObjectURL(file);_x000D_
_x000D_
          _x000D_
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj._x000D_
          _x000D_
   downloadLink.href = fileURL;_x000D_
   downloadLink.download = fName;_x000D_
   downloadLink.click();_x000D_
  });_x000D_
 };_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
services.js_x000D_
_x000D_
.factory('downloadFile', ["$http", function ($http) {_x000D_
 return {_x000D_
  downloadfile : function () {_x000D_
   return $http.get(//here server endpoint to which you want to hit the request_x000D_
              , {_x000D_
    responseType: 'arraybuffer',_x000D_
    params: {_x000D_
     //Required params_x000D_
    },_x000D_
   }).then(function (response, status, headers, config) {_x000D_
    return response;_x000D_
   });_x000D_
  },_x000D_
 };_x000D_
}])
_x000D_
_x000D_
_x000D_