Programs & Examples On #.net micro framework

.NET Micro Framework is a CLR and set of libraries that runs on tiny low-cost microcontrollers with limited resources. It brings the genuine .NET developing experience (Visual Studio, managed high level coding & garbage collection, the VS debugger) to the embedded world.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

Enter

git log .

from the specific directory, it also gives commits in that directory.

get one item from an array of name,value JSON

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

Zero-pad digits in string

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

How to check for Is not Null And Is not Empty string in SQL server?

For some kind of reason my NULL values where of data length 8. That is why none of the abovementioned seemed to work. If you encounter the same problem, use the following code:

--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table

--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8

Solr vs. ElasticSearch

Imagine the use case:

  1. A lot(100+) of small(10Mb-100Mb, 1000-100000 documents) search indexes.
  2. They are using by a lot of applications (microservices)
  3. Each application can use more than one index
  4. Small by size index, yes. But huge load(hundreds search-requests per second) and requests are complex (multiple aggregations, conditions and so on)
  5. Downtimes are not allowed
  6. All of that is working years long, and constantly growing.

Idea to have individual ES instance per each index - is huge overhead in this case.

Based on my experience, this kind of use case is very complex to support with Elasticsearch.

Why?

FIRST.

The major problem is fundamental back compatibility disregard.

Breaking changes are so cool! (Note: imagine SQL-server which require you to do small change in all your SQL-statements, when upgraded... can't imagine it. But for ES it's normal)

Deprecations which will dropped in next major release are so sexy! (Note: you know, Java contain some deprecations, which 20+ years old, but still working in actual Java version...)

And not only that, sometimes you even have something which nowhere documented (personally came across only once but... )

So. If you want to upgrade ES (because you need new features for some app or you want to get bug fixes) - you are in hell. Especially if it is about major version upgrade.

Client API will not back compatible. Index settings will not back compatible. And upgrade all app/services same moment with ES upgrade is not realistic.

But you must do it time to time. No other way.

Existing indexes is automatically upgraded? - Yes. But it not help you when you will need to change some old-index settings.

To live with that, you need constantly invest a lot of power in ... forward compatibility of you apps/services with future releases of ES. Or you need to build(and anyway constantly support) some kind of middleware between you app/services and ES, which provide you back compatible client API. (And, you can't use Transport Client (because it required jar upgrade for every minor version ES upgrade), and this fact do not make your life easier)

Is it looks simple & cheap? No, it's not. Far from it. Continuous maintenance of complex infrastructure which based on ES, is way to expensive in all possible senses.

SECOND. Simple API ? Well... no really. When you is really using complex conditions and aggregations.... JSON-request with 5 nested levels is whatever, but not simple.


Unfortunately, I have no experience with SOLR, can't say anything about it.

But Sphinxsearch is much better it this scenario, becasue of totally back compatible SphinxQL.

Note: Sphinxsearch/Manticore are indeed interesting. It's not Lucine based, and as result seriously different. Contain several unique features from the box which ES do not have and crazy fast with small/middle size indexes.

How can I declare a global variable in Angular 2 / Typescript?

See for example Angular 2 - Implementation of shared services

@Injectable() 
export class MyGlobals {
  readonly myConfigValue:string = 'abc';
}

@NgModule({
  providers: [MyGlobals],
  ...
})

class MyComponent {
  constructor(private myGlobals:MyGlobals) {
    console.log(myGlobals.myConfigValue);
  }
}

or provide individual values

@NgModule({
  providers: [{provide: 'myConfigValue', useValue: 'abc'}],
  ...
})

class MyComponent {
  constructor(@Inject('myConfigValue') private myConfigValue:string) {
    console.log(myConfigValue);
  }
}

How to switch between python 2.7 to python 3 from command line?

No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

#!python2
print "hello"

Or

#!python3
print("hello")

From the command line:

py -3 hello.py

Or

py -2 hello.py

py hello.py by itself will choose the latest Python installed, or consult the PY_PYTHON environment variable, e.g. set PY_PYTHON=3.6.

See Python Launcher for Windows

DataTables: Cannot read property style of undefined

The problem is that the number of <th> tags need to match the number of columns in the configuration (the array with the key "columns"). If there are fewer <th> tags than columns specified, you get this slightly cryptical error message.

(the correct answer is already present as a comment but I'm repeating it as an answer so it's easier to find - I didn't see the comments)

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I was having the same issue till just now; just as you mentioned, I tried "Connect As" and the username and password that I wrote down, was my machine's user (IIS is running on this machine), I tested the connection and it works now. Maybe if you weren't using that machine's user (try user with administrator privileges), you should give it a try, it worked for me, it may work in your case as well.

Getting file size in Python?

Use os.path.getsize(path) which will

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

Or use os.stat(path).st_size

import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 

Or use Path(path).stat().st_size (Python 3.4+)

from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size

How do you parse and process HTML/XML in PHP?

I created a library named PHPPowertools/DOM-Query, which allows you to crawl HTML5 and XML documents just like you do with jQuery.

Under the hood, it uses symfony/DomCrawler for conversion of CSS selectors to XPath selectors. It always uses the same DomDocument, even when passing one object to another, to ensure decent performance.


Example use :

namespace PowerTools;

// Get file content
$htmlcode = file_get_contents('https://github.com');

// Define your DOMCrawler based on file string
$H = new DOM_Query($htmlcode);

// Define your DOMCrawler based on an existing DOM_Query instance
$H = new DOM_Query($H->select('body'));

// Passing a string (CSS selector)
$s = $H->select('div.foo');

// Passing an element object (DOM Element)
$s = $H->select($documentBody);

// Passing a DOM Query object
$s = $H->select( $H->select('p + p'));

// Select the body tag
$body = $H->select('body');

// Combine different classes as one selector to get all site blocks
$siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');

// Nest your methods just like you would with jQuery
$siteblocks->select('button')->add('span')->addClass('icon icon-printer');

// Use a lambda function to set the text of all site blocks
$siteblocks->text(function( $i, $val) {
    return $i . " - " . $val->attr('class');
});

// Append the following HTML to all site blocks
$siteblocks->append('<div class="site-center"></div>');

// Use a descendant selector to select the site's footer
$sitefooter = $body->select('.site-footer > .site-center');

// Set some attributes for the site's footer
$sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));

// Use a lambda function to set the attributes of all site blocks
$siteblocks->attr('data-val', function( $i, $val) {
    return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";
});

// Select the parent of the site's footer
$sitefooterparent = $sitefooter->parent();

// Remove the class of all i-tags within the site's footer's parent
$sitefooterparent->select('i')->removeAttr('class');

// Wrap the site's footer within two nex selectors
$sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');

[...]

Supported methods :


  1. Renamed 'select', for obvious reasons
  2. Renamed 'void', since 'empty' is a reserved word in PHP

NOTE :

The library also includes its own zero-configuration autoloader for PSR-0 compatible libraries. The example included should work out of the box without any additional configuration. Alternatively, you can use it with composer.

How to add external fonts to android application

Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);

How to enable C++11/C++0x support in Eclipse CDT?

When using a cross compiler, I often get advanced custom build systems meticulously crafted by colleagues. I use "Makefile Project with Existing code" so most of the other answers are not applicable.

At the start of the project, I have to specify that I'm using a cross compiler in the wizard for "Makefile Project with Existing Code". The annoying thing is that in the last 10 or so years, the cross compiler button on that wizard doesn't prompt for where the cross compiler is. So in a step that fixes the C++ problem and the cross compiler problem, I have to go to the providers tab as mentioned by answers like @ravwojdyla above, but the provider I have to select is the cross-compiler provider. Then in the command box I put the full path to the compiler and I add -std=gnu++11 for the C++ standard I want to have support for. This works out as well as can be expected.

You can do this to an existing project. The only thing you might need to do is rerun the indexer.

I have never had to add the experimental flag or override __cplusplus's definition. The only thing is, if I have a substantial amount of modern C code, I have nowhere to put the C-specific standard option.

And for when things are going really poorly, getting a parser log, using that command in the Indexer submenu, can be very informative.

Why do I always get the same sequence of random numbers with rand()?

call srand(sameSeed) before calling rand(). More details here.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...

Options are:

Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small

UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:

From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

Also make sure you read the comments below.

mysql_config not found when installing mysqldb python interface

I encountered the same problem, just added the path where *mysql_config* resided to the environment variable PATH and it worked for me.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

For Devs getting this error in Web API Project -

The GetOwinContext extension method is defined in System.Web.Http.Owin dll and one more package will be needed i.e. Microsoft.Owin.Host.SystemWeb. This package needs to be installed in your project from nuget.

Link To Package: OWIN Package Install Command -

Install-Package Microsoft.AspNet.WebApi.Owin    

Link To System.web Package : Package Install Command -

Install-Package Microsoft.Owin.Host.SystemWeb

In order to resolve this error you need to find why its occurring in your case. Please Cross check below points in your code -

  1. You must have reference to Microsoft.AspNet.Identity.Owin;

    using Microsoft.AspNet.Identity.Owin;

  2. Define GetOwinContext() Under HttpContext.Current as below -

     return _userManager1 ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
    

    OR

    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
    

Complete Code Where GetOwinContext() is used -

 public ApplicationSignInManager SignInManager
 {
   get
   {
    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
   }
    private set
    {
     _signInManager = value;
    }
  }

Namespace's I'm Using in Code File where GetOwinContext() Is used

using AngularJSAuthentication.API.Entities;
using AngularJSAuthentication.API.Models;
using HomeCinema.Common;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;

I got this error while moving my code from my one project to another.

Microsoft Excel mangles Diacritics in .csv files?

A correctly formatted UTF8 file can have a Byte Order Mark as its first three octets. These are the hex values 0xEF, 0xBB, 0xBF. These octets serve to mark the file as UTF8 (since they are not relevant as "byte order" information).1 If this BOM does not exist, the consumer/reader is left to infer the encoding type of the text. Readers that are not UTF8 capable will read the bytes as some other encoding such as Windows-1252 and display the characters  at the start of the file.

There is a known bug where Excel, upon opening UTF8 CSV files via file association, assumes that they are in a single-byte encoding, disregarding the presence of the UTF8 BOM. This can not be fixed by any system default codepage or language setting. The BOM will not clue in Excel - it just won't work. (A minority report claims that the BOM sometimes triggers the "Import Text" wizard.) This bug appears to exist in Excel 2003 and earlier. Most reports (amidst the answers here) say that this is fixed in Excel 2007 and newer.

Note that you can always* correctly open UTF8 CSV files in Excel using the "Import Text" wizard, which allows you to specify the encoding of the file you're opening. Of course this is much less convenient.

Readers of this answer are most likely in a situation where they don't particularly support Excel < 2007, but are sending raw UTF8 text to Excel, which is misinterpreting it and sprinkling your text with à and other similar Windows-1252 characters. Adding the UTF8 BOM is probably your best and quickest fix.

