Skip to content

Instantly share code, notes, and snippets.

View stemar's full-sized avatar

Steven Marshall stemar

View GitHub Profile
@stemar
stemar / p.js
Last active August 29, 2015 14:16
JavaScript function that replaces named placeholders in a string template. http://jsfiddle.net/mobc4vss/8/
// Usage: "abc{def}ghi".p({def:"xyz"}); => "abcxyzghi"
String.prototype.p = function(obj) {
return this.replace(/\{[^\}]+\}/g, function(key) {
return obj[key.replace(/^\{([^\}]+)\}$/, "$1")] || key;
});
};
@stemar
stemar / JavaScript window.location
Last active August 29, 2015 14:16
Extend JavaScript window.location with 2 properties
window.location.href returns the URL of the current page
http://www.example.org:8888/foo/bar/index.html?q=baz&w=io#bang
window.location.origin returns the protocol, hostname and port number of a URL
http://www.example.org:8888
window.location.protocol returns the web protocol used (http:// or https://)
http:
window.location.hostname returns the domain name of the web host
@stemar
stemar / trim.js
Created March 16, 2015 23:03
trim.js
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
@stemar
stemar / is_blank.py
Last active October 1, 2015 12:48
is_blank() method in Python
def is_blank(value):
return False if value is not False and value in [0, 0.0] else not value
@stemar
stemar / hsc.php
Last active May 23, 2016 22:47
A UTF-8 compatible htmlspecialchars() with optional arguments. An example of a function with optional arguments.
<?php
function hsc($value, $args=NULL) {
$default_args = array('flags'=>ENT_COMPAT, 'encoding'=>'UTF-8', 'double_encode'=>FALSE);
extract(array_merge($default_args, (array)$args));
return htmlspecialchars((string)$value, (int)$flags, (string)$encoding, (bool)$double_encode);
}
@stemar
stemar / blank.rb
Last active May 23, 2016 23:01
blank? method in Ruby
def blank?
self.respond_to?(:empty?) ? self.empty? : !self
end
@stemar
stemar / loadHTML.php
Last active September 23, 2016 03:33
DOMDocument::loadHTML() removing invalid tags without adding DOCTYPE and <html> tag
<?php
// Invalid end tag </s>
$html = <<<HTML
<table>
<tr>
<td>123</s></td>
<td>456</td>
</tr>
</table>
HTML;
@stemar
stemar / xml_to_array.php
Last active August 22, 2017 13:52
Convert XML to an array and convert the SimpleXMLElement empty arrays into empty strings.
<?php
function xml_to_array($xml) {
return json_decode(str_replace('{}', '""', json_encode(simplexml_load_string($xml))), TRUE);
}
@stemar
stemar / xsd_to_json.php
Created October 19, 2017 22:44
Convert XSD file to JSON file
<?php
function xsd_to_json($xsd_file, $formatted = 448) {
$xml_file = preg_replace('/\.xsd$/', '.xml', $xsd_file);
$json_file = preg_replace('/\.xsd$/', '.json', $xsd_file);
$doc = new DOMDocument();
$doc->preserveWhiteSpace = true;
$doc->load($xsd_file);
$doc->save($xml_file);
$xml = file_get_contents($xml_file);
$obj = str_replace($doc->lastChild->prefix.':', "", $xml);