Recent Gists from andrewbranch
https://github.blog
Updates, ideas, and inspiration from GitHub to help developers build and design software.
フィード
Writing type definitions, on a scale of 1–5
Recent Gists from andrewbranch
writing-type-definitions.md Writing type definitions, on a scale of 1–5By handWith tscWith 3rd party toolEase154Avg. correctness252Flexibility513
1年前
tsc performance consuming .ts vs .d.ts files in npm packages
Recent Gists from andrewbranch
tsc-ts-vs-dts.md Original Tweettsc performance consuming .ts vs .d.ts files in npm packagesWhat if TypeScript libraries published just .ts sources to npm instead of .js and .d.ts files? This might already be tempting for Bun-only libraries, but how will that impact users? This is easy to answer by experimenting on existing libraries that ship .js, .d.ts, and .ts files.RxJS ships .js and .d.ts files, but also .ts files for debugability purposes. By tweaking its package.json "exports", we can compare tsc performance on this file with imports resolving to .d.ts files vs .ts source files:import {} from "rxjs";import {} from "rxjs/ajax";import {} from "rxjs/fetch";import {} from "rxjs/operators";import {} from "rxjs/testing";import {} from "rxjs/webSocket";Results.d.ts.tsFiles268317LOC49k62kInstantiations ❗11k46kMemory92 kB118 kBParse time.76 s.91 sCheck time ❗1.48 s3.02 sTotal time ❗2.58 s4.43 sObviously .ts files look really bad here, which is what I was expecting. I did expect the memory
1年前
Modified avrdude.conf for Adafruit Trinket
Recent Gists from andrewbranch
avrdude.conf This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters # $Id: avrdude.conf.in 1371 2016-02-15 20:15:07Z joerg_wunsch $ -*- text -*- # # AVRDUDE Configuration File # # This file contains configuration data used by AVRDUDE which describes # the programming hardware pinouts and also provides part definitions. # AVRDUDE's "-C" command line option specifies the location of the # configuration file. The "-c" option names the programmer configuration # which must match one of the entry's "id" parameter. The "-p" option # identifies which part AVRDUDE is going to be programming and must match # one of the parts' "id" parameter. # # DO NOT MODIFY THIS FILE. Modifications will be overwritten the next # time a "make install" is run. For user-specific additions, use the # "
7年前
#algorithm challenge: more elegant way to do this
Recent Gists from andrewbranch
transpose-array-test.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters import { describe, it, beforeEach } from 'mocha'; import assert from 'assert'; import transposeArray from './transpose-array'; describe('transpose-array', () => { let array; beforeEach(() => array = [0, 1, 2, 3, 4, 5]); it('works for downward transpositions', () => { let result = transposeArray(array, 4, 2); assert.deepEqual(result, [0, 1, 4, 2, 3, 5]); }); it('works for upward transpositions', () => { let array = [0, 1, 2, 3, 4, 5]; let result = transposeArray(array, 1, 4); assert.deepEqual(result, [0, 2, 3, 4, 1, 5]); }); it('works at the lower bound', () => { let result = transposeArray(array, 0, 3); assert.deepEqual(result, [1, 2, 3, 0, 4, 5]); }); it('works at the upper bound', () => { let re
9年前
One of these is around 10x faster than the other two
Recent Gists from andrewbranch
set-seq-splitting-efficiency.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters // filtered is an Immutable.Seq (lazy sequence) with 307 entries let withinCountry = filtered.filter(p => p.get('locations').some(isSameCountry(yourLocation))); let outsideCountry1 = filtered.filter(p => !withinCountry.includes(p)); let outsideCountry2 = filtered.filter(p => !p.get('locations').some(isSameCountry(yourLocation))); let outsideCountry3 = filtered.toSet().subtract(withinCountry); return withinCountry.sort(someWayOfSorting) .concat(outsideCountryN.sort(someOtherWayOfSorting)) .take(10);
9年前
Variadic sort
Recent Gists from andrewbranch
sort.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters function getTestPeople() { return [{ name: "Kylie", age: 18 }, { name: "Andrew", age: 23 }, { name: "Andrew", age: 18 }, { name: "Clay", age: 23 }]; } function sort() { var sortFunctions = Array.prototype.slice.call(arguments); var lastArgument = sortFunctions.pop(); if (lastArgument.sort) { return lastArgument.sort(function(a, b) { for (var i = 0; i < sortFunctions.length; i++) { var order = sortFunctions[i](a, b); if (order !== 0) { return order; } } return 0; }); } return sortFunctions.reduce(function(bound, arg) { return bound.bind(this, arg); }.bind(this), sort).bind(this, lastArgument); } function byName(a, b) { if (a.name > b.name) { return 1; } else if (a.name < b.name) { return -1; } return 0; } function
9年前
I frequently overcomplicate Promises
Recent Gists from andrewbranch
promise-bad.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters someAsyncMethod() { return new Promise((resolve, reject) => { somePromiseReturningMethod().then(x => { resolve(doSomethingTo(x)); }); }); } promise-good.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters someAsyncMethod() { return somePromiseReturningMethod().then(x => { return doSomethingTo(x); }); }
9年前
Verifying my GitHub identity on keybase.io
Recent Gists from andrewbranch
keybase.md Keybase proofI hereby claim:I am andrewbranch on github.I am andrewbranch (https://keybase.io/andrewbranch) on keybase.I have a public key whose fingerprint is 3F80 A965 F914 BC02 8650 E395 22CC A4B1 20C4 27D2To claim this, I am signing this object:{ "body": { "key": { "fingerprint": "3f80a965f914bc028650e39522cca4b120c427d2", "host": "keybase.io", "key_id": "22cca4b120c427d2", "kid": "010138444fd04ba5f4d5d02e0458368c8b8f4ae46ee26e3829e2e4c5175ac38ca4570a", "uid": "b0edd0144760b0c67f8a4482b838aa19", "username": "andrewbranch" }, "service": { "name": "github", "username": "andrewbranch" }, "type": "web_service_binding", "version": 1 }, "ctime": 1426983307, "expire_in": 157680000, "prev": "68f031cf260c352a284b7656d5f1056c31ea239d49f8824cee0ff50a648b48c9", "seqno": 3, "tag": "signature"}with the key 3F80 A965 F914 BC02 8650 E395 22CC A4B1 20C4 27D2, yielding the signature:-----BEGIN PGP MESSAGE-----Version: Keybase OpenPGP v2.0.8Comment: https://keybase.io/cryptoyMMoAnicfZJ9TFV
10年前
Explore the effect of Promises on JS speed and order of execution
Recent Gists from andrewbranch
defer-with-promise.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters var trash = []; function computationallyIntensiveStuff() { trash.push(Math.pow(Math.pow(Math.cos(Math.sin(Math.random())), Math.random()), Math.random() * 100000)); trash.filter(function (a) { return a > Math.random(); }); } new Promise(function (resolve, reject) { for (var i = 0; i < 1000; i++) { computationallyIntensiveStuff(); } resolve(); }).then(function () { console.log('Promise done: ' + Date.now()); }); console.log('Next statement: ' + Date.now()); // Next statement: 1418958320178 // Promise done: 1418958320180 (2 ms later) defer-with-settimeout.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file i
10年前
Simple, elegant radio button view
Recent Gists from andrewbranch
Readme.md RadioViewUsageJust init with a frame or add a UIView to your nib and set its class to RadioView. (Give it a 1:1 aspect ratio if you want it to look normal.)let radio = RadioView(frame: CGRectMake(0, 0, 30, 30))radio.color = UIColor.redColor()radio.selected = trueRadioView.swift This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters class RadioView: UIView { var selected: Bool = false { didSet { UIView.animateWithDuration(self.fadeTime) { self.inner.alpha = self.selected ? 1 : 0 } } } var color: UIColor = UIColor.blackColor() { didSet { self.layer.borderColor = self.color.CGColor self.inner.layer.backgroundColor = self.color.CGColor } } var fadeTime: NSTimeInterval = 0 private lazy var inner: UIView = { return UIView(frame: CGRectMake(0, 0, 0, 0)) }() override init(
10年前
A nice notification pattern for MVC .NET, along with a better theme for alertify.js
Recent Gists from andrewbranch
_Nested.cshtml This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters @* displays the flash messages via alertify plugin *@ @section head { <script> $(document).ready(function() { var flashes = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Html.Flash(), Newtonsoft.Json.Formatting.None)); for (var i = 0; i < flashes.length; i++) { alertify.log(flashes[i].text, flashes[i].class, 10000); } }); </script> } ActionResultExtensions.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters using System.Collections.Generic; using System.Linq; using System.Web.Mvc;
11年前
Make enums available in JavaScript
Recent Gists from andrewbranch
ModelWithEnum.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters // Drop ModelWithEnum.ThingTypeDictionary into a ViewModel that gets serialized to JSON // for handy, scalable use of enums in JavaScript. For example, you can change // // // if (m.ThingTypeId === 3) // // to // // if (m.ThingTypeId === model.ThingTypeDictionary.Spaceship) namespace App.Models { public class ModelWithEnum { public TypeOfThing ThingTypeId { get; set; } public static Dictionary<string, int> ThingTypeDictionary = Enum.GetValues(typeof(TypeOfThing)).Cast<int>().ToDictionary(t => Enum.GetName(typeof(TypeOfThing), t), t => t); } public enum TypeOfThing { Foo = 1, Bar = 2, Spaceship = 3, Submarine = 4 } }
11年前
Show a custom error page for a custom exception. For example, when trying to access a non-existent database record (app/people/details/9999999).
Recent Gists from andrewbranch
EntityNotFoundException.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters // You could put more information and functionality here if you want. // I just needed an exception distinguishable from other exceptions. // I implemented a "FindOrDie" method in my repository code, from which // I throw this exception whenever a query comes up empty. using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Inspect.Models { [Serializable] public class EntityNotFoundException : Exception { public EntityNotFoundException(string message) : base(message) { } } } EntityNotFoundHandleErrorAttribute.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in
11年前
One-up Bootstrap 3.0.0–3.0.3’s method of accounting for scrollbar width when modal is open.
Recent Gists from andrewbranch
fixBootstrapModalScrollbar.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters // This function courtesy of lostsource: http://stackoverflow.com/questions/13382516 function getScrollbarWidth() { var outer = document.createElement("div"); outer.style.visibility = "hidden"; outer.style.width = "100px"; document.body.appendChild(outer); var widthNoScroll = outer.offsetWidth; outer.style.overflow = "scroll"; var inner = document.createElement("div"); inner.style.width = "100%"; outer.appendChild(inner); var widthWithScroll = inner.offsetWidth; outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; } // Event names are for Bootstrap 3. Adjust for Bootstrap 2. $(document).ready(function() { window.scrollbarWidth = getScrollbarWidth(); var bodyMarginRigh
11年前
SwitchaBLE Light State characteristic write codes
Recent Gists from andrewbranch
KSSBluetoothController.h This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters typedef NS_OPTIONS(NSInteger, LightState) { LightStateOff = 0, LightStateOn = 1 << 0, LightStateToggle = 1 << 1, LightStatePulse = 1 << 2, LightStateStrobe = 1 << 3 };
11年前
Flat styling of select2.
Recent Gists from andrewbranch
select2-override.css This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters .select2-container .select2-choice { height: 34px; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background-color: #fff; background-image: none; background: #fff; } .select2-container .select2-choice .select2-chosen { margin-top: 4px } .select2-container .select2-choice abbr { top: 13px } .select2-container .select2-choice, .select2-container .select2-choice .select2-arrow { -webkit-border-radius: 0; border-radius: 0; border-color: #ccc; } .select2-container .select2-choice .select2-arrow { background-color: #fafafa; background-image: none; background: #fafafa; width: 22px; } .select2-container .select2-choice .select2-arrow b>span { margin: 4px 0 0 6px } .select2-container.selec
11年前
Responds to window resize events. Max font size taken from initial font size (specify with CSS).
Recent Gists from andrewbranch
autoshrink.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters (function($) { function getTextWidth($element) { var tester = $("<div/>").text($element.text()) .css({ "position": "absolute", "float": "left", "white-space": "nowrap", "visibility": "hidden", "font": $element.css("font"), "text-transform": $element.css("text-transform"), "letter-spacing": $element.css("letter-spacing") }) .appendTo($element.parent()), width = tester.innerWidth(); tester.remove(); return width; } function AutoShrinker($element) { this.$element = $element; this.$parent = $element.parent(); this.initialFontSize = parseFloat($element.css("fontSize")); this.currentFontSize = this.initialFontSize; this.leftMarginRatio = parseFloat($element.css("marginLeft")) / this.initialFontSize; this.resize =
11年前
HtmlHelper to generate JavaScript object from C# object
Recent Gists from andrewbranch
ExampleView.aspx This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <%= Html.WriteToJavaScript(Model, "window.model") %> </asp:Content> ScriptExtensions.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; namespace ProjectName.Helpers { public static class ScriptExtensions { public static string WriteToJavaScript(this HtmlHelper helper, object Object, strin
11年前
Bundling with BundleTransformer in ASP.NET MVC. Less files need to have their Build Action set to "Content" in their file properties in order to publish successfully.
Recent Gists from andrewbranch
BundleConfig.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters using System.Web; using System.Web.Optimization; using BundleTransformer.Core.Transformers; namespace Project { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { var styles = new Bundle("~/bundles/stylesheets") .Include( "~/Assets/stylesheets/*.css", "~/Assets/stylesheets/*.less" ); styles.Transforms.Add(new CssTransformer()); bundles.Add(new ScriptBundle("~/bundles/javascripts").IncludeDirectory("~/Assets/javascripts/plugins", "*.js").IncludeDirectory("~/Assets/javascripts", "*.js")); bundles.Add(styles); } } } Global.asax.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the f
11年前
Gets an array of Auburn building names from the web API. Works from auburn.edu domain and subdomains.
Recent Gists from andrewbranch
getAuburnBuildings.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters var auburnBuildingNames; window.getAuburnBuildingNames = function(callback) { if (auburnBuildingNames) { callback(auburnBuildingNames); } else { var buildings; $.getJSON("https://cws.auburn.edu/map/api/3.0/building", function(data) { buildings = $.map(data, function(building, i) { return building.name; }); callback(auburnBuildingNames = buildings); }); } }; // Usage example with Bootstrap Typeahead $(document).ready(function() { getAuburnBuildingNames(function(data) { $("[name*=Building]").typeahead({ source: data }); }); }); getAuburnCalendarEvents.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an
11年前
Easy state and country dropdowns for MVC .NET, current as of 8/2013
Recent Gists from andrewbranch
Country.ascx This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %> <% string defaultCountry = "United States"; if (ViewData.ContainsKey("default")) { defaultCountry = (string)ViewData["default"]; } %> <select id="<%= Html.IdFor(model => model) %>" name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>"<% if (ViewData.ContainsKey("html")) { foreach (var a in HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["html"])) { %> <%= a.Key %>="<%= a.Value %>"<% } } %>> <% if (String.IsNullOrWhiteSpace(Model) && !Inspect.Models.Location.Countries.Keys.Contains(defaultCountry)) { %><option value="<%: defaultCountry %>"><%: defaultCountry %></option><% } %> <% foreach (var country in Inspect.Models.Location.Co
11年前
Files (or snippets of files) to set up a highly flexible custom errors system that works for jQuery AJAX and synchronous calls alike for an ASP.NET MVC project.
Recent Gists from andrewbranch
errors.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters // Include in all Error Views // In conjunction with main.js, allows browser "back" navigation // to clear the error page if the user got here via a bad AJAX call. $(window).hashchange(function() { location.reload(); }); ErrorsController.cs This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters using System.Net; using System.Web.Mvc; namespace ProjectName.Controllers { public class ErrorController : Controller { public ViewResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return
12年前