If you are stuck with users on older Excels, and Excel is the only consumer of your CSVs, you can work around this by exporting UTF16 instead of UTF8. Excel 2000 and 2003 will double-click-open these correctly. (Some other text editors can have issues with UTF16, so you may have to weigh your options carefully.)


* Except when you can't, (at least) Excel 2011 for Mac's Import Wizard does not actually always work with all encodings, regardless of what you tell it. </anecdotal-evidence> :)

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

For footer change from position: relative; to position:fixed;

 footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: fixed;
        }

Example: http://jsfiddle.net/a6RBm/

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Taken From www.regular-expressions.info

Greediness: Greedy quantifiers first tries to repeat the token as many times as possible, and gradually gives up matches as the engine backtracks to find an overall match.

Laziness: Lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match.

Converting JavaScript object with numeric keys into array

Assuming your have a value like the following

var obj = {"0":"1","1":"2","2":"3","3":"4"};

Then you can turn this into a javascript array using the following

var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

This works for converting json into multi-diminsional javascript arrays as well.

None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

Automatically running a batch file as an administrator

CMD Itself does not have a function to run files as admin, but powershell does, and that powershell function can be exectuted through CMD with a certain command. Write it in command prompt to run the file you specified as admin.

powershell -command start-process -file yourfilename -verb runas

Hope it helped!

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

CSS position absolute full width problem

You could set both left and right property to 0. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header is position: relative;)

#site_nav_global_primary {    
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}

Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative; from #header

How to use JavaScript to change div backgroundColor

Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:

document.getElementById("MyHeader").style.backgroundColor='red';

EDIT

You can use getElementsByTagName too, (untested) example:

function colorElementAndH2(elem, colorElem, colorH2) {
    // change element background color
    elem.style.backgroundColor = colorElem;
    // color first contained h2
    var h2s = elem.getElementsByTagName("h2");
    if (h2s.length > 0)
    {
        hs2[0].style.backgroundColor = colorH2;
    }
}

// add event handlers when complete document has been loaded
window.onload = function() {
    // add to _all_ divs (not sure if this is what you want though)
    var elems = document.getElementsByTagName("div");
    for(i = 0; i < elems.length; ++i)
    {
        elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
        elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
    }
}

Getting the object's property name

Use Object.keys():

_x000D_
_x000D_
var myObject = { a: 'c', b: 'a', c: 'b' };_x000D_
var keyNames = Object.keys(myObject);_x000D_
console.log(keyNames); // Outputs ["a","b","c"]
_x000D_
_x000D_
_x000D_

Object.keys() gives you an array of property names belonging to the input object.

How do I use a custom Serializer with Jackson?

I wrote an example for a custom Timestamp.class serialization/deserialization, but you could use it for what ever you want.

When creating the object mapper do something like this:

public class JsonUtils {

    public static ObjectMapper objectMapper = null;

    static {
        objectMapper = new ObjectMapper();
        SimpleModule s = new SimpleModule();
        s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
        s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
        objectMapper.registerModule(s);
    };
}

for example in java ee you could initialize it with this:

import java.time.LocalDateTime;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {

    private final ObjectMapper objectMapper;

    public JacksonConfig() {
        objectMapper = new ObjectMapper();
        SimpleModule s = new SimpleModule();
        s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
        s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
        objectMapper.registerModule(s);
    };

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return objectMapper;
    }
}

where the serializer should be something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampSerializerTypeHandler extends JsonSerializer<Timestamp> {

    @Override
    public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        String stringValue = value.toString();
        if(stringValue != null && !stringValue.isEmpty() && !stringValue.equals("null")) {
            jgen.writeString(stringValue);
        } else {
            jgen.writeNull();
        }
    }

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}

and deserializer something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampDeserializerTypeHandler extends JsonDeserializer<Timestamp> {

    @Override
    public Timestamp deserialize(JsonParser jp, DeserializationContext ds) throws IOException, JsonProcessingException {
        SqlTimestampConverter s = new SqlTimestampConverter();
        String value = jp.getValueAsString();
        if(value != null && !value.isEmpty() && !value.equals("null"))
            return (Timestamp) s.convert(Timestamp.class, value);
        return null;
    }

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}

Click event on select option element in chrome

<select id="myselect">
    <option value="0">sometext</option>
    <option value="2">Ready for Review</option>
    <option value="3">Registration Date</option>
</select>

$('#myselect').change(function() {
    if($('#myselect option:selected').val() == 0) {
    ...
    }
    else {
    ...
    }
});

In Git, how do I figure out what my current revision is?

This gives you the first few digits of the hash and they are unique enough to use as say a version number.

git rev-parse --short HEAD

Python Pandas replicate rows in dataframe

You can put df_try inside a list and then do what you have in mind:

>>> df.append([df_try]*5,ignore_index=True)

    Store  Dept       Date  Weekly_Sales IsHoliday
0       1     1 2010-02-05      24924.50     False
1       1     1 2010-02-12      46039.49      True
2       1     1 2010-02-19      41595.55     False
3       1     1 2010-02-26      19403.54     False
4       1     1 2010-03-05      21827.90     False
5       1     1 2010-03-12      21043.39     False
6       1     1 2010-03-19      22136.64     False
7       1     1 2010-03-26      26229.21     False
8       1     1 2010-04-02      57258.43     False
9       1     1 2010-02-12      46039.49      True
10      1     1 2010-02-12      46039.49      True
11      1     1 2010-02-12      46039.49      True
12      1     1 2010-02-12      46039.49      True
13      1     1 2010-02-12      46039.49      True

Ship an application with a database

There are two options for creating and updating databases.

One is to create a database externally, then place it in the assets folder of the project and then copy the entire database from there. This is much quicker if the database has a lot of tables and other components. Upgrades are triggered by changing the database version number in the res/values/strings.xml file. Upgrades would then be accomplished by creating a new database externally, replacing the old database in the assets folder with the new database, saving the old database in internal storage under another name, copying the new database from the assets folder into internal storage, transferring all of the data from the old database (that was renamed earlier) into the new database and finally deleting the old database. You can create a database originally by using the SQLite Manager FireFox plugin to execute your creation sql statements.

The other option is to create a database internally from a sql file. This is not as quick but the delay would probably be unnoticeable to the users if the database has only a few tables. Upgrades are triggered by changing the database version number in the res/values/strings.xml file. Upgrades would then be accomplished by processing an upgrade sql file. The data in the database will remain unchanged except when its container is removed, for example dropping a table.

The example below demonstrates how to use either method.

Here is a sample create_database.sql file. It is to be placed in the assets folder of the project for the internal method or copied into the "Execute SQL' of SQLite Manager to create the database for the external method. (NOTE: Notice the comment about the table required by Android.)

--Android requires a table named 'android_metadata' with a 'locale' column
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');
INSERT INTO "android_metadata" VALUES ('en_US');

CREATE TABLE "kitchen_table";
CREATE TABLE "coffee_table";
CREATE TABLE "pool_table";
CREATE TABLE "dining_room_table";
CREATE TABLE "card_table"; 

Here is a sample update_database.sql file. It is to be placed in the assets folder of the project for the internal method or copied into the "Execute SQL' of SQLite Manager to create the database for the external method. (NOTE: Notice that all three types of SQL comments will be ignored by the sql parser that is included in this example.)

--CREATE TABLE "kitchen_table";  This is one type of comment in sql.  It is ignored by parseSql.
/*
 * CREATE TABLE "coffee_table"; This is a second type of comment in sql.  It is ignored by parseSql.
 */
{
CREATE TABLE "pool_table";  This is a third type of comment in sql.  It is ignored by parseSql.
}
/* CREATE TABLE "dining_room_table"; This is a second type of comment in sql.  It is ignored by parseSql. */
{ CREATE TABLE "card_table"; This is a third type of comment in sql.  It is ignored by parseSql. }

--DROP TABLE "picnic_table"; Uncomment this if picnic table was previously created and now is being replaced.
CREATE TABLE "picnic_table" ("plates" TEXT);
INSERT INTO "picnic_table" VALUES ('paper');

Here is an entry to add to the /res/values/strings.xml file for the database version number.

<item type="string" name="databaseVersion" format="integer">1</item>

Here is an activity that accesses the database and then uses it. (Note: You might want to run the database code in a separate thread if it uses a lot of resources.)

package android.example;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

/**
 * @author Danny Remington - MacroSolve
 * 
 *         Activity for demonstrating how to use a sqlite database.
 */
public class Database extends Activity {
     /** Called when the activity is first created. */
     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DatabaseHelper myDbHelper;
        SQLiteDatabase myDb = null;

        myDbHelper = new DatabaseHelper(this);
        /*
         * Database must be initialized before it can be used. This will ensure
         * that the database exists and is the current version.
         */
         myDbHelper.initializeDataBase();

         try {
            // A reference to the database can be obtained after initialization.
            myDb = myDbHelper.getWritableDatabase();
            /*
             * Place code to use database here.
             */
         } catch (Exception ex) {
            ex.printStackTrace();
         } finally {
            try {
                myDbHelper.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                myDb.close();
            }
        }

    }
}

Here is the database helper class where the database is created or updated if necessary. (NOTE: Android requires that you create a class that extends SQLiteOpenHelper in order to work with a Sqlite database.)

package android.example;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author Danny Remington - MacroSolve
 * 
 *         Helper class for sqlite database.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    /*
     * The Android's default system path of the application database in internal
     * storage. The package of the application is part of the path of the
     * directory.
     */
    private static String DB_DIR = "/data/data/android.example/databases/";
    private static String DB_NAME = "database.sqlite";
    private static String DB_PATH = DB_DIR + DB_NAME;
    private static String OLD_DB_PATH = DB_DIR + "old_" + DB_NAME;

    private final Context myContext;

    private boolean createDatabase = false;
    private boolean upgradeDatabase = false;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     * 
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, context.getResources().getInteger(
                R.string.databaseVersion));
        myContext = context;
        // Get the path of the database that is based on the context.
        DB_PATH = myContext.getDatabasePath(DB_NAME).getAbsolutePath();
    }

    /**
     * Upgrade the database in internal storage if it exists but is not current. 
     * Create a new empty database in internal storage if it does not exist.
     */
    public void initializeDataBase() {
        /*
         * Creates or updates the database in internal storage if it is needed
         * before opening the database. In all cases opening the database copies
         * the database in internal storage to the cache.
         */
        getWritableDatabase();

        if (createDatabase) {
            /*
             * If the database is created by the copy method, then the creation
             * code needs to go here. This method consists of copying the new
             * database from assets into internal storage and then caching it.
             */
            try {
                /*
                 * Write over the empty data that was created in internal
                 * storage with the one in assets and then cache it.
                 */
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        } else if (upgradeDatabase) {
            /*
             * If the database is upgraded by the copy and reload method, then
             * the upgrade code needs to go here. This method consists of
             * renaming the old database in internal storage, create an empty
             * new database in internal storage, copying the database from
             * assets to the new database in internal storage, caching the new
             * database from internal storage, loading the data from the old
             * database into the new database in the cache and then deleting the
             * old database from internal storage.
             */
            try {
                FileHelper.copyFile(DB_PATH, OLD_DB_PATH);
                copyDataBase();
                SQLiteDatabase old_db = SQLiteDatabase.openDatabase(OLD_DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
                SQLiteDatabase new_db = SQLiteDatabase.openDatabase(DB_PATH,null, SQLiteDatabase.OPEN_READWRITE);
                /*
                 * Add code to load data into the new database from the old
                 * database and then delete the old database from internal
                 * storage after all data has been transferred.
                 */
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }

    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {
        /*
         * Close SQLiteOpenHelper so it will commit the created empty database
         * to internal storage.
         */
        close();

        /*
         * Open the database in the assets folder as the input stream.
         */
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        /*
         * Open the empty db in interal storage as the output stream.
         */
        OutputStream myOutput = new FileOutputStream(DB_PATH);

        /*
         * Copy over the empty db in internal storage with the database in the
         * assets folder.
         */
        FileHelper.copyFile(myInput, myOutput);

        /*
         * Access the copied database so SQLiteHelper will cache it and mark it
         * as created.
         */
        getWritableDatabase().close();
    }

    /*
     * This is where the creation of tables and the initial population of the
     * tables should happen, if a database is being created from scratch instead
     * of being copied from the application package assets. Copying a database
     * from the application package assets to internal storage inside this
     * method will result in a corrupted database.
     * <P>
     * NOTE: This method is normally only called when a database has not already
     * been created. When the database has been copied, then this method is
     * called the first time a reference to the database is retrieved after the
     * database is copied since the database last cached by SQLiteOpenHelper is
     * different than the database in internal storage.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        /*
         * Signal that a new database needs to be copied. The copy process must
         * be performed after the database in the cache has been closed causing
         * it to be committed to internal storage. Otherwise the database in
         * internal storage will not have the same creation timestamp as the one
         * in the cache causing the database in internal storage to be marked as
         * corrupted.
         */
        createDatabase = true;

        /*
         * This will create by reading a sql file and executing the commands in
         * it.
         */
            // try {
            // InputStream is = myContext.getResources().getAssets().open(
            // "create_database.sql");
            //
            // String[] statements = FileHelper.parseSqlFile(is);
            //
            // for (String statement : statements) {
            // db.execSQL(statement);
            // }
            // } catch (Exception ex) {
            // ex.printStackTrace();
            // }
    }

    /**
     * Called only if version number was changed and the database has already
     * been created. Copying a database from the application package assets to
     * the internal data system inside this method will result in a corrupted
     * database in the internal data system.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        /*
         * Signal that the database needs to be upgraded for the copy method of
         * creation. The copy process must be performed after the database has
         * been opened or the database will be corrupted.
         */
        upgradeDatabase = true;

        /*
         * Code to update the database via execution of sql statements goes
         * here.
         */

        /*
         * This will upgrade by reading a sql file and executing the commands in
         * it.
         */
        // try {
        // InputStream is = myContext.getResources().getAssets().open(
        // "upgrade_database.sql");
        //
        // String[] statements = FileHelper.parseSqlFile(is);
        //
        // for (String statement : statements) {
        // db.execSQL(statement);
        // }
        // } catch (Exception ex) {
        // ex.printStackTrace();
        // }
    }

    /**
     * Called everytime the database is opened by getReadableDatabase or
     * getWritableDatabase. This is called after onCreate or onUpgrade is
     * called.
     */
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    /*
     * Add your public helper methods to access and get content from the
     * database. You could return cursors by doing
     * "return myDataBase.query(....)" so it'd be easy to you to create adapters
     * for your views.
     */

}

Here's the FileHelper class that contains methods for byte stream copying files and parsing sql files.

package android.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.channels.FileChannel;

/**
 * @author Danny Remington - MacroSolve
 * 
 *         Helper class for common tasks using files.
 * 
 */
public class FileHelper {
    /**
     * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
     * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
     * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
     * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
     * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
     * operation.
     * 
     * @param fromFile
     *            - InputStream for the file to copy from.
     * @param toFile
     *            - InputStream for the file to copy to.
     */
    public static void copyFile(InputStream fromFile, OutputStream toFile) throws IOException {
        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;

        try {
            while ((length = fromFile.read(buffer)) > 0) {
                toFile.write(buffer, 0, length);
            }
        }
        // Close the streams
        finally {
            try {
                if (toFile != null) {
                    try {
                        toFile.flush();
                    } finally {
                        toFile.close();
                    }
            }
            } finally {
                if (fromFile != null) {
                    fromFile.close();
                }
            }
        }
    }

    /**
     * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
     * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
     * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
     * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
     * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
     * operation.
     * 
     * @param fromFile
     *            - String specifying the path of the file to copy from.
     * @param toFile
     *            - String specifying the path of the file to copy to.
     */
    public static void copyFile(String fromFile, String toFile) throws IOException {
        copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
    }

    /**
     * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
     * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
     * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
     * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
     * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
     * operation.
     * 
     * @param fromFile
     *            - File for the file to copy from.
     * @param toFile
     *            - File for the file to copy to.
     */
    public static void copyFile(File fromFile, File toFile) throws IOException {
        copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
    }

    /**
     * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
     * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
     * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
     * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
     * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
     * operation.
     * 
     * @param fromFile
     *            - FileInputStream for the file to copy from.
     * @param toFile
     *            - FileInputStream for the file to copy to.
     */
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = fromFile.getChannel();
        FileChannel toChannel = toFile.getChannel();

        try {
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }

    /**
     * Parses a file containing sql statements into a String array that contains
     * only the sql statements. Comments and white spaces in the file are not
     * parsed into the String array. Note the file must not contained malformed
     * comments and all sql statements must end with a semi-colon ";" in order
     * for the file to be parsed correctly. The sql statements in the String
     * array will not end with a semi-colon ";".
     * 
     * @param sqlFile
     *            - String containing the path for the file that contains sql
     *            statements.
     * 
     * @return String array containing the sql statements.
     */
    public static String[] parseSqlFile(String sqlFile) throws IOException {
        return parseSqlFile(new BufferedReader(new FileReader(sqlFile)));
    }

    /**
     * Parses a file containing sql statements into a String array that contains
     * only the sql statements. Comments and white spaces in the file are not
     * parsed into the String array. Note the file must not contained malformed
     * comments and all sql statements must end with a semi-colon ";" in order
     * for the file to be parsed correctly. The sql statements in the String
     * array will not end with a semi-colon ";".
     * 
     * @param sqlFile
     *            - InputStream for the file that contains sql statements.
     * 
     * @return String array containing the sql statements.
     */
    public static String[] parseSqlFile(InputStream sqlFile) throws IOException {
        return parseSqlFile(new BufferedReader(new InputStreamReader(sqlFile)));
    }

    /**
     * Parses a file containing sql statements into a String array that contains
     * only the sql statements. Comments and white spaces in the file are not
     * parsed into the String array. Note the file must not contained malformed
     * comments and all sql statements must end with a semi-colon ";" in order
     * for the file to be parsed correctly. The sql statements in the String
     * array will not end with a semi-colon ";".
     * 
     * @param sqlFile
     *            - Reader for the file that contains sql statements.
     * 
     * @return String array containing the sql statements.
     */
    public static String[] parseSqlFile(Reader sqlFile) throws IOException {
        return parseSqlFile(new BufferedReader(sqlFile));
    }

    /**
     * Parses a file containing sql statements into a String array that contains
     * only the sql statements. Comments and white spaces in the file are not
     * parsed into the String array. Note the file must not contained malformed
     * comments and all sql statements must end with a semi-colon ";" in order
     * for the file to be parsed correctly. The sql statements in the String
     * array will not end with a semi-colon ";".
     * 
     * @param sqlFile
     *            - BufferedReader for the file that contains sql statements.
     * 
     * @return String array containing the sql statements.
     */
    public static String[] parseSqlFile(BufferedReader sqlFile) throws IOException {
        String line;
        StringBuilder sql = new StringBuilder();
        String multiLineComment = null;

        while ((line = sqlFile.readLine()) != null) {
            line = line.trim();

            // Check for start of multi-line comment
            if (multiLineComment == null) {
                // Check for first multi-line comment type
                if (line.startsWith("/*")) {
                    if (!line.endsWith("}")) {
                        multiLineComment = "/*";
                    }
                // Check for second multi-line comment type
                } else if (line.startsWith("{")) {
                    if (!line.endsWith("}")) {
                        multiLineComment = "{";
                }
                // Append line if line is not empty or a single line comment
                } else if (!line.startsWith("--") && !line.equals("")) {
                    sql.append(line);
                } // Check for matching end comment
            } else if (multiLineComment.equals("/*")) {
                if (line.endsWith("*/")) {
                    multiLineComment = null;
                }
            // Check for matching end comment
            } else if (multiLineComment.equals("{")) {
                if (line.endsWith("}")) {
                    multiLineComment = null;
                }
            }

        }

        sqlFile.close();

        return sql.toString().split(";");
    }

}

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

MySQL Great Circle Distance (Haversine formula)

I thought my javascript implementation would be a good reference to:

/*
 * Check to see if the second coord is within the precision ( meters )
 * of the first coord and return accordingly
 */
function checkWithinBound(coord_one, coord_two, precision) {
    var distance = 3959000 * Math.acos( 
        Math.cos( degree_to_radian( coord_two.lat ) ) * 
        Math.cos( degree_to_radian( coord_one.lat ) ) * 
        Math.cos( 
            degree_to_radian( coord_one.lng ) - degree_to_radian( coord_two.lng ) 
        ) +
        Math.sin( degree_to_radian( coord_two.lat ) ) * 
        Math.sin( degree_to_radian( coord_one.lat ) ) 
    );
    return distance <= precision;
}

/**
 * Get radian from given degree
 */
function degree_to_radian(degree) {
    return degree * (Math.PI / 180);
}

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

How to replace (or strip) an extension from a filename in Python?

I prefer the following one-liner approach using str.rsplit():

my_filename.rsplit('.', 1)[0] + '.jpg'

Example:

>>> my_filename = '/home/user/somefile.txt'
>>> my_filename.rsplit('.', 1)
>>> ['/home/user/somefile', 'txt']

CSS - How to Style a Selected Radio Buttons Label?

Here's an accessible solution

_x000D_
_x000D_
label {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
label input {_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
label:focus-within {_x000D_
  outline: 1px solid orange;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <label><input type="radio" value="all" checked>All</label>_x000D_
  <label><input type="radio" value="false">Open</label>_x000D_
  <label><input type="radio" value="true">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best way to change the background color for an NSView

Think I figured out how to do it:

- (void)drawRect:(NSRect)dirtyRect {
    // Fill in background Color
    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
    CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}

How to convert a char array back to a string?

You can use String.valueOf method.

For example,

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String b = String.valueOf(a);
System.out.println("Char Array back to String is: " + b);

For more on char array to string you can refer links below

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

https://www.flowerbrackets.com/convert-char-array-to-string-java/

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Is it possible that you can avoid using wsdl2java? You can straight away use CXF FrontEnd APIs to invoke your SOAP Webservice. The only catch is that you need to create your SEI and VOs on your client end. Here is a sample code.

package com.aranin.weblog4j.client;

import com.aranin.weblog4j.services.BookShelfService;
import com.aranin.weblog4j.vo.BookVO;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

public class DemoClient {
    public static void main(String[] args){
        String serviceUrl = "http://localhost:8080/weblog4jdemo/bookshelfservice";
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(BookShelfService.class);
        factory.setAddress(serviceUrl);
        BookShelfService bookService = (BookShelfService) factory.create();

        //insert book
        BookVO bookVO = new BookVO();
        bookVO.setAuthor("Issac Asimov");
        bookVO.setBookName("Foundation and Earth");

        String result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        bookVO = new BookVO();
        bookVO.setAuthor("Issac Asimov");
        bookVO.setBookName("Foundation and Empire");

        result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        bookVO = new BookVO();
        bookVO.setAuthor("Arthur C Clarke");
        bookVO.setBookName("Rama Revealed");

        result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        //retrieve book

        bookVO = bookService.getBook("Foundation and Earth");

        System.out.println("book name : " + bookVO.getBookName());
        System.out.println("book author : " + bookVO.getAuthor());

    }
}

You can see the full tutorial here http://weblog4j.com/2012/05/01/developing-soap-web-service-using-apache-cxf/

How can I find which tables reference a given table in Oracle SQL Developer?

Replace [Your TABLE] with emp in the query below

select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
  from all_constraints 
 where constraint_type='R'
   and r_constraint_name in (select constraint_name 
                               from all_constraints 
                              where constraint_type in ('P','U') 
                                and table_name='[YOUR TABLE]');

when do you need .ascx files and how would you use them?

Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Just to recap (I'm adding this answer quite a distance from the original question):

  • PHP is unable to allocate what appears to be a small amount of memory
  • the current memory usage at the time the error occrs + the requested amount is less than the memory limit currently in force
  • the system has 6Gb available for use by PHP when this occurs
  • since the problem is resolved by restarting apache - it's apache which is preventing the memory from beig available to PHP

If these are all valid then the only possible explanation is that the 6Gb is very fragmented - which I think is a little unlikely. You didn't say how PHP is invoked from Apache - mod_php? fpm? Fcgi?

I would start by examining each of the above predicates - particularly the free memory one. How do you know that there's 6Gb free when the error occurs? A more likely cause is that there's a memory leak occurring which you're not spotting.

You've not provided any details of how apache is configured; I'd also have a look at reducing MaxRequestsPerChild and MaxMemFree. (I'm not very familiar with worker apache where this will apply per thread - really you need a limit per process). If you provided the core setting from the apache config then maybe we could make further suggestions.

Unless you are using Ajax extensively, make sure your keepalive time is 2 or less.

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

How to get day of the month?

tl;dr

LocalDate           // Represent a date-only, without time-of-day and without time zone.
.now()              // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth()    // Interrogate for the day of the month (1-31). 

java.time

The modern approach is the LocalDate class to represent a date-only value.

A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
int dayOfMonth = ld.getDayOfMonth();

You can also get the day-of-week.

DayOfWeek dow = ld.getDayOfWeek();

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?

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.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.

Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.

Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();

Or use similar code with the LocalDate class that has no time-of-day portion.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

You might be able to get what you want by using Console2 with Putty or Plink.

How to add text inside the doughnut chart using Chart.js?

You can also paste mayankcpdixit's code in onAnimationComplete option :

// ...
var myDoughnutChart = new Chart(ctx).Doughnut(data, {
    onAnimationComplete: function() {
        ctx.fillText(data[0].value + "%", 100 - 20, 100, 200);
    }
});

Text will be shown after animation

How to recursively download a folder via FTP on Linux

ncftp -u <user> -p <pass> <server>
ncftp> mget directory

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

how to define variable in jquery

In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The main point is this:

col-lg-* col-md-* col-xs-* col-sm define how many columns will there be in these different screen sizes.

Example: if you want there to be two columns in desktop screens and in phone screens you put two col-md-6 and two col-xs-6 classes in your columns.

If you want there to be two columns in desktop screens and only one column in phone screens (ie two rows stacked on top of each other) you put two col-md-6 and two col-xs-12 in your columns and because sum will be 24 they will auto stack on top of each other, or just leave xs style out.

Use of var keyword in C#

I think the use of var should be coupled with wisely-chosen variable names.

I have no problem using var in a foreach statement, provided it's not like this:

foreach (var c in list) { ... }

If it were more like this:

foreach (var customer in list) { ... }

... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.

The same can apply to other situations. This is pretty useless:

var x = SaveFoo(foo);

... but this makes sense:

var saveSucceeded = SaveFoo(foo);

Each to his own, I guess. I've found myself doing this, which is just insane:

var f = (float)3;

I need some sort of 12-step var program. My name is Matt, and I (ab)use var.

How do I find the location of Python module sources?

Another way to check if you have multiple python versions installed, from the terminal.

-MBP:~python3 -m pip show pyperclip

Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-

MBP:~ python -m pip show pyperclip

Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages

Angular 2 Routing run in new tab

Try this please, <a target="_blank" routerLink="/Page2">


Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw

import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';

@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
    //@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
    @Input('routerLink') link: string;
    constructor(private el: ElementRef, @Inject(Window) private win:Window) {
    }
    @HostListener('mousedown') onMouseEnter() {
        this.win.open(this.link || 'main/default');
    }
}

Notice, Window is provided and OpenLinkInNewWindowDirective declared below:

import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';


const appRoutes: Routes = [
  { path: '', pathMatch: 'full', component: AppDefaultComponent },
  { path: 'home', component: AppComponent },
  { path: 'about', component: AppAboutComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [{ provide: Window, useValue: window }],
  bootstrap: [AppComponent]
})
export class AppModule { }

First link opens in new Window, second one will not:

<h1>
    {{title}}
    <ul>
        <li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
        <li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
    </ul>
    <div style="background-color:#eee;">
        <router-outlet></router-outlet>
    </div>
</h1>

Tada! ..and you are welcome =)

Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2"> works

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Here's a demo:

http://jsfiddle.net/VFVMv/

Create a Date with a set timezone without using a string representation

Best Solution I have seen from this came from

http://www.codingforums.com/archive/index.php/t-19663.html

Print Time Function

<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
    offset++;
    tempDate = new Date()
    tempDate.setTime(UTCDate.getTime()+3600000*(offset))
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    }
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)
</script>

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

Full Code Example

<html>

<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>

</head>

<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>

</body>
</html>

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Can Selenium WebDriver open browser windows silently in the background?

If you are using Ubuntu (Gnome), one simple workaround is to install Gnome extension auto-move-window: https://extensions.gnome.org/extension/16/auto-move-windows/

Then set the browser (eg. Chrome) to another workspace (eg. Workspace 2). The browser will silently run in other workspace and not bother you anymore. You can still use Chrome in your workspace without any interruption.

Table is marked as crashed and should be repaired

Run this from your server's command line:

 mysqlcheck --repair --all-databases

Inner join of DataTables in C#

I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:

private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
    DataTable result = new DataTable();
    foreach (DataColumn col in t1.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataColumn col in t2.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataRow row1 in t1.Rows)
    {
        var joinRows = t2.AsEnumerable().Where(row2 =>
            {
                foreach (var parameter in joinOn)
                {
                    if (!parameter(row1, row2)) return false;
                }
                return true;
            });
        foreach (DataRow fromRow in joinRows)
        {
            DataRow insertRow = result.NewRow();
            foreach (DataColumn col1 in t1.Columns)
            {
                insertRow[col1.ColumnName] = row1[col1.ColumnName];
            }
            foreach (DataColumn col2 in t2.Columns)
            {
                insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
            }
            result.Rows.Add(insertRow);
        }
    }
    return result;
}

An example of how you might use this:

var test = JoinDataTables(transactionInfo, transactionItems,
               (row1, row2) =>
               row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));

One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

Shuffle DataFrame rows

You can shuffle the rows of a dataframe by indexing with a shuffled index. For this, you can eg use np.random.permutation (but np.random.choice is also a possibility):

In [12]: df = pd.read_csv(StringIO(s), sep="\s+")

In [13]: df
Out[13]: 
    Col1  Col2  Col3  Type
0      1     2     3     1
1      4     5     6     1
20     7     8     9     2
21    10    11    12     2
45    13    14    15     3
46    16    17    18     3

In [14]: df.iloc[np.random.permutation(len(df))]
Out[14]: 
    Col1  Col2  Col3  Type
46    16    17    18     3
45    13    14    15     3
20     7     8     9     2
0      1     2     3     1
1      4     5     6     1
21    10    11    12     2

If you want to keep the index numbered from 1, 2, .., n as in your example, you can simply reset the index: df_shuffled.reset_index(drop=True)

Passing parameters in Javascript onClick event

onclick vs addEventListener. A matter of preference perhaps (where IE>9).

// Using closures
function onClickLink(e, index) {   
    alert(index);
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.innerHTML = i + '';
    link.addEventListener('click', (function(e) {
        var index = i;
        return function(e) {
            return onClickLink(e, index);
        }
    })(), false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

How abut just using a plain data-* attribute, not as cool as a closure, but..

function onClickLink(e) {       
    alert(e.target.getAttribute('data-index'));
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.setAttribute('data-index', i);
    link.innerHTML = i + ' Hello';        
    link.addEventListener('click', onClickLink, false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

How do I get a file's last modified time in Perl?

You could use stat() or the File::Stat module.

perldoc -f stat

How to determine the current iPhone/device model?

For swift4.0 and above used below code:

let udid = UIDevice.current.identifierForVendor?.uuidString
let name = UIDevice.current.name
let version = UIDevice.current.systemVersion
let modelName = UIDevice.current.model
let osName = UIDevice.current.systemName
let localized = UIDevice.current.localizedModel

print(udid ?? "")
print(name)
print(version)
print(modelName)
print(osName)
print(localized)

How can I get a list of repositories 'apt-get' is checking?

It seems the closest is:

apt-cache policy

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Try sudo update-alternatives --config java from the command line to set the version of the JRE you want to use. This should fix it.

What are the safe characters for making URLs?

The format for an URI is defined in RFC 3986. See section 3.3 for details.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

Changing the render method, as it states in the error message to

        <div className="aaa">
            {this.renderView()}
        </div>

fixed the problem

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

See git gist with instructions here

Run this:

 sudo -u postgres psql

OR

psql -U postgres

in your terminal to get into postgres

NB: If you're on a Mac and both of the commands above failed jump to the section about Mac below

postgres=#

Run

CREATE USER new_username;

Note: Replace new_username with the user you want to create, in your case that will be tom.

postgres=# CREATE USER new_username;
CREATE ROLE

Since you want that user to be able to create a DB, you need to alter the role to superuser

postgres=# ALTER USER new_username SUPERUSER CREATEDB;
ALTER ROLE

To confirm, everything was successful,

postgres=# \du
                         List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
new_username     | Superuser, Create DB                           | {}
postgres         | Superuser, Create role, Create DB, Replication | {}
root             | Superuser, Create role, Create DB              | {}

postgres=# 

Update/Modification (For Mac):

I recently encountered a similar error on my Mac:

psql: FATAL: role "postgres" does not exist

This was because my installation was setup with a database superuser whose role name is the same as your login (short) name.

But some linux scripts assume the superuser has the traditional role name of postgres

How did I resolve this?

If you installed with homebrew run:

/usr/local/opt/postgres/bin/createuser -s postgres

If you're using a specific version of postgres, say 10.5 then run:

/usr/local/Cellar/postgresql/10.5/bin/createuser -s postgres

OR:

/usr/local/Cellar/postgresql/10.5/bin/createuser -s new_username

OR:

/usr/local/opt/postgresql@11/bin/createuser -s postgres

If you installed with postgres.app for Mac run:

/Applications/Postgres.app/Contents/Versions/10.5/bin/createuser -s postgres

P.S: replace 10.5 with your PostgreSQL version

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

The important thing about a sprint is that: within a sprint the functionality that is to be delivered is fixed.

A sprint is normally an iteration. But you can for example have a 4 week sprint, but have 4 one week "internal" iterations within that sprint.

There is a lot of discussion about the length of sprints. I think that if you do it according to the book they should all be the same length.

We have found that a short first sprint to get the development environment up and running, followed by longer basic functionality sprints, then short sprints towards the end of the project, has worked for us.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure the format of the cell is set to 'general' not 'text' (right click on cell and choose format cell)

Formula should look something like this:

=1+2

Convert spark DataFrame column to python list

This will give you all the elements as a list.

mvv_list = list(
    mvv_count_df.select('mvv').toPandas()['mvv']
)

Correct path for img on React.js

Adding file-loader npm to webpack.config.js per its official usage instruction like so:

config.module.rules.push(
    {
        test: /\.(png|jpg|gif)$/,
        use: [
            {
                loader: 'file-loader',
                options: {}
            }
        ]
    }
);

worked for me.

Selecting a Linux I/O Scheduler

It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like

# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"

inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules). This answer is based on the debian wiki

To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:

for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

select2 onchange event only works once

This is what I am using:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to import a module given the full path?

It sounds like you don't want to specifically import the configuration file (which has a whole lot of side effects and additional complications involved), you just want to run it, and be able to access the resulting namespace. The standard library provides an API specifically for that in the form of runpy.run_path:

from runpy import run_path
settings = run_path("/path/to/file.py")

That interface is available in Python 2.7 and Python 3.2+

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Here's an easy-to-use class for sending emails with Gmail. You need to have the JavaMail library added to your build path or just use Maven.

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class GmailSender
{
    private static String protocol = "smtp";

    private String username;
    private String password;

    private Session session;
    private Message message;
    private Multipart multipart;

    public GmailSender()
    {
        this.multipart = new MimeMultipart();
    }

    public void setSender(String username, String password)
    {
        this.username = username;
        this.password = password;

        this.session = getSession();
        this.message = new MimeMessage(session);
    }

    public void addRecipient(String recipient) throws AddressException, MessagingException
    {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }

    public void setSubject(String subject) throws MessagingException
    {
        message.setSubject(subject);
    }

    public void setBody(String body) throws MessagingException
    {
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
    }

    public void send() throws MessagingException
    {
        Transport transport = session.getTransport(protocol);
        transport.connect(username, password);
        transport.sendMessage(message, message.getAllRecipients());

        transport.close();
    }

    public void addAttachment(String filePath) throws MessagingException
    {
        BodyPart messageBodyPart = getFileBodyPart(filePath);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
    }

    private BodyPart getFileBodyPart(String filePath) throws MessagingException
    {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource dataSource = new FileDataSource(filePath);
        messageBodyPart.setDataHandler(new DataHandler(dataSource));
        messageBodyPart.setFileName(filePath);

        return messageBodyPart;
    }

    private Session getSession()
    {
        Properties properties = getMailServerProperties();
        Session session = Session.getDefaultInstance(properties);

        return session;
    }

    private Properties getMailServerProperties()
    {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", protocol + ".gmail.com");
        properties.put("mail.smtp.user", username);
        properties.put("mail.smtp.password", password);
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");

        return properties;
    }
}

Example usage:

GmailSender sender = new GmailSender();
sender.setSender("[email protected]", "mypassword");
sender.addRecipient("[email protected]");
sender.setSubject("The subject");
sender.setBody("The body");
sender.addAttachment("TestFile.txt");
sender.send();

How to determine whether a Pandas Column contains a particular value

in of a Series checks whether the value is in the index:

In [11]: s = pd.Series(list('abc'))

In [12]: s
Out[12]: 
0    a
1    b
2    c
dtype: object

In [13]: 1 in s
Out[13]: True

In [14]: 'a' in s
Out[14]: False

One option is to see if it's in unique values:

In [21]: s.unique()
Out[21]: array(['a', 'b', 'c'], dtype=object)

In [22]: 'a' in s.unique()
Out[22]: True

or a python set:

In [23]: set(s)
Out[23]: {'a', 'b', 'c'}

In [24]: 'a' in set(s)
Out[24]: True

As pointed out by @DSM, it may be more efficient (especially if you're just doing this for one value) to just use in directly on the values:

In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)

In [32]: 'a' in s.values
Out[32]: True

Download and install an ipa from self hosted url on iOS

Answer for Enterprise account with Xcode8

  1. Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.

  2. Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).

  3. Create the Download Link as given below. url should link to your .plist file location.

    itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist

  4. Copy this link and paste it in safari browser in your iphone. It will ask to install :D

Create a html button using this full url

Errno 13 Permission denied Python

If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.

How do I reference a local image in React?

You need to wrap you image source path within {}

<img src={'path/to/one.jpeg'} />

You need to use require if using webpack

<img src={require('path/to/one.jpeg')} />

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

How to get the filename without the extension in Java?

The fluent way:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}

Selecting pandas column by location

Two approaches that come to mind:

>>> df
          A         B         C         D
0  0.424634  1.716633  0.282734  2.086944
1 -1.325816  2.056277  2.583704 -0.776403
2  1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025  1.325853 -2.513373
4  1.366180 -1.265185 -2.184617  0.881514
>>> df.iloc[:, 2]
0    0.282734
1    2.583704
2   -1.560583
3    1.325853
4   -2.184617
Name: C
>>> df[df.columns[2]]
0    0.282734
1    2.583704
2   -1.560583
3    1.325853
4   -2.184617
Name: C

Edit: The original answer suggested the use of df.ix[:,2] but this function is now deprecated. Users should switch to df.iloc[:,2].

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

How to move a marker in Google Maps API

Just try to create the marker and set the draggable property to true. The code will be something as follows:

Marker = new google.maps.Marker({
    position: latlon,
    map: map,            
    draggable: true,
    title: "Drag me!"
});

I hope this helps!

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

Convert between UIImage and Base64 string

Swift 4.2 Extension method

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
    }
}

XCode 9.1 and Swift 4.0

//
// Convert UIImage to a base64 representation
//
class func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

//
// Convert a base64 representation to a UIImage
//
class func convertBase64ToImage(imageString: String) -> UIImage {
    let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
    return UIImage(data: imageData)!
}

How to remove items from a list while iterating?

This answer was originally written in response to a question which has since been marked as duplicate: Removing coordinates from list on python

There are two problems in your code:

1) When using remove(), you attempt to remove integers whereas you need to remove a tuple.

2) The for loop will skip items in your list.

Let's run through what happens when we execute your code:

>>> L1 = [(1,2), (5,6), (-1,-2), (1,-2)]
>>> for (a,b) in L1:
...   if a < 0 or b < 0:
...     L1.remove(a,b)
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: remove() takes exactly one argument (2 given)

The first problem is that you are passing both 'a' and 'b' to remove(), but remove() only accepts a single argument. So how can we get remove() to work properly with your list? We need to figure out what each element of your list is. In this case, each one is a tuple. To see this, let's access one element of the list (indexing starts at 0):

>>> L1[1]
(5, 6)
>>> type(L1[1])
<type 'tuple'>

Aha! Each element of L1 is actually a tuple. So that's what we need to be passing to remove(). Tuples in python are very easy, they're simply made by enclosing values in parentheses. "a, b" is not a tuple, but "(a, b)" is a tuple. So we modify your code and run it again:

# The remove line now includes an extra "()" to make a tuple out of "a,b"
L1.remove((a,b))

This code runs without any error, but let's look at the list it outputs:

L1 is now: [(1, 2), (5, 6), (1, -2)]

Why is (1,-2) still in your list? It turns out modifying the list while using a loop to iterate over it is a very bad idea without special care. The reason that (1, -2) remains in the list is that the locations of each item within the list changed between iterations of the for loop. Let's look at what happens if we feed the above code a longer list:

L1 = [(1,2),(5,6),(-1,-2),(1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
### Outputs:
L1 is now: [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

As you can infer from that result, every time that the conditional statement evaluates to true and a list item is removed, the next iteration of the loop will skip evaluation of the next item in the list because its values are now located at different indices.

The most intuitive solution is to copy the list, then iterate over the original list and only modify the copy. You can try doing so like this:

L2 = L1
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
print L2 is L1
del L1
L1 = L2; del L2
print ("L1 is now: ", L1)

However, the output will be identical to before:

'L1 is now: ', [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

This is because when we created L2, python did not actually create a new object. Instead, it merely referenced L2 to the same object as L1. We can verify this with 'is' which is different from merely "equals" (==).

>>> L2=L1
>>> L1 is L2
True

We can make a true copy using copy.copy(). Then everything works as expected:

import copy
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
L2 = copy.copy(L1)
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
del L1
L1 = L2; del L2
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Finally, there is one cleaner solution than having to make an entirely new copy of L1. The reversed() function:

L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
for (a,b) in reversed(L1):
    if a < 0 or b < 0 :
        L1.remove((a,b))
print ("L1 is now: ", L1)
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Unfortunately, I cannot adequately describe how reversed() works. It returns a 'listreverseiterator' object when a list is passed to it. For practical purposes, you can think of it as creating a reversed copy of its argument. This is the solution I recommend.

Sorting HTML table with JavaScript

I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?

function column_sort() {
    getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();

    comparer = (idx, asc) => (a, b) => ((v1, v2) => 
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    
    table = $(this).closest('table')[0];
    tbody = $(table).find('tbody')[0];

    elm = $(this)[0];
    children = elm.parentNode.children;
    Array.from(tbody.querySelectorAll('tr')).sort( comparer(
        Array.from(children).indexOf(elm), table.asc = !table.asc))
        .forEach(tr => tbody.appendChild(tr) );
}

table.find('thead th').on('click', column_sort);

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

typescript - cloning object

My take on it:

Object.assign(...) only copies properties and we lose the prototype and methods.

Object.create(...) is not copying properties for me and just creating a prototype.

What worked for me is creating a prototype using Object.create(...) and copying properties to it using Object.assign(...):

So for an object foo, make clone like this:

Object.assign(Object.create(foo), foo)

Reading a date using DataReader

This may seem slightly off topic but this was the post I came across when wondering what happens when you read a column as a dateTime in c#. The post reflects the information I would have liked to be able to find about this mechanism. If you worry about utc and timezones then read on

I did a little more research as I'm always very wary of DateTime as a class because of its automatic assumptions about what timezone you are using and because it is way too easy to confuse local times and utc times.

What I'm trying to avoid here is DateTime going 'oh look the computer I'm being run on is in timezone x, therefore this time must also be in timezone x, when I get asked for my values I'll reply as if I'm in that timezone'

I was trying to read a datetime2 column.

The date time you will get back from sql server will end up being of Kind.Unspecified this seems to mean it gets treated like UTC, which is what I wanted.

When reading a date column you also have to read it as a DateTime even though it has no time and is even more prone to screwing up by timezones (as it is on midnight).

I'd certainly consider this to be safer way of reading the DateTime as I suspect it can probably be modified by either settings in sql server or static settings in your c#:

var time = reader.GetDateTime(1);
var utcTime = new DateTime(time.Ticks, DateTimeKind.Utc);

From there you can get the components (Day, Month, Year) etc and format how you like.

If what you have is actually a date + a time then Utc might not be what you want there - since you are mucking around on the client you may need to convert it to a local time first (depending on what the meaning of the time is). However that opens up a whole can of worms.. If you need to do that I'd recommend using a library like noda time. There is TimeZoneInfo in the standard library but after briefly investigating it, it doesn't seem to have a proper set of timezones. You can see the list provided by TimeZoneInfo by using the method TimeZoneInfo.GetSystemTimeZones();

I also discovered sql server management studio doesn't convert times to local time before displaying them. Which is a relief!

Searching in a ArrayList with custom objects for certain strings

For a custom class to work properly in collections you'll have to implement/override the equals() methods of the class. For sorting also override compareTo().

See this article or google about how to implement those methods properly.

How to select first parent DIV using jQuery?

Keep it simple!

var classes = $(this).parent('div').attr('class');

how to open popup window using jsp or jquery?

<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>

function openPopUp()
{
  $('#divId').css('display','block');
$('#divId').dialog();
}

How do I Set Background image in Flutter?

decoration: BoxDecoration(
      image: DecorationImage(
        image: ExactAssetImage("images/background.png"),
        fit: BoxFit.cover
      ),
    ),

this also works inside a container.

Changing text color of menu item in navigation drawer

NavigationView has a method called setItemTextColor(). It uses a ColorStateList.

// FOR NAVIGATION VIEW ITEM TEXT COLOR
int[][] state = new int[][] {
        new int[] {-android.R.attr.state_enabled}, // disabled
        new int[] {android.R.attr.state_enabled}, // enabled
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_pressed}  // pressed

};

int[] color = new int[] {
        Color.WHITE,
        Color.WHITE,
        Color.WHITE,
        Color.WHITE
};

ColorStateList csl = new ColorStateList(state, color);


// FOR NAVIGATION VIEW ITEM ICON COLOR
int[][] states = new int[][] {
        new int[] {-android.R.attr.state_enabled}, // disabled
        new int[] {android.R.attr.state_enabled}, // enabled
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_pressed}  // pressed

};

int[] colors = new int[] {
        Color.WHITE,
        Color.WHITE,
        Color.WHITE,
        Color.WHITE
};

ColorStateList csl2 = new ColorStateList(states, colors);

Here is where I got that answer. And then right after assigning my NavigationView:

if (nightMode == 0) {
            navigationView.setItemTextColor(csl);
            navigationView.setItemIconTintList(csl2);
        }

How to check if an email address exists without sending an email?

Not really.....Some server may not check the "rcpt to:"

http://www.freesoft.org/CIE/RFC/1123/92.htm

Doing so is security risk.....

If the server do, you can write a bot to discovery every address on the server....

Mac SQLite editor

I use Liya from the Mac App Store, it's free, does the job, and the project is maintained (a month or so between updates as of Jan 2013).

I also test a lot on the device. You can access the SQLITE database on the device by:

  1. Add Application supports iTunes file sharing to the info.plist and setting it to YES
  2. Running the app on a device
  3. Open iTunes
  4. Select the device
  5. Select the "Apps" tab
  6. Scroll down to the "File Sharing" section and select the app
  7. The .sqlite file should appear in the right hand pane - select it and "Save to..."
  8. Once it's saved open it up in your favourite SQLITE editor

You can also edit it and copy it back.

EDIT: You can also do this through the Organizer in XCode

  1. Open the Organizer in XCode (Window > Organiser)
  2. Select the "Devices" tab
  3. Expand the device on the left that you want to download/upload data to
  4. Select Applications
  5. Select an Application in the main panel
  6. The panel at the bottom (Data files in Sandbox) will update with all the files within that application
  7. Choose Download and save it somewhere
  8. Find the file in Finder
  9. Right click and select "Show Package Contents"

You can now view, edit, and re-upload the package to your debug device. This can be really handy for keeping snapshots of different states to try out on other devices.

DataGridView - Focus a specific cell

I had a similar problem. I've hidden some columns and afterwards I tried to select the first row. This didn't really work:

datagridview1.Rows[0].Selected = true;

So I tried selecting cell[0,0], but it also didn't work, because this cell was not displayed. Now my final solution is working very well:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

So this selects the complete first row.

How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in ng-model.

Is there possibility of sum of ArrayList without looping

for me the clearest way is this:

doubleList.stream().reduce((a,b)->a+b).get();

or

doubleList.parallelStream().reduce((a,b)->a+b).get();

It also use internal loops, but it is not possible without loops.

Base64 length calculation?

I don't see the simplified formula in other responses. The logic is covered but I wanted a most basic form for my embedded use:

  Unpadded = ((4 * n) + 2) / 3

  Padded = 4 * ((n + 2) / 3)

NOTE: When calculating the unpadded count we round up the integer division i.e. add Divisor-1 which is +2 in this case

How to bind bootstrap popover on dynamic elements

Probably way too late but this is another option:

 $('body').popover({
    selector: '[rel=popover]',
    trigger: 'hover',
    html: true,
    content: function () {
        return $(this).parents('.row').first().find('.metaContainer').html();
    }
});

Why does this code using random strings print "hello world"?

It's all about the input seed. Same seed give the same results all the time. Even you re-run your program again and again it's the same output.

public static void main(String[] args) {

    randomString(-229985452);
    System.out.println("------------");
    randomString(-229985452);

}

private static void randomString(int i) {
    Random ran = new Random(i);
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());

}

Output

-755142161
-1073255141
-369383326
1592674620
-1524828502
------------
-755142161
-1073255141
-369383326
1592674620
-1524828502

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

img onclick call to JavaScript function

This should work(with or without 'javascript:' part):

<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
     alert(a, b);
 }
</script>

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

How do I add options to a DropDownList using jQuery?

With the plugin: jQuery Selection Box. You can do this:

var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false); 

Best way to find the intersection of multiple sets?

From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

where *a_list is list expansion

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.

No shadow by default on Toolbar?

Use /values folders to apply the correct shadow style based on OS version.

For under 5.0 devices, use /values/styles.xml to add windowContentOverlay to the body of your activity:

<style name="MyViewArea">
    <item name="android:foreground">?android:windowContentOverlay</item>
</style>

<style name="MyToolbar">
    <item name="android:background">?attr/colorPrimary</item>
</style>

Then add your own custom shadow by changing your Theme to include:

<item name="android:windowContentOverlay">@drawable/bottom_shadow</item>

You can grab Google's IO app shadow resource here: https://github.com/google/iosched/blob/master/android/src/main/res/drawable-xxhdpi/bottom_shadow.9.png

For 5.0 devices & later, use /values-v21/styles.xml to add elevation to your toolbar using a custom header style:

<style name="MyViewArea">
</style>

<style name="MyToolbar">
    <item name="android:background">?attr/colorPrimary</item>
    <item name="android:elevation">4dp</item>
</style>

Note that in the second case, I had to create an empty MyViewArea style so the windowContentOverlay wouldn't show up too.

[Update: changed resource names and added Google shadow.]

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

The configuration property is called hibernate.hbm2ddl.auto

In our development environment we set hibernate.hbm2ddl.auto=create-drop to drop and create a clean database each time we deploy, so that our database is in a known state.

In theory, you can set hibernate.hbm2ddl.auto=update to update your database with changes to your model, but I would not trust that on a production database. An earlier version of the documentation said that this was experimental, at least; I do not know the current status.

Therefore, for our production database, do not set hibernate.hbm2ddl.auto - the default is to make no database changes. Instead, we manually create an SQL DDL update script that applies changes from one version to the next.

How to push JSON object in to array using javascript

can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data

 var my_json;
    $.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
    console.log(json1);
        var data = [];
    json1.feeds.forEach(function(feed,i){
        console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
        my_json = feed;
        console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
        data.push(my_json);
    }); 

Error: Local workspace file ('angular.json') could not be found

Uninstall the old version of Angular cli, and install Angular CLI global:

Update Angular cli global package to the next version, "@angular/compiler-cli": "^6.0.0"

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@next

Generate a new project and default application by running the following command:

ng new my-project
cd my-project
ng serve

How to export all collections in MongoDB?

I realize that this is quite an old question and that mongodump/mongorestore is clearly the right way if you want a 100% faithful result, including indexes.

However, I needed a quick and dirty solution that would likely be forwards and backwards compatible between old and new versions of MongoDB, provided there's nothing especially wacky going on. And for that I wanted the answer to the original question.

There are other acceptable solutions above, but this Unix pipeline is relatively short and sweet:

mongo --quiet mydatabase --eval "db.getCollectionNames().join('\n')" | \
grep -v system.indexes | \
xargs -L 1 -I {} mongoexport -d mydatabase -c {} --out {}.json

This produces an appropriately named .json file for each collection.

Note that the database name ("mydatabase") appears twice. I'm assuming the database is local and you don't need to pass credentials but it's easy to do that with both mongo and mongoexport.

Note that I'm using grep -v to discard system.indexes, because I don't want an older version of MongoDB to try to interpret a system collection from a newer one. Instead I'm allowing my application to make its usual ensureIndex calls to recreate the indexes.

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

Signing a Windows EXE file

The ASP's magazine ASPects has a detailed description on how to sign code (You have to be a member to read the article). You can download it through http://www.asp-shareware.org/

Here's link to a description how you can make your own test certificate.

This might also be interesting.

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

input() error - NameError: name '...' is not defined

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

Unable to establish SSL connection, how do I fix my SSL cert?

Just a quick note (and possible cause).

You can have a perfectly correct VirtualHost setup with _default_:443 etc. in your Apache .conf file.

But... If there is even one .conf file enabled with incorrect settings that also listens to port 443, then it will bring the whole SSL system down.

Therefore, if you are sure your .conf file is correct, try disabling the other site .conf files in sites-enabled.

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Create thumbnail image

Here is an example to convert high res image into thumbnail size-

protected void Button1_Click(object sender, EventArgs e)
{
    //----------        Getting the Image File
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));

    //----------        Getting Size of Original Image
    double imgHeight = img.Size.Height;
    double imgWidth = img.Size.Width;

    //----------        Getting Decreased Size
    double x = imgWidth / 200;
    int newWidth = Convert.ToInt32(imgWidth / x);
    int newHeight = Convert.ToInt32(imgHeight / x);

    //----------        Creating Small Image
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);

    //----------        Saving Image
    myThumbnail.Save(Server.MapPath("~/profile/NewImage.jpg"));
}
public bool ThumbnailCallback()
{
    return false;
}

Source- http://iknowledgeboy.blogspot.in/2014/03/c-creating-thumbnail-of-large-image-by.html

What is the difference between field, variable, attribute, and property in Java POJOs?

Variables are comprised of fields and non-fields.

Fields can be either:

  1. Static fields or
  2. non-static fields also called instantiations e.g. x = F()

Non-fields can be either:

  1. local variables, the analog of fields but inside a methods rather than outside all of them, or
  2. parameters e.g. y in x = f(y)

In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.

Basic Example (excuse me for my syntax, I am just a beginner)

Class {    
    //fields    

    method1 {              
         //non-fields    

    }    
}

How to style a select tag's option element?

Since version 49+, Chrome has supported styling <option> elements with font-weight. Source: https://code.google.com/p/chromium/issues/detail?id=44917#c22

New SELECT Popup: font-weight style should be applied.

This CL removes themeChromiumSkia.css. |!important| in it prevented to apply font-weight. Now html.css has |font-weight:normal|, and |!important| should be unnecessary.

There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important; in it all this time. It was introduced to the stable Chrome channel in version 49.0.

How to execute XPath one-liners from shell?

clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.

So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"

And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))

How do I use Apache tomcat 7 built in Host Manager gui?

Solution for a fresh install of Tomcat 7 on Ubuntu 12.04.

Edit this file - /etc/tomcat7/tomcat-users.xml to add this xml section -

<tomcat-users>
<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="tomcatadmin" password="tomcat2009" roles="admin,admin-gui,manager-gui"/>
</tomcat-users>

restart Tomcat -

service tomcat7 restart

urls to access managers -

  1. tomcat test page - http://localhost:8080/
  2. manager webapp - http://localhost:8080/manager/html
  3. host-manager webapp - http://localhost:8080/host-manager/html

just wanted to put the latest info out there.

ReactJS - .JS vs .JSX

As already mentioned, there is no difference, if you create a file with .jsx or .js.

I would like to bring another expect of creating the files as .jsx while creating a component.

This is not mandatory, but an architectural approach that we can follow. So, in large projects we divide our components as Presentational components or Container components. Just to brief, in container components we write the logic to get data for the component and render the Presentational component with props. In presentational components, we usually donot write functional logic, presentational components are used to represent the UI with required props.

So, if you check the definition on JSX in React documents.

It says,

const element = <h1>Hello, world!</h1>;

It is called JSX, and it is a syntax extension to JavaScript. 
We recommend using it with React to describe what the UI should look like. 
JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. Instead of artificially separating technologies by putting
markup and logic in separate files, React separates concerns with loosely coupled units 
called “components” that contain both. 

React doesn’t require using JSX, but most people find it helpful as a visual aid when 
working with UI inside the JavaScript code. It also allows React to show more useful 
error and warning messages.

It means, It's not mandatory but you can think of creating presentational components with '.jsx' as it actually binds the props with the UI. and container components, as .js files as those contains logic to get the data.

It's a convention that you can follow while creating the .jsx or .js files, to logically and physically separate the code.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

How do I select between the 1st day of the current month and current day in MySQL?

I used this one

select DATE_ADD(DATE_SUB(LAST_DAY(now()), INTERVAL  1 MONTH),INTERVAL  1 day) first_day
      ,LAST_DAY(now()) last_day, date(now()) today_day

Is it possible to import a whole directory in sass using @import?

You could use a bit of workaround by placing a sass file in folder what you would like to import and import all files in that file like this:

file path:main/current/_current.scss

@import "placeholders"; @import "colors";

and in next dir level file you just use import for file what imported all files from that dir:

file path:main/main.scss

@import "EricMeyerResetCSSv20"; @import "clearfix"; @import "current";

That way you have same number of files, like you are importing the whole dir. Beware of order, file that comes last will override the matching stiles.

How to get function parameter names/values dynamically?

Here is an updated solution that attempts to address all the edge cases mentioned above in a compact way:

function $args(func) {  
    return (func + '')
      .replace(/[/][/].*$/mg,'') // strip single-line comments
      .replace(/\s+/g, '') // strip white space
      .replace(/[/][*][^/*]*[*][/]/g, '') // strip multi-line comments  
      .split('){', 1)[0].replace(/^[^(]*[(]/, '') // extract the parameters  
      .replace(/=[^,]+/g, '') // strip any ES6 defaults  
      .split(',').filter(Boolean); // split & filter [""]
}  

Abbreviated test output (full test cases are attached below):

'function (a,b,c)...' // returns ["a","b","c"]
'function ()...' // returns []
'function named(a, b, c) ...' // returns ["a","b","c"]
'function (a /* = 1 */, b /* = true */) ...' // returns ["a","b"]
'function fprintf(handle, fmt /*, ...*/) ...' // returns ["handle","fmt"]
'function( a, b = 1, c )...' // returns ["a","b","c"]
'function (a=4*(5/3), b) ...' // returns ["a","b"]
'function (a, // single-line comment xjunk) ...' // returns ["a","b"]
'function (a /* fooled you...' // returns ["a","b"]
'function (a /* function() yes */, \n /* no, */b)/* omg! */...' // returns ["a","b"]
'function ( A, b \n,c ,d \n ) \n ...' // returns ["A","b","c","d"]
'function (a,b)...' // returns ["a","b"]
'function $args(func) ...' // returns ["func"]
'null...' // returns ["null"]
'function Object() ...' // returns []

_x000D_
_x000D_
function $args(func) {  _x000D_
    return (func + '')_x000D_
      .replace(/[/][/].*$/mg,'') // strip single-line comments_x000D_
      .replace(/\s+/g, '') // strip white space_x000D_
      .replace(/[/][*][^/*]*[*][/]/g, '') // strip multi-line comments  _x000D_
      .split('){', 1)[0].replace(/^[^(]*[(]/, '') // extract the parameters  _x000D_
      .replace(/=[^,]+/g, '') // strip any ES6 defaults  _x000D_
      .split(',').filter(Boolean); // split & filter [""]_x000D_
}  _x000D_
_x000D_
// test cases  _x000D_
document.getElementById('console_info').innerHTML = (_x000D_
[  _x000D_
  // formatting -- typical  _x000D_
  function(a,b,c){},  _x000D_
  function(){},  _x000D_
  function named(a, b,  c) {  _x000D_
/* multiline body */  _x000D_
  },  _x000D_
    _x000D_
  // default values -- conventional  _x000D_
  function(a /* = 1 */, b /* = true */) { a = a||1; b=b||true; },  _x000D_
  function fprintf(handle, fmt /*, ...*/) { },  _x000D_
  _x000D_
  // default values -- ES6  _x000D_
  "function( a, b = 1, c ){}",  _x000D_
  "function (a=4*(5/3), b) {}",  _x000D_
  _x000D_
  // embedded comments -- sardonic  _x000D_
  function(a, // single-line comment xjunk) {}_x000D_
    b //,c,d_x000D_
  ) // single-line comment_x000D_
  {},  _x000D_
  function(a /* fooled you{*/,b){},  _x000D_
  function /* are you kidding me? (){} */(a /* function() yes */,  _x000D_
   /* no, */b)/* omg! */{/*}}*/},  _x000D_
  _x000D_
  // formatting -- sardonic  _x000D_
  function  (  A,  b  _x000D_
,c  ,d  _x000D_
  )  _x000D_
  {  _x000D_
  },  _x000D_
  _x000D_
  // by reference  _x000D_
  this.jQuery || function (a,b){return new e.fn.init(a,b,h)},_x000D_
  $args,  _x000D_
  _x000D_
  // inadvertent non-function values  _x000D_
  null,  _x000D_
  Object  _x000D_
].map(function(f) {_x000D_
    var abbr = (f + '').replace(/\n/g, '\\n').replace(/\s+|[{]+$/g, ' ').split("{", 1)[0] + "...";_x000D_
    return "    '" + abbr + "' // returns " + JSON.stringify($args(f));_x000D_
  }).join("\n") + "\n"); // output for copy and paste as a markdown snippet
_x000D_
<pre id='console_info'></pre>
_x000D_
_x000D_
_x000D_

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

How to send POST request?

If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 

How to add a RequiredFieldValidator to DropDownList control?

Suppose your drop down list is:

<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>

There are two ways:

<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />

the 2nd way is to use a compare validator:

<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

Semi-transparent color layer over background-image?

You need then a wrapping element with the bg image and in it the content element with the bg color:

<div id="Wrapper">
  <div id="Content">
    <!-- content here -->
  </div>
</div>

and the css:

#Wrapper{
    background:url(../img/bg/diagonalnoise.png); 
    width:300px; 
    height:300px;
}

#Content{
    background-color:rgba(248,247,216,0.7); 
    width:100%; 
    height:100%;
}

Checking for empty queryset in Django

You could also use this:

if(not(orgs)): #if orgs is empty else: #if orgs is not empty

Java Reflection: How to get the name of a variable?

It is not possible at all. Variable names aren't communicated within Java (and might also be removed due to compiler optimizations).

EDIT (related to comments):

If you step back from the idea of having to use it as function parameters, here's an alternative (which I wouldn't use - see below):

public void printFieldNames(Object obj, Foo... foos) {
    List<Foo> fooList = Arrays.asList(foos);
    for(Field field : obj.getClass().getFields()) {
         if(fooList.contains(field.get()) {
              System.out.println(field.getName());
         }
    }
}

There will be issues if a == b, a == r, or b == r or there are other fields which have the same references.

EDIT now unnecessary since question got clarified

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

What is the difference between an interface and abstract class?

An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.

Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code.

hash keys / values as array

Here are implementations from phpjs.org:

This is not my code, I'm just pointing you to a useful resource.

Returning a pointer to a vector element in c++

Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself.

Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element.

In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often.

EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos'

Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer.

Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const_' from the definition of the iterator).

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

How to move files from one git repo to another (not a clone), preserving history

In my case, I didn't need to preserve the repo I was migrating from or preserve any previous history. I had a patch of the same branch, from a different remote

#Source directory
git remote rm origin
#Target directory
git remote add branch-name-from-old-repo ../source_directory

In those two steps, I was able to get the other repo's branch to appear in the same repo.

Finally, I set this branch (that I imported from the other repo) to follow the target repo's mainline (so I could diff them accurately)

git br --set-upstream-to=origin/mainline

Now it behaved as-if it was just another branch I had pushed against that same repo.

How to destroy an object?

This is a simple prove that you cannot destroy an object, you can only destroy a link to it.

$var = (object)['a'=>1];
$var2 = $var;
$var2->a = 2;
unset($var2);
echo $var->a;

returns

2

See it in action here: https://eval.in/1054130

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

DB2 Query to retrieve all table names for a given schema

select name from sysibm.systables 
where name like '%ISP%' 
and type = 'T'

How to run a script file remotely using SSH

Make the script executable by the user "Kev" and then remove the try it running through the command sh kev@server1 /test/foo.sh

Static way to get 'Context' in Android?

Kotlin way:

Manifest:

<application android:name="MyApplication">

</application>

MyApplication.kt

class MyApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: MyApplication
            private set
    }
}

You can then access the property via MyApplication.instance

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Unable to find a @SpringBootConfiguration when doing a JpaTest

In my case I was using the Test class from wrong package. when I replaced import org.junit.Test; with import org.junit.jupiter.api.Test; it worked.

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

Find by key deep in a nested array

Improved @haitaka answer, using the key and predicate

function  deepSearch (object, key, predicate) {
    if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object

    for (let i = 0; i < Object.keys(object).length; i++) {
      let value = object[Object.keys(object)[i]];
      if (typeof value === "object" && value != null) {
        let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
        if (o != null) return o
      }
    }
    return null
}

So this can be invoked as:

var result = deepSearch(myObject, 'id', (k, v) => v === 1);

or

var result = deepSearch(myObject, 'title', (k, v) => v === 'Some Recommends');

Here is the demo: http://jsfiddle.net/a21dx6c0/

EDITED

In the same way you can find more than one object

function deepSearchItems(object, key, predicate) {
        let ret = [];
        if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) {
            ret = [...ret, object];
        }
        if (Object.keys(object).length) {
            for (let i = 0; i < Object.keys(object).length; i++) {
                let value = object[Object.keys(object)[i]];
                if (typeof value === "object" && value != null) {
                    let o = this.deepSearchItems(object[Object.keys(object)[i]], key, predicate);
                    if (o != null && o instanceof Array) {
                        ret = [...ret, ...o];
                    }
                }
            }
        }
        return ret;
    }

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

How to design RESTful search/filtering?

If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.

What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.

Use URL or Query parameters instead of request body parameters, e.g.:

/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx 

In fact, the HTTP RFC 7231 says that:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

For more information take a look here.

Html table with button on each row

Pretty sure this solves what you're looking for:

HTML:

<table>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
</table>

Javascript (using jQuery):

$(document).ready(function(){
    $('.editbtn').click(function(){
        $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
    });
});

Edit:

Apparently I should have looked at your sample code first ;)

You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

By using classes, you can apply the same logic to multiple elements without any conflicts.

JSFiddle sample

Getting value from a cell from a gridview on RowDataBound event

I had a similar question, but found the solution through a slightly different approach. Instead of looking up the control as Chris suggested, I first changed the way the field was specified in the .aspx page. Instead of using a <asp:TemplateField ...> tag, I changed the field in question to use <asp:BoundField ...>. Then, when I got to the RowDataBound event, the data could be accessed in the cell directly.

The relevant fragments: First, the aspx page:

<asp:GridView ID="gvVarianceReport" runat="server" ... >
...Other fields...
    <asp:BoundField DataField="TotalExpected" 
     HeaderText="Total Expected <br />Filtration Events" 
     HtmlEncode="False" ItemStyle-HorizontalAlign="Left" 
     SortExpression="TotalExpected" />
...
</asp:Gridview>

Then in the RowDataBound event I can access the values directly:

protected void gvVarianceReport_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.Row.Cells[2].Text == "0")
    {
        e.Row.Cells[2].Text = "N/A";
        e.Row.Cells[3].Text = "N/A";
        e.Row.Cells[4].Text = "N/A";
    }
}

If someone could comment on why this works, I'd appreciate it. I don't fully understand why without the BoundField the value is not in the cell after the bind, but you have to look it up via the control.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

When is a C++ destructor called?

Whenever you use "new", that is, attach an address to a pointer, or to say, you claim space on the heap, you need to "delete" it.
1.yes, when you delete something, the destructor is called.
2.When the destructor of the linked list is called, it's objects' destructor is called. But if they are pointers, you need to delete them manually. 3.when the space is claimed by "new".

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

How do you get the length of a list in the JSF expression language?

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

In class MyBean:
public int getSomelistLength() { return this.somelist.length; }

In your JSF page:
#{MyBean.somelistLength}

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

In JSF page:
#{ fn:length(MyBean.somelist) }

Call to getLayoutInflater() in places not in activity

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

Node.js - Maximum call stack size exceeded

If you don't want to implement your own wrapper, you can use a queue system, e.g. async.queue, queue.

Xcode project not showing list of simulators

I ran into another situation where this can occur. I work with a team we use Xcode server for continuous integration. The server wasn't seeing any simulators, but only for one project. I eventually determined that this was due to the fact that the version of Xcode on our server was one release earlier, and the Xcode project was set to build to the newest version available. Simply updating Xcode solved the issue for us.

git rebase: "error: cannot stat 'file': Permission denied"

When I see this on my machine, it's worse than just a "some process has the file open". The actual ownership of the file gets jacked up to the point where I (running as administrator) can only access it after rebooting.

Nearest I can tell, IIS is part of the problem. If I switch between two major branches that require a lot of files to modify, git will delete a file or directory (usually DLLs) while IIS is trying to do something or another with it. At this point, the IIS process automatically overwrites the file on disk with a version that's locked and appears to be owned by nobody.

Stopping IIS at this point doesn't do it. Best I've found out to do is to reboot, and remember to stop IIS before changing across major branches in the future.

I know that doesn't really answer the question, but might be helpful to others.

How to debug "ImagePullBackOff"?

I ran into this issue on GKE and the reason was no credentials for docker.

Running this resolved it:

gcloud auth configure-docker

Get root view from current activity

Kotlin Extension Solution

Use this to simplify access in an Activity. Then you can directly refer to rootView from the Activity, or activity.rootView outside of it:

val Activity.rootView get() = window.decorView.rootView

If you'd like to add the same for Fragments for consistency, add:

val Fragment.rootView get() = view?.rootView

SQL Server copy all rows from one table into another i.e duplicate table

try this single command to both delete and insert the data:

DELETE MyTable
    OUTPUT DELETED.Col1, DELETED.COl2,...
        INTO MyBackupTable

working sample:

--set up the tables
DECLARE @MyTable table (col1 int, col2 varchar(5))
DECLARE @MyBackupTable table (col1 int, col2 varchar(5))
INSERT INTO @MyTable VALUES (1,'A')
INSERT INTO @MyTable VALUES (2,'B')
INSERT INTO @MyTable VALUES (3,'C')
INSERT INTO @MyTable VALUES (4,'D')

--single command that does the delete and inserts
DELETE @MyTable
    OUTPUT DELETED.Col1, DELETED.COl2
        INTO @MyBackupTable

--show both tables final values
select * from @MyTable
select * from @MyBackupTable

OUTPUT:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(4 row(s) affected)
col1        col2
----------- -----

(0 row(s) affected)

col1        col2
----------- -----
1           A
2           B
3           C
4           D

(4 row(s) affected)

What's the purpose of META-INF?

I've noticed that some Java libraries have started using META-INF as a directory in which to include configuration files that should be packaged and included in the CLASSPATH along with JARs. For example, Spring allows you to import XML Files that are on the classpath using:

<import resource="classpath:/META-INF/cxf/cxf.xml" />
<import resource="classpath:/META-INF/cxf/cxf-extensions-*.xml" />

In this example, I'm quoting straight out of the Apache CXF User Guide. On a project I worked on in which we had to allow multiple levels of configuration via Spring, we followed this convention and put our configuration files in META-INF.

When I reflect on this decision, I don't know what exactly would be wrong with simply including the configuration files in a specific Java package, rather than in META-INF. But it seems to be an emerging de facto standard; either that, or an emerging anti-pattern :-)

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Get name of currently executing test in JUnit 4

I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.

How do I auto-hide placeholder text upon focus using css or jquery?

Here is a CSS-only solution (for now, only works in WebKit):

input:focus::-webkit-input-placeholder {
    opacity: 0;
}

Disable mouse scroll wheel zoom on embedded Google Maps

I tried the first answer in this discussion and it wasn't working for me no matter what I did so I came up with my own solution:

Wrap the iframe with a class (.maps in this example) and ideally embedresponsively code: http://embedresponsively.com/ — Change the CSS of the iframe to pointer-events: none and then using jQuery's click function to the parent element you can change the iframes css to pointer-events:auto

HTML

<div class='embed-container maps'>
    <iframe width='600' height='450' frameborder='0' src='http://foo.com'></iframe>
</div>

CSS

.maps iframe{
    pointer-events: none;
}

jQuery

$('.maps').click(function () {
    $('.maps iframe').css("pointer-events", "auto");
});

$( ".maps" ).mouseleave(function() {
  $('.maps iframe').css("pointer-events", "none"); 
});

I'm sure there's a JavaScript only way of doing this, if someone wants to add to this feel free.

The JavaScript way to reactivate the pointer-events is pretty simple. Just give an Id to the iFrame (i.e. "iframe"), then apply an onclick event to the cointainer div:

onclick="document.getElementById('iframe').style.pointerEvents= 'auto'"

<div class="maps" onclick="document.getElementById('iframe').style.pointerEvents= 'auto'">
   <iframe id="iframe" src="" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>

Git diff says subproject is dirty

This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update again:

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Programmatically go back to previous ViewController in Swift

Swift 3

I might be late in the answer but for swift 3 you can do it this way:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))

    // Do any additional setup if required.
}

func backAction(){
    //print("Back Button Clicked")
    dismiss(animated: true, completion: nil)
}

C# Iterating through an enum? (Indexing a System.Array)

You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[] if you ask for typeof(myEnum):

myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));

Then values[0] etc

awk partly string match (if column/word partly matches)

Also possible by looking for substring with index() function:

awk '(index($3, "snow") != 0) {print}' dummy_file

Shorter version:

awk 'index($3, "snow")' dummy_file

Javascript - How to extract filename from a file input control

If you are using jQuery then

$("#fileupload").val();

Can someone explain how to implement the jQuery File Upload plugin?

I struggled with this plugin for a while on Rails, and then someone gemified it obsoleting all the code I had created.

Although it looks like you're not using this in Rails, however if anyone is using it checkout this gem. The source is here --> jQueryFileUpload Rails.

Update:

In order to satisfy the commenter I've updated my answer. Essentially "use this gem, here is the source code" If it disappears then do it the long way.