text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove use of prototype extension This makes the component compatible with newer versions of Ember.
import Ember from 'ember'; import Remarkable from 'remarkable'; import hljs from 'hljs'; const { computed } = Ember; export default Ember.Component.extend({ text: '', typographer: false, linkify: false, html: false, parsedMarkdown: computed('text', 'html', 'typographer', 'linkify', function() { var md = new Remarkable({ typographer: this.get('typographer'), linkify: this.get('linkify'), html: this.get('html'), highlight: function(str, lang) { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(lang, str).value; } catch (err) {} } try { return hljs.highlightAuto(str).value; } catch (err) {} return ''; } }); var html = md.render(this.get('text')); return new Ember.Handlebars.SafeString(html); }) });
import Ember from 'ember'; import Remarkable from 'remarkable'; import hljs from 'hljs'; export default Ember.Component.extend({ text: '', typographer: false, linkify: false, html: false, parsedMarkdown: function() { var md = new Remarkable({ typographer: this.get('typographer'), linkify: this.get('linkify'), html: this.get('html'), highlight: function(str, lang) { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(lang, str).value; } catch (err) {} } try { return hljs.highlightAuto(str).value; } catch (err) {} return ''; } }); var html = md.render(this.get('text')); return new Ember.Handlebars.SafeString(html); }.property('text', 'highlight', 'typographer', 'linkify') });
Kill UI.insert, make UI.render require DOM node
Tinytest.add("stylus - presence", function(test) { var div = document.createElement('div'); UI.render(Template.stylus_test_presence, div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); var leftBorder = getStyleProperty(p, 'border-left-style'); test.equal(leftBorder, "dashed"); document.body.removeChild(div); }); Tinytest.add("stylus - @import", function(test) { var div = document.createElement('div'); UI.render(Template.stylus_test_import, div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); test.equal(getStyleProperty(p, 'font-size'), "20px"); test.equal(getStyleProperty(p, 'border-left-style'), "dashed"); document.body.removeChild(div); });
Tinytest.add("stylus - presence", function(test) { var div = document.createElement('div'); UI.insert(UI.render(Template.stylus_test_presence), div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); var leftBorder = getStyleProperty(p, 'border-left-style'); test.equal(leftBorder, "dashed"); document.body.removeChild(div); }); Tinytest.add("stylus - @import", function(test) { var div = document.createElement('div'); UI.insert(UI.render(Template.stylus_test_import), div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); test.equal(getStyleProperty(p, 'font-size'), "20px"); test.equal(getStyleProperty(p, 'border-left-style'), "dashed"); document.body.removeChild(div); });
Switch ftp server now ftp.kernel.org closed
from wex.url import URL url = 'ftp://anonymous:me@speedtest.tele2.net/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: " + url + "\r\n", b"\r\n", ] expected_content = b''.join(expected_lines) def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 n = 3 r0 = readables[0] first_few_lines = [r0.readline() for i in range(n)] assert first_few_lines == expected_lines[:n]
from wex.url import URL expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: ftp://anonymous:me@ftp.kernel.org/pub/site/README\r\n", b"\r\n", b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) url = 'ftp://anonymous:me@ftp.kernel.org/pub/site/README' def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] first_four_lines = [r0.readline() for i in range(4)] assert first_four_lines == expected_lines[:4]
Fix vw and vh units
export const template = ` <style> :host { width: 50vw; height: 50vh; margin: 0; padding: 0; display: inline-block; font-family: 'Helvetiva Neue', Arial, Helvetica, sans-serif; font-size: 12px; } .url-bar { width: 100%; } </style> <div> <input class="url-bar"> </div> <iframe></iframe> `; class SharedPane extends HTMLElement { static get tagName() { return 'shared-pane'; } connectedCallback() { this.id = this.getAttribute('id'); if(!this.id) { throw new Error('An id is required for shared-pane to function'); } this.root = this.attachShadow({ mode: 'open' }); this.root.innerHTML = template; } } customElements.define(SharedPane.tagName, SharedPane);
export const template = ` <style> :host { width: .5vw; height: .5vh; margin: 0; padding: 0; display: inline-block; font-family: 'Helvetiva Neue', Arial, Helvetica, sans-serif; font-size: 12px; } .url-bar { width: 100%; } </style> <div> <input class="url-bar"> </div> <iframe></iframe> `; class SharedPane extends HTMLElement { static get tagName() { return 'shared-pane'; } connectedCallback() { this.id = this.getAttribute('id'); if(!this.id) { throw new Error('An id is required for shared-pane to function'); } this.root = this.attachShadow({ mode: 'open' }); this.root.innerHTML = template; } } customElements.define(SharedPane.tagName, SharedPane);
Add before each reset to format add
'use strict'; // Load chai const chai = require('chai'); const expect = chai.expect; // Load our module const format = require('../../../../app/lib/queue/format'); // Describe the module describe('Function "add"', () => { beforeEach(() => { format.reset(); }); afterEach(() => { format.reset(); }); it('should export a function', () => { expect(format.add).to.be.a('function'); }); it('should add a single new item', () => { let addResult = format.add('foo'); expect(addResult).to.be.true; expect(format.formats).to.include('foo'); }); it('should add multiple formats when given an array', () => { let addResult = format.add(['foo', 'bar']); expect(addResult).to.be.true; expect(format.formats).to.include.members(['foo', 'bar']); }); it('should update the regex pattern on change', () => { let addResult = format.add('foo'); expect(addResult).to.be.true; let matchResult = 'test file.foo'.match(format.pattern); expect(matchResult).to.not.be.null; }); it('should still be successful when passing an existing format', () => { let addResult = format.add('mkv'); expect(addResult).to.be.true; }); it('should handle an invalid or no argument given', () => { let addResult = format.add(); expect(addResult).to.be.false; }); });
'use strict'; // Load chai const chai = require('chai'); const expect = chai.expect; // Load our module const format = require('../../../../app/lib/queue/format'); // Describe the module describe('Function "add"', () => { afterEach(() => { format.reset(); }); it('should export a function', () => { expect(format.add).to.be.a('function'); }); it('should add a single new item', () => { let addResult = format.add('foo'); expect(addResult).to.be.true; expect(format.formats).to.include('foo'); }); it('should add multiple formats when given an array', () => { let addResult = format.add(['foo', 'bar']); expect(addResult).to.be.true; expect(format.formats).to.include.members(['foo', 'bar']); }); it('should update the regex pattern on change', () => { let addResult = format.add('foo'); expect(addResult).to.be.true; let matchResult = 'test file.foo'.match(format.pattern); expect(matchResult).to.not.be.null; }); it('should still be successful when passing an existing format', () => { let addResult = format.add('mkv'); expect(addResult).to.be.true; }); it('should handle an invalid or no argument given', () => { let addResult = format.add(); expect(addResult).to.be.false; }); });
Change default email to newsletter@uwcs instead of noreply
from django.db import models from django.utils import timezone from django.utils.datetime_safe import strftime from hashlib import sha256 from markdownx.models import MarkdownxField def generate_unsub_token(email, date): return sha256('{date}:{email}'.format(date=date, email=email).encode()).hexdigest() class Subscription(models.Model): email = models.EmailField() date_subscribed = models.DateTimeField(default=timezone.now) unsubscribe_token = models.CharField(max_length=64, blank=True) def save(self, *args, **kwargs): if not self.pk: self.unsubscribe_token = generate_unsub_token(self.email, self.date_subscribed) super(Subscription, self).save(*args, **kwargs) def __str__(self): return self.email class Mail(models.Model): subject = models.CharField(max_length=120) sender_name = models.CharField(max_length=50, default='UWCS Newsletter') sender_email = models.EmailField(default='newsletter@uwcs.co.uk') text = MarkdownxField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return '{subject} - {date}'.format(date=strftime(self.date_created, '%Y-%m-%d'), subject=self.subject)
from django.db import models from django.utils import timezone from django.utils.datetime_safe import strftime from hashlib import sha256 from markdownx.models import MarkdownxField def generate_unsub_token(email, date): return sha256('{date}:{email}'.format(date=date, email=email).encode()).hexdigest() class Subscription(models.Model): email = models.EmailField() date_subscribed = models.DateTimeField(default=timezone.now) unsubscribe_token = models.CharField(max_length=64, blank=True) def save(self, *args, **kwargs): if not self.pk: self.unsubscribe_token = generate_unsub_token(self.email, self.date_subscribed) super(Subscription, self).save(*args, **kwargs) def __str__(self): return self.email class Mail(models.Model): subject = models.CharField(max_length=120) sender_name = models.CharField(max_length=50, default='UWCS Newsletter') sender_email = models.EmailField(default='noreply@uwcs.co.uk') text = MarkdownxField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return '{subject} - {date}'.format(date=strftime(self.date_created, '%Y-%m-%d'), subject=self.subject)
Clean up how loading user page from / works
FlowRouter.route('/', { name: 'landing', action: function() { var loginRedirect = Deps.autorun( function() { if (Meteor.user()) { loginRedirect.stop(); FlowRouter.go('user-home', {userId: Meteor.user()._id}); } }) } }) FlowRouter.route('/user/:userId', { name: 'user-home', action: function(params, queryParams) { todoRoute(params.userId, ['root']); } }); FlowRouter.route("/user/:userId/:breadcrumbs", { name:'user-task', action: function(params, queryParams) { todoRoute(params.userId, params.breadcrumbs.split('-')); } }); var todoRoute = function(userId, breadcrumbs) { Meteor.subscribe("tasks", userId); Session.set('userId', userId); Session.set('breadcrumbs', breadcrumbs); }
FlowRouter.route('/', { name: 'landing', action: function() { if (Meteor.userId()) { FlowRouter.go('user-home', {userId: Meteor.userId()}); } else { var loginRedirect = Accounts.onLogin(function() { FlowRouter.go('user-home', {userId: Meteor.userId()}); loginRedirect.stop(); }); } } }) FlowRouter.route('/user/:userId', { name: 'user-home', action: function(params, queryParams) { todoRoute(params.userId, ['root']); } }); FlowRouter.route("/user/:userId/:breadcrumbs", { name:'user-task', action: function(params, queryParams) { todoRoute(params.userId, params.breadcrumbs.split('-')); } }); var todoRoute = function(userId, breadcrumbs) { Meteor.subscribe("tasks", userId); Session.set('userId', userId); Session.set('breadcrumbs', breadcrumbs); }
Update log location to reflect ubuntu
# Location of Apache Error Log log_location_linux = '/var/log/apache2/error.log' log_location_windows = 'C:\Apache24\logs\error.log' # Regular expression to filter for timestamp in Apache Error Log # # Default timestamp format: (example: [Thu Nov 09 09:04:38.912314 2017]) log_date_regex = "\[([A-Z][a-z]{2} [A-z][a-z]{2} \d{1,2} \d{1,2}\:\d{1,2}\:\d{1,2}\.\d+? \d{4})\]" # # Reverse format: (example: [2017-11-09 08:25:03.002312]) #log_date_regex = "\[([0-9-]{10} [0-9:.]{15})\]" # Date format matching the timestamp format used by Apache # in order to generate matching timestamp ourself # # Default timestamp format: (example: see above) log_date_format = "%a %b %d %H:%M:%S.%f %Y" # # Reverse format: (example: see above) #log_date_format = "%Y-%m-%d %H:%M:%S.%f"
# Location of Apache Error Log log_location_linux = '/var/log/httpd/error_log' log_location_windows = 'C:\Apache24\logs\error.log' # Regular expression to filter for timestamp in Apache Error Log # # Default timestamp format: (example: [Thu Nov 09 09:04:38.912314 2017]) log_date_regex = "\[([A-Z][a-z]{2} [A-z][a-z]{2} \d{1,2} \d{1,2}\:\d{1,2}\:\d{1,2}\.\d+? \d{4})\]" # # Reverse format: (example: [2017-11-09 08:25:03.002312]) #log_date_regex = "\[([0-9-]{10} [0-9:.]{15})\]" # Date format matching the timestamp format used by Apache # in order to generate matching timestamp ourself # # Default timestamp format: (example: see above) log_date_format = "%a %b %d %H:%M:%S.%f %Y" # # Reverse format: (example: see above) #log_date_format = "%Y-%m-%d %H:%M:%S.%f"
Validate command not only exists but was used Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)
""" skele Usage: skele hello skele -h | --help skele --version Options: -h --help Show this screen. --version Show version. Examples: skele hello Help: For help using this tool, please open an issue on the Github repository: https://github.com/rdegges/skele-cli """ from inspect import getmembers, isclass from docopt import docopt from . import __version__ as VERSION def main(): """Main CLI entrypoint.""" import commands options = docopt(__doc__, version=VERSION) # Here we'll try to dynamically match the command the user is trying to run # with a pre-defined command class we've already created. for k, v in options.iteritems(): if hasattr(commands, k) and v: module = getattr(commands, k) commands = getmembers(module, isclass) command = [command[1] for command in commands if command[0] != 'Base'][0] command = command(options) command.run()
""" skele Usage: skele hello skele -h | --help skele --version Options: -h --help Show this screen. --version Show version. Examples: skele hello Help: For help using this tool, please open an issue on the Github repository: https://github.com/rdegges/skele-cli """ from inspect import getmembers, isclass from docopt import docopt from . import __version__ as VERSION def main(): """Main CLI entrypoint.""" import commands options = docopt(__doc__, version=VERSION) # Here we'll try to dynamically match the command the user is trying to run # with a pre-defined command class we've already created. for k, v in options.iteritems(): if hasattr(commands, k): module = getattr(commands, k) commands = getmembers(module, isclass) command = [command[1] for command in commands if command[0] != 'Base'][0] command = command(options) command.run()
Comment out property parser due to commit mistake
import os, sys __file__ = os.path.normpath(os.path.abspath(__file__)) __path__ = os.path.dirname(__file__) # print(__path__) if __path__ not in sys.path: sys.path.insert(0, __path__) from csharp_element import CSharpElement import csharp_class_method_parser import csharp_class_member_parser # import csharp_class_property_parser # class_region = (token_start, token_end) of enclosure class def parse_tokens(tokens_data, class_region, class_name, class_instance): tokens_data = csharp_class_method_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) tokens_data = csharp_class_member_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) # tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) return tokens_data
import os, sys __file__ = os.path.normpath(os.path.abspath(__file__)) __path__ = os.path.dirname(__file__) # print(__path__) if __path__ not in sys.path: sys.path.insert(0, __path__) from csharp_element import CSharpElement import csharp_class_method_parser import csharp_class_member_parser import csharp_class_property_parser # class_region = (token_start, token_end) of enclosure class def parse_tokens(tokens_data, class_region, class_name, class_instance): tokens_data = csharp_class_method_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) tokens_data = csharp_class_member_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance) return tokens_data
Change test to use MultiProcessInvoker
from nose.tools import eq_ # from orges.invoker.simple import SimpleInvoker from orges.invoker.multiprocess import MultiProcessInvoker from orges.invoker.pluggable import PluggableInvoker from orges.main import custom_optimize from orges.optimizer.gridsearchoptimizer import GridSearchOptimizer import orges.test.utils as utils def test_custom_optimize_running_too_long_aborts(): invoker = PluggableInvoker(None, invoker=MultiProcessInvoker()) optimizer = GridSearchOptimizer() f = utils.one_param_sleep_and_negate_f val = custom_optimize(f, optimizer=optimizer, invoker=invoker, timeout=1)[1] # f(a=0) is 0, f(a=1) is -1. Because of the timeout we never see a=1, hence # we except the minimum before the timeout to be 0. eq_(val, 0) if __name__ == '__main__': import nose nose.runmodule()
from nose.tools import eq_ from orges.invoker.simple import SimpleInvoker from orges.invoker.pluggable import PluggableInvoker from orges.main import custom_optimize from orges.optimizer.gridsearchoptimizer import GridSearchOptimizer import orges.test.utils as utils def test_custom_optimize_running_too_long_aborts(): invoker = PluggableInvoker(None, invoker=SimpleInvoker(None)) optimizer = GridSearchOptimizer() f = utils.one_param_sleep_and_negate_f val = custom_optimize(f, optimizer=optimizer, invoker=invoker, timeout=1)[1] # f(a=0) is 0, f(a=1) is -1. Because of the timeout we never see a=1, hence # we except the minimum before the timeout to be 0. eq_(val, 0) if __name__ == '__main__': import nose nose.runmodule()
Fix missing space between lede and rest of article
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
Fix main step change detection
angular.module('facette.ui.pane', []) .directive('ngPane', function() { return { restrict: 'A', scope: {}, controller: 'PaneController' }; }) .controller('PaneController', function($scope, $rootScope, $element) { $rootScope.steps = {}; // Define scope functions $rootScope.switch = function(step) { var element = angular.element('[ng-pane-step="' + step + '"]').show(); element.siblings('[ng-pane-step]').hide(); // Update step in both parent and root scopes (needed for main step change detection) $rootScope.step = $scope.$parent.step = step; }; // Add class on pane element $element.addClass('pane'); // Switch to first pane by default $scope.$evalAsync(function() { $rootScope.switch(1); }); }) .directive('ngPaneStep', function($rootScope) { return { require: '^ngPane', restrict: 'A', scope: {}, link: function(scope, element, attrs) { $rootScope.steps[attrs.ngPaneStep] = element; } }; });
angular.module('facette.ui.pane', []) .directive('ngPane', function() { return { restrict: 'A', scope: {}, controller: 'PaneController' }; }) .controller('PaneController', function($scope, $rootScope, $element) { $rootScope.steps = {}; // Define scope functions $rootScope.switch = function(step) { var element = angular.element('[ng-pane-step="' + step + '"]').show(); element.siblings('[ng-pane-step]').hide(); $scope.$parent.step = step; }; // Add class on pane element $element.addClass('pane'); // Switch to first pane by default $scope.$evalAsync(function() { $rootScope.switch(1); }); }) .directive('ngPaneStep', function($rootScope) { return { require: '^ngPane', restrict: 'A', scope: {}, link: function(scope, element, attrs) { $rootScope.steps[attrs.ngPaneStep] = element; } }; });
Verify that integer variables also work.
import parser, codegen, compile import sys, os, unittest, subprocess DIR = os.path.dirname(__file__) TESTS_DIR = os.path.join(DIR, 'tests') TESTS = [ 'hello', 'print-int', 'multi-stmt', 'int-add', 'var-hello', 'int-var', ] def run(self, key): fullname = os.path.join(TESTS_DIR, key + '.lng') base = fullname.rsplit('.lng', 1)[0] bin = base + '.test' compile.compile(fullname, bin) out = subprocess.check_output([bin]) if os.path.exists(base + '.out'): expected = open(base + '.out').read() else: expected = '' self.assertEquals(out, expected) def testfunc(key): def do(self): return self._do(key) return do attrs = {'_do': run} for key in TESTS: m = testfunc(key) m.__name__ = 'test_%s' % key attrs[m.__name__] = m LangTests = type('LangTests', (unittest.TestCase,), attrs) def suite(): return unittest.makeSuite(LangTests, 'test') if __name__ == '__main__': if len(sys.argv) > 1: print run(None, sys.argv[1]) else: unittest.main(defaultTest='suite')
import parser, codegen, compile import sys, os, unittest, subprocess DIR = os.path.dirname(__file__) TESTS_DIR = os.path.join(DIR, 'tests') TESTS = [ 'hello', 'print-int', 'multi-stmt', 'int-add', 'var-hello', ] def run(self, key): fullname = os.path.join(TESTS_DIR, key + '.lng') base = fullname.rsplit('.lng', 1)[0] bin = base + '.test' compile.compile(fullname, bin) out = subprocess.check_output([bin]) if os.path.exists(base + '.out'): expected = open(base + '.out').read() else: expected = '' self.assertEquals(out, expected) def testfunc(key): def do(self): return self._do(key) return do attrs = {'_do': run} for key in TESTS: m = testfunc(key) m.__name__ = 'test_%s' % key attrs[m.__name__] = m LangTests = type('LangTests', (unittest.TestCase,), attrs) def suite(): return unittest.makeSuite(LangTests, 'test') if __name__ == '__main__': if len(sys.argv) > 1: print run(None, sys.argv[1]) else: unittest.main(defaultTest='suite')
Add options to gulp-chug to clean logs
'use strict'; var gulp = require('gulp'); var chug = require( 'gulp-chug' ); var shell = require('gulp-shell'); var del = require('del'); gulp.task( 'client', function () { return gulp.src( './dontforget-client/gulpfile.js' ) .pipe( chug( { tasks: [ 'default' ], logPackage : false, logScript : false, removeDate : true, removeLineBreaks : true } ) ); } ); gulp.task('server_cleanPublic', function (done) { del('./dontforget-server/public/**/*', done); }); gulp.task('server_copyPublic', ['client', 'server_cleanPublic'], function (done) { return gulp.src(['./dontforget-client/dist/**/*', './dontforget-client/dist/**/.*']) .pipe(gulp.dest('./dontforget-server/public')); }); gulp.task('server_build', ['server_copyPublic'], shell.task('activator test dist', {cwd : 'dontforget-server'})); gulp.task('server', ['server_build']); gulp.task('default', ['server']);
'use strict'; var gulp = require('gulp'); var chug = require( 'gulp-chug' ); var shell = require('gulp-shell'); var del = require('del'); gulp.task( 'client', function () { gulp.src( './dontforget-client/gulpfile.js' ) .pipe( chug( { tasks: [ 'default' ], } ) ); } ); gulp.task('server_cleanPublic', function (done) { del('./dontforget-server/public/**/*', done); }); gulp.task('server_copyPublic', ['client', 'server_cleanPublic'], function (done) { return gulp.src(['./dontforget-client/dist/**/*', './dontforget-client/dist/**/.*']) .pipe(gulp.dest('./dontforget-server/public')); }); gulp.task('server_build', ['server_copyPublic'], shell.task('activator test dist', {cwd : 'dontforget-server'})); gulp.task('server', ['server_build']); gulp.task('default', ['server']);
Fix an issue where the scores would not show if a user left the page, then returned using the browser's back/forward buttons (since the form values would be saved, but the DOM not updated by our logic).
var fields = ['skin', 'location', 'ink', 'layering', 'scarring', 'colors']; var form; $(function() { form = document.forms[0]; $('input').change(onChange); onChange(); }); function onChange() { var scale = {}; var field_count = 0; for (var i = 0; i < fields.length; ++i) { var field = fields[i]; if (form[field].value) { scale[field] = form[field].value; ++field_count; } } var total_points = 0; for (var field in scale) { $('.' + field + '-points').text(scale[field]); total_points += parseInt(scale[field]); } if (field_count == fields.length) { $('.total-points').text(total_points); } }
var fields = ['skin', 'location', 'ink', 'layering', 'scarring', 'colors']; var form; $(function() { form = document.forms[0]; $('input').change(onChange); }); function onChange(e) { var scale = {}; var field_count = 0; for (var i = 0; i < fields.length; ++i) { var field = fields[i]; if (form[field].value) { scale[field] = form[field].value; ++field_count; } } var total_points = 0; for (var field in scale) { $('.' + field + '-points').text(scale[field]); total_points += parseInt(scale[field]); } if (field_count == fields.length) { $('.total-points').text(total_points); } }
Fix capitalization of included Request module
var debug = require( 'debug' )( 'wpcom-vip' ); var Request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.req = new Request( this ); this.auth = {}; } WPCOM_VIP.prototype.API_VERSION = '1'; WPCOM_VIP.prototype.API_TIMEOUT = 10000; WPCOM_VIP.prototype.get = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( arguments ); }; module.exports = WPCOM_VIP;
var debug = require( 'debug' )( 'wpcom-vip' ); var request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.req = new Request( this ); this.auth = {}; } WPCOM_VIP.prototype.API_VERSION = '1'; WPCOM_VIP.prototype.API_TIMEOUT = 10000; WPCOM_VIP.prototype.get = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( arguments ); }; module.exports = WPCOM_VIP;
Remove unused code from readme generator.
/* * broccoli-replace * * Copyright (c) 2014 outaTiME * Licensed under the MIT license. * https://github.com/outaTiME/broccoli-replace/blob/master/LICENSE-MIT */ var fs = require('fs'); var filename = 'node_modules/pattern-replace/README.md'; var readme = fs.readFileSync(filename, 'utf8'); // initialize section var sections = {}; // http://regex101.com/r/wJ2wW8 var pattern = /(\n#{3}\s)(.*)([\s\S]*?)(?=\1|$)/ig; var match; while ((match = pattern.exec(readme)) !== null) { var section = match[2]; var contents = match[3]; // trace /* var msg = "Found " + section + " → "; msg += "Next match starts at " + pattern.lastIndex; console.log(msg); */ sections[section] = contents; } // write readme var Replacer = require('pattern-replace'); var options = { variables: { 'options': function () { var name = 'Replacer Options'; return sections[name] || '_(Coming soon)_'; // empty } } }; var replacer = new Replacer(options); var contents = fs.readFileSync('docs/README.md', 'utf8'); var result = replacer.replace(contents); fs.writeFileSync('README.md', result, 'utf8');
/* * broccoli-replace * http://gruntjs.com/ * * Copyright (c) 2014 outaTiME * Licensed under the MIT license. * https://github.com/outaTiME/broccoli-replace/blob/master/LICENSE-MIT */ var fs = require('fs'); var filename = 'node_modules/pattern-replace/README.md'; var readme = fs.readFileSync(filename, 'utf8'); // initialize section var sections = {}; // http://regex101.com/r/wJ2wW8 var pattern = /(\n#{3}\s)(.*)([\s\S]*?)(?=\1|$)/ig; var match; while ((match = pattern.exec(readme)) !== null) { var section = match[2]; var contents = match[3]; // trace /* var msg = "Found " + section + " → "; msg += "Next match starts at " + pattern.lastIndex; console.log(msg); */ sections[section] = contents; } // took contents from readme section var getSectionContents = function (name) { }; // write readme var Replacer = require('pattern-replace'); var options = { variables: { 'options': function () { var name = 'Replacer Options'; return sections[name] || '_(Coming soon)_'; // empty } } }; var replacer = new Replacer(options); var contents = fs.readFileSync('docs/README.md', 'utf8'); var result = replacer.replace(contents); fs.writeFileSync('README.md', result, 'utf8');
Use lisnters_[i].callback rather than the listener itself. In crrev.com/145145, Chrome extension's addListener doesn't add the callback function to the listeners_, rather it adds an object wrapping the callback and some other metadata. So here needs to refer .callback too. R=zork@chromium.org BUG=136058 TEST=manually verified on lumpy device with installing an IME extension. Review URL: https://chromiumcodereview.appspot.com/10698102 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@145510 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Custom bindings for the input ime API. Only injected into the // v8 contexts for extensions which have permission for the API. var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); chromeHidden.registerCustomHook('input.ime', function() { chrome.input.ime.onKeyEvent.dispatch = function(engineID, keyData) { var args = Array.prototype.slice.call(arguments); if (this.validate_) { var validationErrors = this.validate_(args); if (validationErrors) { chrome.input.ime.eventHandled(requestId, false); return validationErrors; } } if (this.listeners_.length > 1) { console.error('Too many listeners for onKeyEvent: ' + e.stack); chrome.input.ime.eventHandled(requestId, false); return; } for (var i = 0; i < this.listeners_.length; i++) { try { var requestId = keyData.requestId; var result = this.listeners_[i].callback.apply(null, args); chrome.input.ime.eventHandled(requestId, result); } catch (e) { console.error('Error in event handler for onKeyEvent: ' + e.stack); chrome.input.ime.eventHandled(requestId, false); } } }; });
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Custom bindings for the input ime API. Only injected into the // v8 contexts for extensions which have permission for the API. var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); chromeHidden.registerCustomHook('input.ime', function() { chrome.input.ime.onKeyEvent.dispatch = function(engineID, keyData) { var args = Array.prototype.slice.call(arguments); if (this.validate_) { var validationErrors = this.validate_(args); if (validationErrors) { chrome.input.ime.eventHandled(requestId, false); return validationErrors; } } if (this.listeners_.length > 1) { console.error('Too many listeners for onKeyEvent: ' + e.stack); chrome.input.ime.eventHandled(requestId, false); return; } for (var i = 0; i < this.listeners_.length; i++) { try { var requestId = keyData.requestId; var result = this.listeners_[i].apply(null, args); chrome.input.ime.eventHandled(requestId, result); } catch (e) { console.error('Error in event handler for onKeyEvent: ' + e.stack); chrome.input.ime.eventHandled(requestId, false); } } }; });
Make test pass in php 7.0
<?php /** * @param ?array $a * @param array{key:?string} $a2 * @param string $offset */ function example471Isset($a, array $a2, string $offset) { if (isset($a[$offset])) { echo intdiv($a, 2); // Expect array (not null) } if (isset($a2['key'])) { echo intdiv($a2, -2); // Expect array{key:string} (not null) } } /** * @param ?array $a * @param array{key:?string} $a2 * @param array{key:?bool} $a3 * @param string $offset */ function example471NotEmpty(?array $a, array $a2, array $a3, string $offset) { if (!empty($a[$offset])) { echo intdiv($a, 2); } if (!empty($a2['key'])) { echo intdiv($a2, -2); // Expect array{key:string} (not falsey) } if (!empty($a3['key'])) { echo intdiv($a3, -2); // Expect array{key:true} (not falsey) } }
<?php /** * @param ?array $a * @param array{key:?string} $a2 * @param string $offset */ function example471Isset(?array $a, array $a2, string $offset) { if (isset($a[$offset])) { echo intdiv($a, 2); // Expect array (not null) } if (isset($a2['key'])) { echo intdiv($a2, -2); // Expect array{key:string} (not null) } } /** * @param ?array $a * @param array{key:?string} $a2 * @param array{key:?bool} $a3 * @param string $offset */ function example471NotEmpty(?array $a, array $a2, array $a3, string $offset) { if (!empty($a[$offset])) { echo intdiv($a, 2); } if (!empty($a2['key'])) { echo intdiv($a2, -2); // Expect array{key:string} (not falsey) } if (!empty($a3['key'])) { echo intdiv($a3, -2); // Expect array{key:true} (not falsey) } }
Remove unused jshint mention in gulp serve task
var gulp = require('gulp'); var load = require('gulp-load-plugins')(); var browserSync = require('browser-sync'); var reload = browserSync.reload; var url = require('url'); var proxy = require('proxy-middleware'); var historyApiFallback = require('connect-history-api-fallback'); var serve = function(baseDir) { var proxyOptions = url.parse('http://localhost:9000/api/'); proxyOptions.route = '/api'; browserSync({ port: 5200, notify: false, logPrefix: 'PSK', snippetOptions: { rule: { match: '<span id="browser-sync-binding"></span>', fn: function (snippet) { return snippet; } } }, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: { baseDir: baseDir, middleware: [historyApiFallback(), proxy(proxyOptions)] } }); }; // Watch Files For Changes & Reload gulp.task('serve', function () { serve(['src']); gulp.watch(['src/**/*.html'], reload); gulp.watch(['src/styles/**/*.css'], [reload]); gulp.watch(['src/**/*.js'], [reload]); gulp.watch(['app/images/**/*'], reload); });
var gulp = require('gulp'); var load = require('gulp-load-plugins')(); var browserSync = require('browser-sync'); var reload = browserSync.reload; var url = require('url'); var proxy = require('proxy-middleware'); var historyApiFallback = require('connect-history-api-fallback'); var serve = function(baseDir) { var proxyOptions = url.parse('http://localhost:9000/api/'); proxyOptions.route = '/api'; browserSync({ port: 5200, notify: false, logPrefix: 'PSK', snippetOptions: { rule: { match: '<span id="browser-sync-binding"></span>', fn: function (snippet) { return snippet; } } }, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: { baseDir: baseDir, middleware: [historyApiFallback(), proxy(proxyOptions)] } }); }; // Watch Files For Changes & Reload gulp.task('serve', function () { serve(['src']); gulp.watch(['src/**/*.html'], reload); gulp.watch(['src/styles/**/*.css'], [reload]); gulp.watch(['src/**/*.js'], ['jshint', reload]); gulp.watch(['app/images/**/*'], reload); });
Prepare for the next development cycle
from setuptools import setup, find_packages import sys, os version = '0.2.0' setup(name='mytardisbf', version=version, description="Bioformats App for MyTardis", long_description="""\ Bioformats App for extracting metadata and thumbnails from microscopy images\ in MyTardis""", classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='mytardis bioformats', author='Keith Schulze', author_email='keith.schulze@monash.edu', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'numpy>=1.9', 'scipy>=0.15', 'javabridge>=1.0', 'python-bioformats>=1.0' ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import sys, os version = '0.1.0' setup(name='mytardisbf', version=version, description="Bioformats App for MyTardis", long_description="""\ Bioformats App for extracting metadata and thumbnails from microscopy images\ in MyTardis""", classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='mytardis bioformats', author='Keith Schulze', author_email='keith.schulze@monash.edu', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'numpy>=1.9', 'scipy>=0.15', 'javabridge>=1.0', 'python-bioformats>=1.0' ], entry_points=""" # -*- Entry points: -*- """, )
Fix error caused by having typings and spec files in the models directory
'use strict' var browserify = require('browserify') var coffeeify = require('coffeeify') var path = require('path') var fs = require('fs') module.exports = function (rootFolder) { var src = null var b = browserify() b.transform(coffeeify) ;[ 'mongodb', './bundle', './routes', './router', './config', './auth', 'socket.io' ].forEach(function (toIgnore) { b.ignore(toIgnore) }) var modelFiles = fs.readdirSync(rootFolder) modelFiles.filter(function (i) { return i.match(/\.js$/) && !i.match(/\.spec\.js$/) }).forEach(function (modelName) { var modelFile = path.join(rootFolder, modelName) console.log(modelFile) b.add(modelFile) require(modelFile) }) b.bundle(function (err, compiled) { if (err) { throw err } src = compiled console.log('Invisible: Created bundle') }) return function (req, res, next) { if (req.path !== '/invisible.js') { return next() } res.contentType('application/javascript') res.send(src) } }
'use strict'; var browserify = require('browserify'); var coffeeify = require('coffeeify'); var path = require('path'); var fs = require('fs'); module.exports = function(rootFolder) { var src = null; var b = browserify(); b.transform(coffeeify); [ 'mongodb', './bundle', './routes', './router', './config', './auth', 'socket.io' ].forEach(function(toIgnore) { b.ignore(toIgnore); }); var modelFiles = fs.readdirSync(rootFolder); modelFiles.forEach(function(modelName) { var modelFile = path.join(rootFolder, modelName); b.add(modelFile); require(modelFile); }); b.bundle(function(err, compiled) { if (err) { throw err; } src = compiled; console.log('Invisible: Created bundle'); }); return function(req, res, next) { if (req.path !== '/invisible.js') { return next(); } res.contentType('application/javascript'); res.send(src); }; };
docs(site): Add dependabot task to site sidebar
module.exports = { someSidebar: { Docs: [ 'getting-started', 'making-tasks', 'sharing-tasks', 'making-presets', 'mrm-core', 'faq', ], Presets: ['mrm-preset-default'], Tasks: [ 'mrm-task-codecov', 'mrm-task-contributing', 'mrm-task-dependabot', 'mrm-task-editorconfig', 'mrm-task-eslint', 'mrm-task-gitignore', 'mrm-task-license', 'mrm-task-lint-staged', 'mrm-task-package', 'mrm-task-prettier', 'mrm-task-readme', 'mrm-task-semantic-release', 'mrm-task-styleguidist', 'mrm-task-travis', 'mrm-task-typescript', ], }, };
module.exports = { someSidebar: { Docs: [ 'getting-started', 'making-tasks', 'sharing-tasks', 'making-presets', 'mrm-core', 'faq', ], Presets: ['mrm-preset-default'], Tasks: [ 'mrm-task-codecov', 'mrm-task-contributing', 'mrm-task-editorconfig', 'mrm-task-eslint', 'mrm-task-gitignore', 'mrm-task-license', 'mrm-task-lint-staged', 'mrm-task-package', 'mrm-task-prettier', 'mrm-task-readme', 'mrm-task-semantic-release', 'mrm-task-styleguidist', 'mrm-task-travis', 'mrm-task-typescript', ], }, };
Clean up formatting a bit
package com.instagram.common.json.annotation.processor.parent; import com.instagram.common.json.annotation.JsonType; /** * Interface parent to test that polymorphic deserialization works. */ @JsonType( valueExtractFormatter = "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper" + ".parseFromJson(${parser_object})", serializeCodeFormatter = "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper" + ".serializeToJson(${generator_object}, " + "(com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)" + "${object_varname}.${field_varname}, " + "true)") public interface InterfaceParentUUT { }
package com.instagram.common.json.annotation.processor.parent; import com.instagram.common.json.annotation.JsonType; /** * Interface parent to test that polymorphic deserialization works. */ @JsonType( valueExtractFormatter = "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper" + ".parseFromJson(${parser_object})", serializeCodeFormatter = "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper" + ".serializeToJson(${generator_object}, (com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)${object_varname}.${field_varname}, true)") public interface InterfaceParentUUT { }
Include README.md in package metadata
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages from pkg_resources import resource_filename with open("README.md", "r") as fh: long_description = fh.read() # depending on your execution context the version file # may be located in a different place! vsn_path = resource_filename(__name__, 'hvac/version') if not os.path.exists(vsn_path): vsn_path = resource_filename(__name__, 'version') if not os.path.exists(vsn_path): print("%s is missing" % vsn_path) sys.exit(1) setup( name='hvac', version=open(vsn_path, 'r').read(), description='HashiCorp Vault API client', long_description=long_description, long_description_content_type="text/markdown", author='Ian Unruh', author_email='ianunruh@gmail.com', url='https://github.com/ianunruh/hvac', keywords=['hashicorp', 'vault'], classifiers=['License :: OSI Approved :: Apache Software License'], packages=find_packages(), install_requires=[ 'requests>=2.7.0', ], include_package_data=True, package_data={'hvac': ['version']}, extras_require={ 'parser': ['pyhcl>=0.2.1,<0.3.0'] } )
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages from pkg_resources import resource_filename # depending on your execution context the version file # may be located in a different place! vsn_path = resource_filename(__name__, 'hvac/version') if not os.path.exists(vsn_path): vsn_path = resource_filename(__name__, 'version') if not os.path.exists(vsn_path): print("%s is missing" % vsn_path) sys.exit(1) setup( name='hvac', version=open(vsn_path, 'r').read(), description='HashiCorp Vault API client', author='Ian Unruh', author_email='ianunruh@gmail.com', url='https://github.com/ianunruh/hvac', keywords=['hashicorp', 'vault'], classifiers=['License :: OSI Approved :: Apache Software License'], packages=find_packages(), install_requires=[ 'requests>=2.7.0', ], include_package_data=True, package_data={'hvac': ['version']}, extras_require={ 'parser': ['pyhcl>=0.2.1,<0.3.0'] } )
Order feedback items by their timestamp.
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) class Meta: ordering = ["-timestamp"]
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path )
Update the view in prep to display logged transactions.
<?php require_once __DIR__."/../config.php"; require_once __DIR__."/templates/auth_check.php"; require_once __DIR__."/../controllers/history_class.php"; $historyClass = new historyClass; $h_data = $historyClass->readHistory($_COOKIE['USER']); ?> <!DOCTYPE html> <html> <head> <?php require_once SITEROOT."/templates/top.php"; ?> </head> <body> <noscript> <h3>This service requires javascript to be enabled.</h3> <h4>Please turn it on in your browser and refresh the page for proper operation.</h4> </noscript> <?php require_once SITEROOT."/templates/top_menu.php"; ?> <!--// Page title --> <h3>My Access History</h3> <div class="well well-lg"> <p>`My Access History` content here.</p> <?php foreach ($h_data as $transaction) { print_r($transaction); } ?> </div> <?php require_once SITEROOT."/templates/bottom.php"; ?> </body> </html>
<?php require_once "../config.php"; ?> <!DOCTYPE html> <html> <head> <?php require_once SITEROOT."/templates/top.php"; ?> </head> <body> <noscript> <h3>This service requires javascript to be enabled.</h3> <h4>Please turn it on in your browser and refresh the page for proper operation.</h4> </noscript> <?php require_once SITEROOT."/templates/top_menu.php"; ?> <!--// Page title --> <h3>My Access History</h3> <div class="well well-lg"> <p>`My Access History` content here.</p> </div> <?php require_once SITEROOT."/templates/bottom.php"; ?> </body> </html>
Send correct stop to server
import fetch from 'isomorphic-fetch' /* Add a SL public transit stop export const ADD_STOP = 'ADD_STOP' function addStop(stop) { return { type: ADD_STOP, stop } } */ export const START_UPDATING_STOP = 'START_UPDATING_STOP' function startUpdatingStop(stop) { return { type: START_UPDATING_STOP, stop } } export const RECEIVE_STOP_DATA = 'RECEIVE_STOP_DATA' function receiveStopData(stop, data) { return { type: RECEIVE_STOP_DATA, stop, data } } export function fetchStop(stop) { return function(dispatch) { dispatch(startUpdatingStop(stop)) return fetch('http://localhost:3000/stop/'+stop) .then(response => response.json()) .then(json => dispatch(receiveStopData(stop, json))) } }
import fetch from 'isomorphic-fetch' /* Add a SL public transit stop export const ADD_STOP = 'ADD_STOP' function addStop(stop) { return { type: ADD_STOP, stop } } */ export const START_UPDATING_STOP = 'START_UPDATING_STOP' function startUpdatingStop(stop) { return { type: START_UPDATING_STOP, stop } } export const RECEIVE_STOP_DATA = 'RECEIVE_STOP_DATA' function receiveStopData(stop, data) { return { type: RECEIVE_STOP_DATA, stop, data } } export function fetchStop(stop) { return function(dispatch) { dispatch(startUpdatingStop(stop)) return fetch('http://localhost:3000/stop/9260') .then(response => response.json()) .then(json => dispatch(receiveStopData(stop, json))) } }
Exclude the project name when requiring files
/* globals jQuery,QUnit */ jQuery(document).ready(function() { var TestLoader = require('ember-cli/test-loader')['default']; TestLoader.prototype.shouldLoadModule = function(moduleName) { return moduleName.match(/\/.*[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)); }; TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { QUnit.module('TestLoader Failures'); QUnit.test(moduleName + ': could not be loaded', function() { throw error; }); }; var autostart = QUnit.config.autostart !== false; QUnit.config.autostart = false; setTimeout(function() { TestLoader.load(); if (autostart) { QUnit.start(); } }, 250); });
/* globals jQuery,QUnit */ jQuery(document).ready(function() { var TestLoader = require('ember-cli/test-loader')['default']; TestLoader.prototype.shouldLoadModule = function(moduleName) { return moduleName.match(/[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)); }; TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { QUnit.module('TestLoader Failures'); QUnit.test(moduleName + ': could not be loaded', function() { throw error; }); }; var autostart = QUnit.config.autostart !== false; QUnit.config.autostart = false; setTimeout(function() { TestLoader.load(); if (autostart) { QUnit.start(); } }, 250); });
Update config for Webpack 2.0
const { resolve } = require('path'); module.exports = { entry: resolve(__dirname, '../src/index.js'), output: { path: resolve(__dirname, '../dist'), filename: '<%= initialComponentName %>.bundle.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader' ] }, { test: /\.scss$/, use: [ 'raw-loader', 'sass-loader' ] }, { test: /\.(yml|yaml)$/, include: resolve(__dirname, '../translations'), use: [ 'json-loader', 'yaml-loader' ] } ] } };
const { resolve } = require('path'); module.exports = { entry: resolve(__dirname, '../src/index.js'), output: { path: resolve(__dirname, '../dist'), filename: '<%= initialComponentName %>.bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loaders: [ 'raw-loader', 'sass-loader' ] }, { test: /\.(yml|yaml)$/, include: resolve(__dirname, '../translations'), loaders: [ 'json-loader', 'yaml-loader' ] } ] } };
Test if we create interface with UP status
package network import ( "net" "strings" "testing" ) func TestDeviceCreate(t *testing.T) { iface := "tun0" _, err := CreateTunInterface(iface) if err != nil { t.Error(err) } niface, err := net.InterfaceByName(iface) if err != nil { t.Error(err) } if !strings.Contains(niface.Flags.String(), "up") { t.Error("Interface not up") } } func TestCreateDeviceWithIpAddr(t *testing.T) { iface := "tun0" IpAddr := "10.0.0.1/24" _, err := CreateTunInterfaceWithIp(iface, IpAddr) if err != nil { t.Error(err) } ifce, err := net.InterfaceByName(iface) if err != nil { t.Error(err) } addr, err := ifce.Addrs() if err != nil { t.Error(err) } if addr[0].String() != IpAddr { t.Error("Wrong Ip address on device") } }
package network import ( "net" "testing" ) func TestDeviceCreate(t *testing.T) { iface := "tun0" _, err := CreateTunInterface(iface) if err != nil { t.Error(err) } } func TestCreateDeviceWithIpAddr(t *testing.T) { iface := "tun0" IpAddr := "10.0.0.1/24" _, err := CreateTunInterfaceWithIp(iface, IpAddr) if err != nil { t.Error(err) } ifce, err := net.InterfaceByName(iface) if err != nil { t.Error(err) } addr, err := ifce.Addrs() if err != nil { t.Error(err) } if addr[0].String() != IpAddr { t.Error("Wrong Ip address on device") } }
Use the relative path to the executable.
<?php /** * This file is part of the CronSymfonyBundle package. * * (c) Dries De Peuter <dries@nousefreak.be> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cron\CronBundle\Cron; use Symfony\Component\Process\PhpExecutableFinder; /** * @author Dries De Peuter <dries@nousefreak.be> */ class CommandBuilder { /** * @var string */ private $environment; /** * @var string */ private $phpExecutable; /** * @param string $environment */ public function __construct($environment) { $this->environment = $environment; $finder = new PhpExecutableFinder(); $this->phpExecutable = $finder->find(); } /** * @param string $command * * @return string */ public function build($command) { return sprintf('%s %s %s --env=%s', $this->phpExecutable, $_SERVER['SCRIPT_NAME'], $command, $this->environment); } }
<?php /** * This file is part of the CronSymfonyBundle package. * * (c) Dries De Peuter <dries@nousefreak.be> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cron\CronBundle\Cron; use Symfony\Component\Process\PhpExecutableFinder; /** * @author Dries De Peuter <dries@nousefreak.be> */ class CommandBuilder { /** * @var string */ private $environment; /** * @var string */ private $phpExecutable; /** * @param string $environment */ public function __construct($environment) { $this->environment = $environment; $finder = new PhpExecutableFinder(); $this->phpExecutable = $finder->find(); } /** * @param string $command * * @return string */ public function build($command) { return sprintf('%s %s %s --env=%s', $this->phpExecutable, 'app/console', $command, $this->environment); } }
Add link to home page
L.Control.MapRequest = L.Control.extend({ options: { position: "topright" }, initialize: function(options) { L.setOptions(this, options); }, onAdd: function(map) { let self = this; let container = L.DomUtil.create("div", "bm-map-request"); container.innerHTML = "<p>Would you like to play some other map? <a target='blank' href='https://feedback.userreport.com/2229a84e-c2fa-4427-99ab-27639f103569/'>Issue a map request.</a></p>"; container.innerHTML += "<p>Chose the wrong map? <a href='/'>Choose again!</a></p>" L.DomEvent.disableClickPropagation(container); L.DomEvent.disableScrollPropagation(container); return container; } }); L.control.mapRequest = function(opts) { return new L.Control.MapRequest(opts); };
L.Control.MapRequest = L.Control.extend({ options: { position: "topright" }, initialize: function(options) { L.setOptions(this, options); }, onAdd: function(map) { let self = this; let container = L.DomUtil.create("div", "bm-map-request"); container.innerHTML = "<p>Would you like to play some other map? <a target='blank' href='https://feedback.userreport.com/2229a84e-c2fa-4427-99ab-27639f103569/'>Issue a map request.</a></p>"; L.DomEvent.disableClickPropagation(container); L.DomEvent.disableScrollPropagation(container); return container; } }); L.control.mapRequest = function(opts) { return new L.Control.MapRequest(opts); };
Add database notification for new replies
<?php namespace App\Notifications; use App\Mail\NewReplyEmail; use App\Models\Reply; use App\Models\Subscription; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; final class NewReplyNotification extends Notification implements ShouldQueue { use Queueable; /** * @var \App\Models\Reply */ public $reply; /** * @var \App\Models\Subscription */ public $subscription; public function __construct(Reply $reply, Subscription $subscription) { $this->reply = $reply; $this->subscription = $subscription; } public function via(User $user) { return ['mail', 'database']; } public function toMail(User $user) { return (new NewReplyEmail($this->reply, $this->subscription)) ->to($user->emailAddress(), $user->name()); } public function toArray(User $user) { return [ 'type' => 'reply', 'author' => $this->reply->author(), 'reply' => $this->reply, 'thread' => $this->reply->replyAble(), ]; } }
<?php namespace App\Notifications; use App\Mail\NewReplyEmail; use App\Models\Reply; use App\Models\Subscription; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; final class NewReplyNotification extends Notification implements ShouldQueue { use Queueable; /** * @var \App\Models\Reply */ public $reply; /** * @var \App\Models\Subscription */ public $subscription; public function __construct(Reply $reply, Subscription $subscription) { $this->reply = $reply; $this->subscription = $subscription; } public function via(User $user) { return ['mail']; } public function toMail(User $user) { return (new NewReplyEmail($this->reply, $this->subscription)) ->to($user->emailAddress(), $user->name()); } public function toArray(User $user) { return [ // ]; } }
Test should verify internal dir not output dir
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.asset_pipeline = { setUp: function(done) { // setup here if necessary done(); }, concat: function(test) { test.expect(2); var all = fs.readFileSync('build/asset_pipeline/concat/custom.js',{encoding:'utf8'}); // var foo ='bar'; var lorem = 'ipsum'; foo = 'the unexpected'; eval(all); test.equal( lorem, 'ipsum'); test.equal( foo, 'the unexpected'); test.done(); } };
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.asset_pipeline = { setUp: function(done) { // setup here if necessary done(); }, concat: function(test) { test.expect(2); var all = fs.readFileSync('build/artifacts/concat/custom.js',{encoding:'utf8'}); // var foo ='bar'; var lorem = 'ipsum'; foo = 'the unexpected'; eval(all); test.equal( lorem, 'ipsum'); test.equal( foo, 'the unexpected'); test.done(); } };
Replace non-breaking space with regular space
package main import ( "fmt" "time" "github.com/miquella/ask" "github.com/miquella/vaulted/lib" ) type Spawn struct { SessionOptions Command []string DisplayStatus bool } func (s *Spawn) Run(store vaulted.Store) error { session, err := GetSessionWithOptions(store, &s.SessionOptions) if err != nil { return err } timeRemaining := session.Expiration.Sub(time.Now()) timeRemaining = time.Second * time.Duration(timeRemaining.Seconds()) if s.DisplayStatus { ask.Print(fmt.Sprintf("%s — expires: %s (%s remaining)\n", session.Name, session.Expiration.Format("2 Jan 2006 15:04 MST"), timeRemaining)) } code, err := session.Spawn(s.Command) if err != nil { return ErrorWithExitCode{err, 2} } else if *code != 0 { return ErrorWithExitCode{ErrNoError, *code} } return nil }
package main import ( "fmt" "time" "github.com/miquella/ask" "github.com/miquella/vaulted/lib" ) type Spawn struct { SessionOptions Command []string DisplayStatus bool } func (s *Spawn) Run(store vaulted.Store) error { session, err := GetSessionWithOptions(store, &s.SessionOptions) if err != nil { return err } timeRemaining := session.Expiration.Sub(time.Now()) timeRemaining = time.Second * time.Duration(timeRemaining.Seconds()) if s.DisplayStatus { ask.Print(fmt.Sprintf("%s — expires: %s (%s remaining)\n", session.Name, session.Expiration.Format("2 Jan 2006 15:04 MST"), timeRemaining)) } code, err := session.Spawn(s.Command) if err != nil { return ErrorWithExitCode{err, 2} } else if *code != 0 { return ErrorWithExitCode{ErrNoError, *code} } return nil }
Fix comment after dropping the pytz dependency.
""" @author: Bryan Silverthorn <bcs@cargo-cult.org> """ from datetime import tzinfo class UTC(tzinfo): """ The one true time zone. """ def utcoffset(self, dt): """ Return the offset to UTC. """ from datetime import timedelta return timedelta(0) def tzname(self, dt): """ Return the time zone name. """ return "UTC" def dst(self, dt): """ Return the DST offset. """ from datetime import timedelta return timedelta(0) def utc_now(): """ Return a non-naive UTC datetime instance. """ from datetime import datetime as DateTime return DateTime.now(UTC()) def seconds(value): """ Return the equivalent number of seconds, floating-point. """ return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6
""" @author: Bryan Silverthorn <bcs@cargo-cult.org> """ from datetime import tzinfo class UTC(tzinfo): """ The one true time zone. """ def utcoffset(self, dt): """ Return the offset to UTC. """ from datetime import timedelta return timedelta(0) def tzname(self, dt): """ Return the time zone name. """ return "UTC" def dst(self, dt): """ Return the DST offset. """ from datetime import timedelta return timedelta(0) def utc_now(): """ Return a non-naive UTC datetime instance, zoned pytz.utc. """ from datetime import datetime as DateTime return DateTime.now(UTC()) def seconds(value): """ Return the equivalent number of seconds, floating-point. """ return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6
[2.0] Fix bug in detection of global Doctrine Cli Configuration finding the empty replacement configuration before the correct one. git-svn-id: c8c49e1140e1cd2a8fb163f3c2b0f6eec231a71d@7322 625475ce-881a-0410-a577-b389adb331d8
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = null; if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $configuration = ($configuration) ?: new \Doctrine\Common\Cli\Configuration(); $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = new \Doctrine\Common\Cli\Configuration(); if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
Change form field image to archive
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from .models import Image from .widgets import MultipleUpload, CropExample from redactor.widgets import RedactorEditor class ImageModelForm(forms.ModelForm): archive = forms.FileField(required=True, widget=MultipleUpload()) crop_example = forms.CharField(required=False, widget=CropExample()) crop_x1 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_x2 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_y1 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_y2 = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta: model = Image widgets = {'description': RedactorEditor()} def more_image(self): more_image = self.files.getlist('image')[:] if len(more_image) >= 2: del more_image[-1] return more_image return []
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from .models import Image from .widgets import MultipleUpload, CropExample from redactor.widgets import RedactorEditor class ImageModelForm(forms.ModelForm): image = forms.FileField(required=True, widget=MultipleUpload()) crop_example = forms.CharField(required=False, widget=CropExample()) crop_x1 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_x2 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_y1 = forms.CharField(required=False, widget=forms.HiddenInput()) crop_y2 = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta: model = Image widgets = {'description': RedactorEditor()} def more_image(self): more_image = self.files.getlist('image')[:] if len(more_image) >= 2: del more_image[-1] return more_image return []
Make test also work on Windows that uses backslash as path delimiter
import os.path from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): def test_run(self): proc = self.runIn( 'scenario/test_with_module', '-v', '--with-coverage', '--coverage=lib/' ) STATS = ' 8 5 38%' stdout, stderr = proc.communicate() self.assertTestRunOutputMatches( proc, stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS) self.assertTestRunOutputMatches( proc, stderr='TOTAL ' + STATS)
from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): def test_run(self): proc = self.runIn( 'scenario/test_with_module', '-v', '--with-coverage', '--coverage=lib/' ) stdout, stderr = proc.communicate() self.assertTestRunOutputMatches(proc, stderr='lib/mod1 8 5 38%') self.assertTestRunOutputMatches(proc, stderr='TOTAL 8 5 38%')
Add metrics jar to downloader
package com.ForgeEssentials.coremod; /** * Kindly do not reference any FE classes outside the coremod package in this * class. This is a store room for all String[]s used by the coremod, 99% of * stuff is edited here and not in the actual coremod classes. */ public class Data { protected static String[] libraries = { "mysql-connector-java-bin.jar", "H2DB.jar", "worldedit-5.4.6-SNAPSHOT.jar", "Metrics.jar" }; protected static String[] checksums = { "3ae0cff91d7f40d5b4c7cefbbd1eab34025bdc15", "32f12e53b4dab80b721525c01d766b95d22129bb", "de96549f9c31aa9268f649fc6757e7b68b180549", "47a1fc60cc5a16f0e125ca525daa596fd7ac0c3a" }; protected static String[] transformers = { "com.ForgeEssentials.coremod.transformers.FEPermissionsTransformer", "com.ForgeEssentials.coremod.transformers.FEAccessTransformer", "com.ForgeEssentials.coremod.transformers.FEeventAdder" }; }
package com.ForgeEssentials.coremod; /** * Kindly do not reference any FE classes outside the coremod package in this * class. This is a store room for all String[]s used by the coremod, 99% of * stuff is edited here and not in the actual coremod classes. */ public class Data { protected static String[] libraries = { "mysql-connector-java-bin.jar", "H2DB.jar", "worldedit-5.4.6-SNAPSHOT.jar" }; protected static String[] checksums = { "3ae0cff91d7f40d5b4c7cefbbd1eab34025bdc15", "32f12e53b4dab80b721525c01d766b95d22129bb", "de96549f9c31aa9268f649fc6757e7b68b180549" }; protected static String[] transformers = { "com.ForgeEssentials.coremod.transformers.FEPermissionsTransformer", "com.ForgeEssentials.coremod.transformers.FEAccessTransformer", "com.ForgeEssentials.coremod.transformers.FEeventAdder" }; }
Clean up unfinished idea in comment
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.generator; import org.terasology.engine.API; import org.terasology.engine.SimpleUri; import org.terasology.math.Vector3i; import org.terasology.world.ChunkView; import org.terasology.world.chunks.Chunk; import org.terasology.world.chunks.ChunkAPI; /** * @author Immortius */ @API public interface WorldGenerator { SimpleUri getUri(); void setWorldSeed(String seed); void applySecondPass(Vector3i chunkPos, ChunkView view); void createChunk(ChunkAPI chunk); float getFog(float x, float y, float z); float getTemperature(float x, float y, float z); float getHumidity(float x, float y, float z); }
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.generator; import org.terasology.engine.API; import org.terasology.engine.SimpleUri; import org.terasology.math.Vector3i; import org.terasology.world.ChunkView; import org.terasology.world.chunks.Chunk; import org.terasology.world.chunks.ChunkAPI; /** * @author Immortius */ @API public interface WorldGenerator { SimpleUri getUri(); void setWorldSeed(String seed); void applySecondPass(Vector3i chunkPos, ChunkView view); void createChunk(ChunkAPI chunk); //TODO: create a WorldInfo interface to contain the fog, temp, and humidity float getFog(float x, float y, float z); float getTemperature(float x, float y, float z); float getHumidity(float x, float y, float z); }
Add simple logic to driver code test for easy testing
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading def take_50_pictures(): camera_thread = threading.Thread(target=start_camera) camera_thread.start() from get_images_from_pi import get_image, valid_image time.sleep(2) count = 0 while (count < 50): get_image(count) count += 1 def detect_stop_sign(image): reds = image.hueDistance(color=scv.Color.RED) stretch = reds.stretch(20,21) invert = stretch.invert() blobs = invert.findBlobs(minsize=2000) if blobs: for blob in blobs: print blob.area() blob.draw(color=(0, 128, 0)) invert.show() invert.show() time.sleep(3) image = Image('images/0.jpg') x = 0 while (x < 40): image = Image('images/'+ str(x) + '.jpg') detect_stop_sign(image) print x x +=1 exit()
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading # camera_thread = threading.Thread(target=start_camera) # camera_thread.start() # from get_images_from_pi import get_image, valid_image # time.sleep(2) # count = 0 # while (count < 50): # get_image(count) # count += 1 # exit() image = Image('images/stop') image.show() image.show() time.sleep(2) reds = image.hueDistance(color=scv.Color.RED) reds.show() reds.show() time.sleep(2) stretch = reds.stretch(20,21) stretch.show() stretch.show() time.sleep(3) # blobs = image.findBlobs() # if blobs: # for blob in blobs: # print "got a blob" # blob.draw(color=(0, 128, 0)) # image.show() # image.show() # time.sleep(4)
Clear reauthentication in ACP logout This will kill access to the ACP without invalidating the frontend session. By redirecting to the frontend the user can easily perform a full logout.
<?php namespace wcf\acp\action; use wcf\action\AbstractSecureAction; use wcf\system\request\LinkHandler; use wcf\system\WCF; use wcf\util\HeaderUtil; /** * Does the user logout in the admin control panel. * * @author Tim Duesterhus, Marcel Werk * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Action */ class LogoutAction extends AbstractSecureAction { /** * @inheritDoc */ public $loginRequired = true; /** * @inheritDoc */ public function execute() { parent::execute(); // do logout WCF::getSession()->clearReauthentication(); $this->executed(); HeaderUtil::redirect(LinkHandler::getInstance()->getLink(null, [ 'forceFrontend' => true, ])); exit; } }
<?php namespace wcf\acp\action; use wcf\action\AbstractSecureAction; use wcf\system\request\LinkHandler; use wcf\system\WCF; use wcf\util\HeaderUtil; /** * Does the user logout in the admin control panel. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Action */ class LogoutAction extends AbstractSecureAction { /** * @inheritDoc */ public $loginRequired = true; /** * @inheritDoc */ public function execute() { parent::execute(); // do logout WCF::getSession()->delete(); $this->executed(); // forward to index page // warning: if doLogout() writes a cookie this is buggy in MS IIS HeaderUtil::redirect(LinkHandler::getInstance()->getLink('Login')); exit; } }
[pig] Rename app to Pig Editor
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DJANGO_APPS = ['pig'] NICE_NAME = 'Pig Editor' MENU_INDEX = 12 ICON = '/pig/static/art/icon_pig_24.png' REQUIRES_HADOOP = False IS_URL_NAMESPACED = True
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DJANGO_APPS = ['pig'] NICE_NAME = 'Pig' MENU_INDEX = 12 ICON = '/pig/static/art/icon_pig_24.png' REQUIRES_HADOOP = False IS_URL_NAMESPACED = True
Fix version in web pages
# Copyright (c) 2015, Daniele Venzano # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import Blueprint web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static') import zoe_web.web.start import zoe_web.web.status import zoe_web.web.applications from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION @web_bp.context_processor def inject_version(): return { 'zoe_version': ZOE_VERSION, 'zoe_api_version': ZOE_API_VERSION, }
# Copyright (c) 2015, Daniele Venzano # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import Blueprint web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static') import zoe_web.web.start import zoe_web.web.status import zoe_web.web.applications from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION @web_bp.context_processor def inject_version(): return { 'zoe_lib_version': ZOE_VERSION, 'zoe_api_version': ZOE_API_VERSION, }
Fix register() method visibility in service provider
<?php namespace LaravelTrailingSlash; use Illuminate\Routing\RoutingServiceProvider as BaseRoutingServiceProvider; use LaravelTrailingSlash\UrlGenerator; class RoutingServiceProvider extends BaseRoutingServiceProvider { /** * Register the URL generator service. * * @return void */ public function register() { $this->app['url'] = $this->app->share(function($app) { $routes = $app['router']->getRoutes(); // The URL generator needs the route collection that exists on the router. // Keep in mind this is an object, so we're passing by references here // and all the registered routes will be available to the generator. $app->instance('routes', $routes); $url = new UrlGenerator( $routes, $app->rebinding('request', $this->requestRebinder()) ); $url->setSessionResolver(function ($app) { return $app['session']; }); // If the route collection is "rebound", for example, when the routes stay // cached for the application, we will need to rebind the routes on the // URL generator instance so it has the latest version of the routes. $app->rebinding('routes', function ($app, $routes) { $app['url']->setRoutes($routes); }); return $url; }); } }
<?php namespace LaravelTrailingSlash; use Illuminate\Routing\RoutingServiceProvider as BaseRoutingServiceProvider; use LaravelTrailingSlash\UrlGenerator; class RoutingServiceProvider extends BaseRoutingServiceProvider { /** * Register the URL generator service. * * @return void */ protected function register() { $this->app['url'] = $this->app->share(function($app) { $routes = $app['router']->getRoutes(); // The URL generator needs the route collection that exists on the router. // Keep in mind this is an object, so we're passing by references here // and all the registered routes will be available to the generator. $app->instance('routes', $routes); $url = new UrlGenerator( $routes, $app->rebinding('request', $this->requestRebinder()) ); $url->setSessionResolver(function ($app) { return $app['session']; }); // If the route collection is "rebound", for example, when the routes stay // cached for the application, we will need to rebind the routes on the // URL generator instance so it has the latest version of the routes. $app->rebinding('routes', function ($app, $routes) { $app['url']->setRoutes($routes); }); return $url; }); } }
Add new commit/tag when bumping version
package main import ( "flag" "fmt" "log" "os" "os/exec" "github.com/Shyp/bump_version" ) const VERSION = "0.1" func usage() { fmt.Fprintf(os.Stderr, "Usage: bump_version <major|minor|patch> <filename>\n") } func runCommand(binary string, args ...string) { out, err := exec.Command(binary, args...).CombinedOutput() if err != nil { log.Fatalf("Error when running command: %s.\nOutput was:\n%s", err.Error(), string(out)) } } func main() { flag.Usage = usage flag.Parse() args := flag.Args() if len(args) != 2 { usage() os.Exit(2) } versionTypeStr := args[0] filename := args[1] version, err := bump_version.BumpInFile(bump_version.VersionType(versionTypeStr), filename) if err != nil { log.Fatal(err) } else { fmt.Fprintf(os.Stderr, "Bumped version to %s\n", version) } runCommand("git", "add", filename) runCommand("git", "commit", "-m", version.String()) runCommand("git", "tag", version.String()) fmt.Fprintf(os.Stderr, "Added new commit and tagged version %s.\n", version) }
package main import ( "flag" "fmt" "log" "os" "os/exec" "github.com/Shyp/bump_version" ) const VERSION = "4.1.1" func usage() { fmt.Fprintf(os.Stderr, "Usage: bump_version <major|minor|patch> <filename>\n") } func main() { flag.Usage = usage flag.Parse() args := flag.Args() if len(args) != 2 { usage() os.Exit(2) } versionTypeStr := args[0] filename := args[1] version, err := bump_version.BumpInFile(bump_version.VersionType(versionTypeStr), filename) if err != nil { log.Fatal(err) } else { fmt.Fprintf(os.Stderr, "Bumped version to %s\n", version) } out, err := exec.Command("git", "tag", version.String()).CombinedOutput() if err != nil { log.Fatalf("Error when attempting to git tag: %s.\nOutput was:\n%s", err.Error(), string(out)) } fmt.Fprintf(os.Stderr, "Tagged git version: %s. Commit your changes\n", version) }
Fix incorrect redirect in clear_all
""" Debug Blueprints. """ from flask import Blueprint, current_app, redirect, jsonify, url_for, request debug_pages = Blueprint('debug', __name__) @debug_pages.route("/clear_all", methods=['GET', 'POST']) def clear_all(): if request.method == 'GET': return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>' else: mongo = current_app.mongo mongo.db.userSessions.remove() mongo.db.interactionSessions.remove() return redirect(url_for('end_session')) @debug_pages.route("/dump") def dump_session(): mongo = current_app.mongo return jsonify({ 'userSessions': list(mongo.db.userSessions.find()), 'interactionSessions': list(mongo.db.interactionSessions.find()), })
""" Debug Blueprints. """ from flask import Blueprint, current_app, redirect, jsonify, url_for, request debug_pages = Blueprint('debug', __name__) @debug_pages.route("/clear_all", methods=['GET', 'POST']) def clear_all(): if request.method == 'GET': return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>' else: mongo = current_app.mongo mongo.db.userSessions.remove() mongo.db.interactionSessions.remove() return redirect(url_for('destroy_session')) @debug_pages.route("/dump") def dump_session(): mongo = current_app.mongo return jsonify({ 'userSessions': list(mongo.db.userSessions.find()), 'interactionSessions': list(mongo.db.interactionSessions.find()), })
Update example for new message syntax.
var net = require('net'); // Assuming the existence of some `build` method that returns a promise. var sequence = build(); // gathers rapid changes as one build var timeout = null; var scheduleBuild = function() { if (timeout) { return; } // we want the timeout to start now before we wait for the current build var timeoutPromise = new Promise(function(resolve) { timeout = setTimeout(resolve, 100); }); var timeoutThenBuild = function() { timeoutPromise.then(function() { timeout = null return build(); }); }; // we want the current promise to be waiting for the current build // regardless if it fails or not. sequence = sequence.then(timeoutThenBuild, timeoutThenBuild); }; var port = 4000; var host = '172.16.172.1'; var client = new net.Socket(); client.connect(port, host, function() { console.log('Connected to listen server: ', host, port); }); client.on('data', function(data) { // message is [modified, added, removed] console.log('Data received', data) var message = JSON.parse(data.toString().trim()) scheduleBuild(); }); client.on('close', function() { console.log('Connection closed'); });
var net = require('net'); // Assuming the existence of some `build` method that returns a promise. var sequence = build(); // gathers rapid changes as one build var timeout = null; var scheduleBuild = function() { if (timeout) { return; } // we want the timeout to start now before we wait for the current build var timeoutPromise = new Promise(function(resolve) { timeout = setTimeout(resolve, 100); }); var timeoutThenBuild = function() { timeoutPromise.then(function() { timeout = null return build(); }); }; // we want the current promise to be waiting for the current build // regardless if it fails or not. sequence = sequence.then(timeoutThenBuild, timeoutThenBuild); }; var port = 4000; var host = '172.16.172.1'; var client = new net.Socket(); client.connect(port, host, function() { console.log('Connected to listen server: ', host, port); }); client.on('data', function(data) { // Can't find any doc on the message format, but it looks like the first // 4 bytes are always the header, which includes the message length, and // the result is always a json array. // * https://github.com/guard/listen/blob/master/lib/listen/tcp/message.rb var header = data.slice(0, 4); var message = JSON.parse(data.slice(4).toString()); // message is [type, operation, dir, file, unknown] console.log('Change detected in:', message[3]) scheduleBuild(); }); client.on('close', function() { console.log('Connection closed'); });
Remove unused field in the calculator struct.
package discountcalculator type discountCalculator struct { strategy func() (rate float64, strategyCode int) } func New() *discountCalculator { return &discountCalculator{} } func (calculator *discountCalculator) DiscountFor(customer *customer) *discount { switch c := customer.category; c { case STANDARD: return NewDiscount(STANDARD_DISCOUNT) case SILVER: return NewDiscount(SILVER_DISCOUNT) case GOLD: return NewDiscount(GOLD_DISCOUNT) case PREMIUM: return NewDiscount(PREMIUM_DISCOUNT) } return nil } func (calculator *discountCalculator) SpecialDiscountFor(customer *customer, couponType int) *discount { customerDiscount := calculator.DiscountFor(customer) var d *discount switch couponType { case BIRTHDAY_ANNIVERSARY: d = NewDiscount(BIRTHDAY_DISCOUNT) } decimal := 2 d.addRates(customerDiscount, decimal) return d }
package discountcalculator type discountCalculator struct { strategy func() (rate float64, strategyCode int) strategyCode int } func New() *discountCalculator { return &discountCalculator{} } func (calculator *discountCalculator) DiscountFor(customer *customer) *discount { switch c := customer.category; c { case STANDARD: return NewDiscount(STANDARD_DISCOUNT) case SILVER: return NewDiscount(SILVER_DISCOUNT) case GOLD: return NewDiscount(GOLD_DISCOUNT) case PREMIUM: return NewDiscount(PREMIUM_DISCOUNT) } return nil } func (calculator *discountCalculator) SpecialDiscountFor(customer *customer, couponType int) *discount { customerDiscount := calculator.DiscountFor(customer) var d *discount switch couponType { case BIRTHDAY_ANNIVERSARY: d = NewDiscount(BIRTHDAY_DISCOUNT) } decimal := 2 d.addRates(customerDiscount, decimal) return d }
Work with custom user models in django >= 1.5 settings only provide module strs, not real implementations
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') User = get_model(app_label, model_name) except: from django.contrib.auth.models import User try: app_label, model_name = settings.AUTH_USER_ADMIN_MODEL.split('.') UserAdmin = get_model(app_label, model_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
from django.contrib import admin from django.conf import settings from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: User = settings.AUTH_USER_MODEL except: from django.contrib.auth.models import User try: UserAdmin = settings.AUTH_USER_ADMIN_MODEL except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
Put cache in node_modules for Netlify’s build cache
const Cache = require("async-disk-cache"); module.exports = class BigCachedFunction { constructor(name) { this.inProgress = new Map(); this.cache = new Cache(name, { supportBuffer: true, location: "node_modules/.cache" }); } async get(ikey, fn) { if (this.inProgress.has(ikey)) { return this.inProgress.get(ikey); } const p = new Promise(async resolve => { let { isCached, key, value } = await this.cache.get(ikey); if (!isCached) { value = await fn(); this.cache.set(ikey, value); key = await this.cache.get(ikey).key; } resolve({ key, value }); }); this.inProgress.set(ikey, p); p.then(() => this.inProgress.delete(ikey)); return p; } };
const Cache = require("async-disk-cache"); module.exports = class BigCachedFunction { constructor(name) { this.inProgress = new Map(); this.cache = new Cache(name, { supportBuffer: true, location: ".cache" }); } async get(ikey, fn) { if (this.inProgress.has(ikey)) { return this.inProgress.get(ikey); } const p = new Promise(async resolve => { let { isCached, key, value } = await this.cache.get(ikey); if (!isCached) { value = await fn(); this.cache.set(ikey, value); key = await this.cache.get(ikey).key; } resolve({ key, value }); }); this.inProgress.set(ikey, p); p.then(() => this.inProgress.delete(ikey)); return p; } };
Define an error object if it is undefined to prevent errors on failed requests.
/* * Internal module that is used by the default client, http client, and * the session fetching apparatus. Made as a separate module to avoid * circular dependencies and repeated code. */ import axios from 'axios'; import qs from 'qs'; export default function clientFactory(options) { const client = axios.create({ xsrfCookieName: 'kolibri_csrftoken', xsrfHeaderName: 'X-CSRFToken', paramsSerializer: function(params) { // Do custom querystring stingifying to comma separate array params return qs.stringify(params, { arrayFormat: 'comma' }); }, ...options, }); client.interceptors.response.use( response => response, function(error) { if (!error) { error = {}; } if (!error.response) { error.response = { status: 0, }; } return Promise.reject(error); } ); return client; }
/* * Internal module that is used by the default client, http client, and * the session fetching apparatus. Made as a separate module to avoid * circular dependencies and repeated code. */ import axios from 'axios'; import qs from 'qs'; export default function clientFactory(options) { const client = axios.create({ xsrfCookieName: 'kolibri_csrftoken', xsrfHeaderName: 'X-CSRFToken', paramsSerializer: function(params) { // Do custom querystring stingifying to comma separate array params return qs.stringify(params, { arrayFormat: 'comma' }); }, ...options, }); client.interceptors.response.use( response => response, function(error) { if (!error.response) { error.response = { status: 0, }; } return Promise.reject(error); } ); return client; }
Set Schemas changed to String Schemas
package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private String schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public String getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } }
package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private Set<String> schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public Set<String> getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } }
Add res.end() to end the POST request @chinedufn Line 24 is where I get the contents of `req.body` in order to get the text from the textbox the problem is I believe it should be `req.body.text` like the example on the 'body-parser' page shows.
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body res.end('done') console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries VALUES(%L, %L)', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) }) */ return }) app.listen(3000, function () { console.log('listening on 3000') })
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body.text // var thought = 'cool stuff' console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries (date, thought) VALUES(%L, %L);', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) */ }) app.listen(3000, function () { console.log('listening on 3000') })
Replace Activity by Application as it what it needs
package com.novoda.downloadmanager; import android.content.ContentResolver; import android.content.Context; import com.novoda.downloadmanager.lib.DownloadManager; /** * A client can specify whether the downloads are allowed to proceed by implementing * {@link com.novoda.downloadmanager.lib.DownloadClientReadyChecker} on your Application class * */ public class DownloadManagerBuilder { private final Context context; private boolean verboseLogging; DownloadManagerBuilder(Context context) { this.context = context; } public static DownloadManagerBuilder from(Context context) { return new DownloadManagerBuilder(context.getApplicationContext()); } public DownloadManagerBuilder withVerboseLogging() { this.verboseLogging = true; return this; } public DownloadManager build(ContentResolver contentResolver) { if (contentResolver == null) { throw new IllegalStateException("You must use a ContentResolver with the DownloadManager."); } return new DownloadManager(context, contentResolver, verboseLogging); } }
package com.novoda.downloadmanager; import android.content.ContentResolver; import android.content.Context; import com.novoda.downloadmanager.lib.DownloadManager; /** * A client can specify whether the downloads are allowed to proceed by implementing * {@link com.novoda.downloadmanager.lib.DownloadClientReadyChecker} on your Activity class * */ public class DownloadManagerBuilder { private final Context context; private boolean verboseLogging; DownloadManagerBuilder(Context context) { this.context = context; } public static DownloadManagerBuilder from(Context context) { return new DownloadManagerBuilder(context.getApplicationContext()); } public DownloadManagerBuilder withVerboseLogging() { this.verboseLogging = true; return this; } public DownloadManager build(ContentResolver contentResolver) { if (contentResolver == null) { throw new IllegalStateException("You must use a ContentResolver with the DownloadManager."); } return new DownloadManager(context, contentResolver, verboseLogging); } }
Add a .exe to the compile bootstrap for testing
package integration import ( "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" "testing" ) var agentBinary string // This init compiles a bootstrap to be invoked by the bootstrap tester // We could possibly use the compiled test stub, but ran into some issues with mock compilation func compileBootstrap(dir string) string { _, filename, _, _ := runtime.Caller(0) projectRoot := filepath.Join(filepath.Dir(filename), "..", "..") binPath := filepath.Join(dir, "buildkite-agent") if runtime.GOOS == "windows" { binPath += ".exe" } cmd := exec.Command("go", "build", "-o", binPath, "main.go") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = projectRoot err := cmd.Run() if err != nil { panic(err) } return binPath } func TestMain(m *testing.M) { dir, err := ioutil.TempDir("", "agent-binary") if err != nil { log.Fatal(err) } agentBinary = compileBootstrap(dir) code := m.Run() os.RemoveAll(dir) os.Exit(code) }
package integration import ( "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" "testing" ) var agentBinary string // This init compiles a bootstrap to be invoked by the bootstrap tester // We could possibly use the compiled test stub, but ran into some issues with mock compilation func compileBootstrap(dir string) string { _, filename, _, _ := runtime.Caller(0) projectRoot := filepath.Join(filepath.Dir(filename), "..", "..") binPath := filepath.Join(dir, "buildkite-agent") cmd := exec.Command("go", "build", "-o", binPath, "main.go") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = projectRoot err := cmd.Run() if err != nil { panic(err) } return binPath } func TestMain(m *testing.M) { dir, err := ioutil.TempDir("", "agent-binary") if err != nil { log.Fatal(err) } agentBinary = compileBootstrap(dir) code := m.Run() os.RemoveAll(dir) os.Exit(code) }
Fix missing data for markdown
'use strict' const { css } = require('glamor') const propTypes = require('prop-types') const h = require('../utils/h') const shadowBox = require('../styles/shadowBox') const Tabs = require('./Tabs') const Code = require('./Code') const Markdown = require('./Markdown') const Empty = require('./Empty') const style = { self: css({ flexGrow: '1', display: 'flex', minHeight: '0' }), shadowBox: css(shadowBox, { display: 'flex', flexDirection: 'column' }) } module.exports = ({ components, currentComponent, currentTab }) => { const { data, languages } = currentTab const isMarkdown = languages[0] === 'markdown' const isCode = isMarkdown === false return ( h('div', { className: style.self.toString() }, h('div', { className: style.shadowBox.toString() }, h(Tabs, { currentComponent, currentTab }), data != null && isMarkdown === true && h(Markdown, { data }), data != null && isCode === true && h(Code, { components, currentTab }), data == null && h(Empty, { color: '#bbb', text: 'No data found' }) ) ) ) } module.exports.propTypes = { components: propTypes.array.isRequired, currentComponent: propTypes.object.isRequired, currentTab: propTypes.object.isRequired }
'use strict' const { css } = require('glamor') const propTypes = require('prop-types') const h = require('../utils/h') const shadowBox = require('../styles/shadowBox') const Tabs = require('./Tabs') const Code = require('./Code') const Markdown = require('./Markdown') const Empty = require('./Empty') const style = { self: css({ flexGrow: '1', display: 'flex', minHeight: '0' }), shadowBox: css(shadowBox, { display: 'flex', flexDirection: 'column' }) } module.exports = ({ components, currentComponent, currentTab }) => { const { data, languages } = currentTab const Viewer = languages[0] === 'markdown' ? Markdown : Code return ( h('div', { className: style.self.toString() }, h('div', { className: style.shadowBox.toString() }, h(Tabs, { currentComponent, currentTab }), data != null && h(Viewer, { components, currentTab }), data == null && h(Empty, { color: '#bbb', text: 'No data found' }) ) ) ) } module.exports.propTypes = { components: propTypes.array.isRequired, currentComponent: propTypes.object.isRequired, currentTab: propTypes.object.isRequired }
Use more predictable demo IP address
#!/usr/bin/env python # Designed for use with boofuzz v0.0.1-dev3 from boofuzz import * def main(): session = sessions.Session( target=sessions.Target( connection=SocketConnection("127.0.0.1", 8021, proto='tcp'))) s_initialize("user") s_string("USER") s_delim(" ") s_string("anonymous") s_static("\r\n") s_initialize("pass") s_string("PASS") s_delim(" ") s_string("james") s_static("\r\n") s_initialize("stor") s_string("STOR") s_delim(" ") s_string("AAAA") s_static("\r\n") s_initialize("retr") s_string("RETR") s_delim(" ") s_string("AAAA") s_static("\r\n") session.connect(s_get("user")) session.connect(s_get("user"), s_get("pass")) session.connect(s_get("pass"), s_get("stor")) session.connect(s_get("pass"), s_get("retr")) session.fuzz() if __name__ == "__main__": main()
#!/usr/bin/env python # Designed for use with boofuzz v0.0.1-dev3 from boofuzz import * def main(): session = sessions.Session( target=sessions.Target( connection=SocketConnection("192.168.56.101", 8021, proto='tcp'))) s_initialize("user") s_string("USER") s_delim(" ") s_string("anonymous") s_static("\r\n") s_initialize("pass") s_string("PASS") s_delim(" ") s_string("james") s_static("\r\n") s_initialize("stor") s_string("STOR") s_delim(" ") s_string("AAAA") s_static("\r\n") s_initialize("retr") s_string("RETR") s_delim(" ") s_string("AAAA") s_static("\r\n") session.connect(s_get("user")) session.connect(s_get("user"), s_get("pass")) session.connect(s_get("pass"), s_get("stor")) session.connect(s_get("pass"), s_get("retr")) session.fuzz() if __name__ == "__main__": main()
Remove loaded module which was removed
'use strict'; var app = angular.module('settingsWindow', []); app.run(function($rootScope) { $rootScope.GUI = require('nw.gui'); $rootScope.AppName = $rootScope.GUI.App.manifest.name; $rootScope.Version = $rootScope.GUI.App.manifest.version; $rootScope.Window = $rootScope.GUI.Window.get(); $rootScope.Pussh = global.Pussh; $rootScope.Window.focus(); }); app.controller('settings', function($scope, $rootScope) { var Pussh = $rootScope.Pussh; $scope.services = Pussh.services.list(); $scope.settings = Pussh.settings.get(); $scope.selectedService = Pussh.services.get($scope.settings.selectedService); $scope.serviceSettings = $scope.selectedService.getSettings(); $scope.$watch('selectedService', function(service) { $scope.settings.selectedService = service._name; $scope.serviceSettings = $scope.selectedService.settings; Pussh.settings.save(); }); $scope.$watch('settings', function() { Pussh.settings.save(); }, true); $scope.$watch('serviceSettings', function() { $scope.selectedService.saveSettings(); }, true); });
'use strict'; var app = angular.module('settingsWindow', ['schemaForm']); app.run(function($rootScope) { $rootScope.GUI = require('nw.gui'); $rootScope.AppName = $rootScope.GUI.App.manifest.name; $rootScope.Version = $rootScope.GUI.App.manifest.version; $rootScope.Window = $rootScope.GUI.Window.get(); $rootScope.Pussh = global.Pussh; $rootScope.Window.focus(); }); app.controller('settings', function($scope, $rootScope) { var Pussh = $rootScope.Pussh; $scope.services = Pussh.services.list(); $scope.settings = Pussh.settings.get(); $scope.selectedService = Pussh.services.get($scope.settings.selectedService); $scope.serviceSettings = $scope.selectedService.getSettings(); $scope.$watch('selectedService', function(service) { $scope.settings.selectedService = service._name; $scope.serviceSettings = $scope.selectedService.settings; Pussh.settings.save(); }); $scope.$watch('settings', function() { Pussh.settings.save(); }, true); $scope.$watch('serviceSettings', function() { $scope.selectedService.saveSettings(); }, true); });
Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true, "/socket.io/socket.io.js": true, "/socket.io/": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
Set upgrade to version 0.2.0
# -*- coding: utf8 -*- import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' setup( name="django-basis", version='0.2.0', url='http://github.com/frecar/django-basis', author='Fredrik Nygård Carlsen', author_email='me@frecar.no', description='Simple reusable django app for basic model functionality', packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
# -*- coding: utf8 -*- import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' setup( name="django-basis", version='0.1.9', url='http://github.com/frecar/django-basis', author='Fredrik Nygård Carlsen', author_email='me@frecar.no', description='Simple reusable django app for basic model functionality', packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
Use github.com/martini-contrib/cors instead of github.com/zachlatta/cors.
package v1 import ( "net/http" "time" "github.com/codegangsta/martini" "github.com/coopernurse/gorp" "github.com/hackedu/backend/v1/model" "github.com/hackedu/backend/v1/route" "github.com/martini-contrib/binding" "github.com/martini-contrib/cors" ) func Setup(m *martini.ClassicMartini) { // TODO: Only apply middleware on /v1/** routes m.Use(cors.Allow(&cors.Options{ AllowAllOrigins: true, AllowMethods: []string{"GET", "POST"}, MaxAge: 5 * time.Minute, })) m.MapTo(Dbm, (*gorp.SqlExecutor)(nil)) m.Get("/v1/schools", route.GetSchools) m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser) // OPTIONS catchall for CORS. m.Options("/**", func() int { return http.StatusOK }) }
package v1 import ( "net/http" "time" "github.com/codegangsta/martini" "github.com/coopernurse/gorp" "github.com/hackedu/backend/v1/model" "github.com/hackedu/backend/v1/route" "github.com/martini-contrib/binding" "github.com/zachlatta/cors" ) func Setup(m *martini.ClassicMartini) { // TODO: Only apply middleware on /v1/** routes m.Use(cors.Allow(&cors.Options{ AllowAllOrigins: true, AllowMethods: []string{"GET", "POST"}, MaxAge: 5 * time.Minute, })) m.MapTo(Dbm, (*gorp.SqlExecutor)(nil)) m.Get("/v1/schools", route.GetSchools) m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser) // OPTIONS catchall for CORS. m.Options("/**", func() int { return http.StatusOK }) }
Remove call to setTimeout and use callLater instead.
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
Fix the travis issues 2
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Tomas Krehlik # Copyright (c) 2014 Tomas Krehlik # # License: MIT # """This module exports the Julialint plugin class.""" from SublimeLinter.lint import Linter, util class Julialint(Linter): """Provides an interface to julialint.""" syntax = 'julia' cmd = ['julia', '-e', 'using Lint; lintfile(ARGS[1])'] regex = r'(?P<file>^.*\.jl):(?P<line>\d{1,4}) \[(?P<func>.*)\] ((?P<error>ERROR)|(?P<warning>WARN)) (?P<message>.*)' multiline = False line_col_base = (1, 1) tempfile_suffix = "jl" error_stream = util.STREAM_BOTH selectors = {} word_re = None comment_re = r'#' defaults = {} inline_settings = None inline_overrides = None comment_re = None
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Tomas Krehlik # Copyright (c) 2014 Tomas Krehlik # # License: MIT # """This module exports the Julialint plugin class.""" from SublimeLinter.lint import Linter, util class Julialint(Linter): """Provides an interface to julialint.""" syntax = 'julia' cmd = ['julia', '-e', 'using Lint; lintfile(ARGS[1])'] regex = r'(?P<file>^.*\.jl):(?P<line>\d{1,4}) \[(?P<func>.*)\] ((?P<error>ERROR)|(?P<warning>WARN)) (?P<message>.*)' multiline = False line_col_base = (1, 1) tempfile_suffix = "jl" error_stream = util.STREAM_BOTH selectors = {} word_re = None comment_re = r'#' defaults = {} inline_settings = None inline_overrides = None comment_re = None
Refactor (Dashboard): Define security acces level
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; /** * Class DashboardController * @package AppBundle\Controller * @Route("/dashboard") * @Security("is_granted('ROLE_OBSERVER')") */ class DashboardController extends Controller { /** * @Route("/compte", name="dashboard.account") * @Method({"GET","POST"}) */ public function accountAction(Request $request) { return $this->render('dashboard/account.html.twig'); } /** * @Route("/profil", name="dashboard.profil") * @Method({"GET"}) */ public function profilAction() { return $this->render('dashboard/profil.html.twig'); } /** * @Route("/notification", name="dashboard.notification") * @Method({"GET"}) */ public function notificationAction() { return $this->render('dashboard/notification.html.twig'); } }
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; /** * Class DashboardController * @package AppBundle\Controller * @Route("/dashboard") */ class DashboardController extends Controller { /** * @Route("/compte", name="dashboard.account") * @Method({"GET","POST"}) */ public function accountAction(Request $request) { return $this->render('dashboard/account.html.twig'); } /** * @Route("/profil", name="dashboard.profil") * @Method({"GET"}) */ public function profilAction() { return $this->render('dashboard/profil.html.twig'); } /** * @Route("/notification", name="dashboard.notification") * @Method({"GET"}) */ public function notificationAction() { return $this->render('dashboard/notification.html.twig'); } }
Clean up test a little --HG-- branch : delegation
package net.lshift.spki.suiteb; import static net.lshift.spki.suiteb.AlwaysCondition.ALWAYS; import static net.lshift.spki.suiteb.ConditionJoiner.and; import static net.lshift.spki.suiteb.ConditionJoiner.or; import static net.lshift.spki.suiteb.NeverCondition.NEVER; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ConditionJoinerTest { private static final Condition[] BOOLEANS = new Condition[] {NEVER, ALWAYS}; @Test public void test() { for (Condition a: BOOLEANS) { for (Condition b: BOOLEANS) { assertEquals( a.allows(null, null) || b.allows(null, null), or(a, b).allows(null, null)); assertEquals( a.allows(null, null) && b.allows(null, null), and(a, b).allows(null, null)); } } } }
package net.lshift.spki.suiteb; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ConditionJoinerTest { private static final Condition[] BOOLEANS = new Condition[] { NeverCondition.NEVER, AlwaysCondition.ALWAYS}; @Test public void test() { for (Condition a: BOOLEANS) { for (Condition b: BOOLEANS) { assertEquals( a.allows(null, null) || b.allows(null, null), ConditionJoiner.or(a, b).allows(null, null)); assertEquals( a.allows(null, null) && b.allows(null, null), ConditionJoiner.and(a, b).allows(null, null)); } } } }
Make Flappy Wumpus Great Again Ad Campaign!
$(document).ready(function(){ // Displaying random banner ads below the game var bannerArray = [ //{"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/trailerad.png"}, //{"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/malloryad.png"}, {"url":"https://clubwump.us/","banner":"img/electionad.png"}, //{"url":"https://soundcloud.com/cheesecast/its-time-to-softsoap","banner":"img/songad.png"}, //{"url":"https://www.youtube.com/watch?v=xUVz4nRmxn4","banner":"img/milliondollarsad.png"} {"url":"https://clubwump.us/","banner":"img/mfwgaad.png"}] var selectBanner = bannerArray[Math.floor(Math.random()*bannerArray.length)]; $('#bottom-banner__inner').html('<a target="_blank" href="' + selectBanner.url + '"><img src="' + selectBanner.banner + '" alt="Random Banner" /></a>'); // Adding background audio + reducing volume var backgroundAudio=new Audio('sounds/FlappilyWumped.mp3'); backgroundAudio.autoplay = true; backgroundAudio.loop = true; backgroundAudio.volume=0.5; });
$(document).ready(function(){ // Displaying random banner ads below the game var bannerArray = [ {"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/trailerad.png"}, {"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/malloryad.png"}, {"url":"https://clubwump.us/","banner":"img/electionad.png"}, {"url":"https://soundcloud.com/cheesecast/its-time-to-softsoap","banner":"img/songad.png"}, {"url":"https://www.youtube.com/watch?v=xUVz4nRmxn4","banner":"img/milliondollarsad.png"}] var selectBanner = bannerArray[Math.floor(Math.random()*bannerArray.length)]; $('#bottom-banner__inner').html('<a target="_blank" href="' + selectBanner.url + '"><img src="' + selectBanner.banner + '" alt="Random Banner" /></a>'); // Adding background audio + reducing volume var backgroundAudio=new Audio('sounds/FlappilyWumped.mp3'); backgroundAudio.autoplay = true; backgroundAudio.loop = true; backgroundAudio.volume=0.5; });
Add gulp watcher Rejigged gulp tasks to remove repeated code to run browserify
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); }); gulp.task('build', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['build'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['javascript']); gulp.task('javascript', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./spec/**/*.js') .pipe(browserified) .pipe(jasmine()); });
normalize_namreply_params: Fix typo in function call
""" Handles ambiguities of RFCs. """ def normalize_namreply_params(params): # So… RFC 2812 says: # "( "=" / "*" / "@" ) <channel> # :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> ) # but spaces seem to be missing (eg. before the colon), so we # don't know if there should be one before the <channel> and its # prefix. # So let's normalize this to “with space”, and strip spaces at the # end of the nick list. if len(params) == 3: assert params[1][0] in "=*@", params params.insert(1, params[1][0]) params[2] = params[2][1:] params[3] = params[3].rstrip() return params
""" Handles ambiguities of RFCs. """ def normalize_namreply_params(params): # So… RFC 2812 says: # "( "=" / "*" / "@" ) <channel> # :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> ) # but spaces seem to be missing (eg. before the colon), so we # don't know if there should be one before the <channel> and its # prefix. # So let's normalize this to “with space”, and strip spaces at the # end of the nick list. if len(params) == 3: assert params[1][0] in "=*@", params params.insert(1), params[1][0] params[2] = params[2][1:] params[3] = params[3].rstrip() return params
Fix wrong table preferrence for role_user
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->unsigned()->index(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->unsigned()->index(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); } }
Fix build exitting from make coverage
from __future__ import absolute_import, division, print_function import os, sys, tempfile from data import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'Some data') temp.flush() fname = temp.name d = {fname: "5b82f8bf4df2bfb0e66ccaa7306fd024"} assert data.check_hashes(d) d = {fname: "4b82f8bf4df2bfb0e66ccaa7306fd024"} assert not data.check_hashes(d) def test_make_hash_dict(): l = "http://www.jarrodmillman.com/rcsds/_downloads/ds107_sub001_highres.nii" with open("ds107_sub001_highres.nii", 'wb') as outfile: outfile.write(urlopen(l).read()) hash_O = data.make_hash_dict(".")["./ds107_sub001_highres.nii"] hash_E = "fd733636ae8abe8f0ffbfadedd23896c" assert hash_O == hash_E os.remove("ds107_sub001_highres.nii")
from __future__ import absolute_import, division, print_function import os, sys, tempfile sys.path.append("data/") import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'Some data') temp.flush() fname = temp.name d = {fname: "5b82f8bf4df2bfb0e66ccaa7306fd024"} assert data.check_hashes(d) d = {fname: "4b82f8bf4df2bfb0e66ccaa7306fd024"} assert not data.check_hashes(d) def test_make_hash_dict(): l = "http://www.jarrodmillman.com/rcsds/_downloads/ds107_sub001_highres.nii" with open("ds107_sub001_highres.nii", 'wb') as outfile: outfile.write(urlopen(l).read()) hash_O = data.make_hash_dict(".")["./ds107_sub001_highres.nii"] hash_E = "fd733636ae8abe8f0ffbfadedd23896c" assert hash_O == hash_E os.remove("ds107_sub001_highres.nii")
Use simpler endpoint for barelyBot
"use strict"; const express = require("express"); const bodyParser = require("body-parser"); const gutiBot = require("./gutiBot"); const barelyBot = require("./barelyBot").bot; const defineBot = require("./defineBot"); const windBot = require("./windBot"); const app = express(); const port = process.env.PORT || 3000; app.use(bodyParser.urlencoded({ extended: true })); app.get('/', (req, res) => { res.send('Hello! This is gutibot. Are you lost?'); }); app.post("/barely", gutiBot.doSync(barelyBot)); app.post("/define", defineBot); app.post("/wind", gutiBot.doSync(windBot)); app.use((err, req, res, next) => { console.error(err.stack); res.status(400).send(err.message); }); app.listen(port, () => console.log("Listening on port " + port));
"use strict"; const express = require("express"); const bodyParser = require("body-parser"); const gutibot = require("./gutiBot"); const barelyBot = require("./barelyBot").bot; const defineBot = require("./defineBot"); const windBot = require("./windBot"); const app = express(); const port = process.env.PORT || 3000; app.use(bodyParser.urlencoded({ extended: true })); app.get('/', (req, res) => { res.send('Hello! This is gutibot. Are you lost?'); }); app.post("/define", defineBot); app.post("/doesheknower", gutibot.doSync(barelyBot)); app.post("/wind", gutibot.doSync(windBot)); app.use((err, req, res, next) => { console.error(err.stack); res.status(400).send(err.message); }); app.listen(port, () => console.log("Listening on port " + port));
Add test for invalid series in `episodesByAirDate`
'use strict'; const TVDB = require('..'); const API_KEY = process.env.TVDB_KEY; const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); const expect = chai.expect; chai.use(chaiAsPromised); describe('#episodeByAirDate', () => { it('should return all episodes aired on "2011-10-03" from the show with id "153021"', () => { const tvdb = new TVDB(API_KEY); return tvdb.getEpisodesByAirDate(153021, '2011-10-03').then(response => { expect(response.length).to.equal(6); [4185563, 4185564, 4185565, 4185566, 4185567, 4185568].forEach(episodeId => { return expect(response.find(episode => episode.id === episodeId)).to.exist; }); }); }); it('should return an empty array if no episodes did air on the requested date', () => { const tvdb = new TVDB(API_KEY); return expect(tvdb.getEpisodesByAirDate(153021, '2000-01-01')).to.be.rejected; }); it('should return an error if given an invalid series', () => { const tvdb = new TVDB(API_KEY); return expect(tvdb.getEpisodesByAirDate('', '2016-01-01')).to.be.rejected; }); });
'use strict'; const TVDB = require('..'); const API_KEY = process.env.TVDB_KEY; const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); const expect = chai.expect; chai.use(chaiAsPromised); describe('#episodeByAirDate', () => { it('should return all episodes aired on "2011-10-03" from the show with id "153021"', () => { const tvdb = new TVDB(API_KEY); return tvdb.getEpisodesByAirDate(153021, '2011-10-03').then(response => { expect(response.length).to.equal(6); [4185563, 4185564, 4185565, 4185566, 4185567, 4185568].forEach(episodeId => { return expect(response.find(episode => episode.id === episodeId)).to.exist; }); }); }); it('should return an empty array if no episodes did air on the requested date', () => { const tvdb = new TVDB(API_KEY); return expect(tvdb.getEpisodesByAirDate(153021, '2000-01-01')).to.be.rejected; }); });
Fix plumber not work bug
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var buffer = require("vinyl-buffer"); var reactify = require("reactify"); var watch = require("gulp-watch"); var plumber = require("gulp-plumber"); var uglify = require('gulp-uglify'); gulp.task("browserify", function() { var bs = browserify({ entries: ["./src/main.js"], transform: [reactify] }); bs.bundle() .on("error", function() {}) .pipe(plumber()) .pipe(source("app.js")) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest("./public/js")); }); gulp.task("watch", function() { gulp.watch("src/*.js", ["browserify"]); gulp.watch("src/*.jsx", ["browserify"]); }); gulp.task('compress', function() { gulp.src('lib/*.js') .pipe(uglify()) .pipe(gulp.dest('dist')) }); gulp.task("default", ["browserify"]);
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var buffer = require("vinyl-buffer"); var reactify = require("reactify"); var watch = require("gulp-watch"); var plumber = require("gulp-plumber"); var uglify = require('gulp-uglify'); gulp.task("browserify", function() { var bs = browserify({ entries: ["./src/main.js"], transform: [reactify] }); return gulp .src("./src/main.js", {"read": false}) .pipe(plumber()) .pipe(bs.bundle()) .pipe(source("app.js")) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest("./public/js")); }); gulp.task("watch", function() { gulp.watch("src/*.js", ["browserify"]); gulp.watch("src/*.jsx", ["browserify"]); }); gulp.task('compress', function() { gulp.src('lib/*.js') .pipe(uglify()) .pipe(gulp.dest('dist')) }); gulp.task("default", ["browserify"]);
Move ob_get_level() script initialization check to libphutil from arcanist Summary: See D1950, D1951. We should always normalize any output buffering initialized in the environmen when running scripts. Test Plan: Ran "arc". Reviewers: btrahan, killermonk Reviewed By: btrahan CC: aran, epriestley Differential Revision: https://secure.phabricator.com/D1952
<?php /* * Copyright 2012 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ $root = dirname(dirname(__FILE__)); require_once $root.'/src/__phutil_library_init__.php'; /** * Adjust the runtime language configuration to be reasonable and inline with * expectations. */ function __phutil_adjust_php_ini() { error_reporting(E_ALL | E_STRICT); $config_map = array( 'display_errors' => true, 'error_log' => null, ); foreach ($config_map as $config_key => $config_value) { ini_set($config_key, $config_value); } // There may be some kind of auto-prepend script configured which starts an // output buffer. Discard any such output buffers so messages can be sent to // stdout (if a user wants to capture output from a script, there are a large // number of ways they can accomplish it legitimately; historically, we ran // into this on only one install which had some bizarre configuration, but it // was difficult to diagnose because the symptom is "no messages of any // kind"). while (ob_get_level() > 0) { ob_end_clean(); } } __phutil_adjust_php_ini();
<?php /* * Copyright 2012 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ $root = dirname(dirname(__FILE__)); require_once $root.'/src/__phutil_library_init__.php'; /** * Adjust the runtime language configuration to be reasonable and inline with * expectations. */ function __phutil_adjust_php_ini() { error_reporting(E_ALL | E_STRICT); $config_map = array( 'display_errors' => true, 'error_log' => null, ); foreach ($config_map as $config_key => $config_value) { ini_set($config_key, $config_value); } } __phutil_adjust_php_ini();
Enable mutable config in searchlight New releases of oslo.config support a 'mutable' parameter to Opts. oslo.service provides an option here Icec3e664f3fe72614e373b2938e8dee53cf8bc5e allows services to tell oslo.service they want mutate_config_files to be called by passing a parameter. This commit is to use the same. This allows searchlight to benefit from I1e7a69de169cc85f4c09954b2f46ce2da7106d90, where the 'debug' option (owned by oslo.log) is made mutable. we should be able to turn debug logging on and off by changing the config. tc goal: https://governance.openstack.org/tc/goals/rocky/enable-mutable-configuration.html Change-Id: I1c2833bef93b1382c7ddb71dba8621004dcd4cb1
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg from oslo_service import service as os_service from searchlight import listener from searchlight import service CONF = cfg.CONF CONF.import_group("listener", "searchlight.listener") def main(): service.prepare_service() launcher = os_service.ProcessLauncher(CONF, restart_method='mutate') launcher.launch_service( listener.ListenerService(), workers=CONF.listener.workers) launcher.wait() if __name__ == "__main__": main()
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg from oslo_service import service as os_service from searchlight import listener from searchlight import service CONF = cfg.CONF CONF.import_group("listener", "searchlight.listener") def main(): service.prepare_service() launcher = os_service.ProcessLauncher(CONF) launcher.launch_service( listener.ListenerService(), workers=CONF.listener.workers) launcher.wait() if __name__ == "__main__": main()
Remove cached file from require so that they got actually reloaded
/* Define configuration from local environment */ const SERVER_IP = process.env.OPENSHIFT_NODEJS_IP || 'localhost' const SERVER_PORT = process.env.OPENSHIFT_NODEJS_PORT || 8080 const MAIN = './main.js' var app = require('http').Server(require(MAIN)) function restart() { process.stdout.write('\x1Bc') Object.keys(require.cache) .filter(x => new RegExp(`^${__dirname}`).test(x)) .forEach(x => delete require.cache[x]) app.close(() => { app = require('http').Server(require(MAIN)) app.listen(SERVER_PORT, SERVER_IP, e => { if (e != null) { console.log(e) process.exit(1) } console.log(`[${Date.now()}]Connected on ${SERVER_IP}:${SERVER_PORT}`) }) }) } if (["--development", "-D", "--dev"].indexOf(process.argv[2]) !== -1) { /* Watch for changes */ require('watch').watchTree(__dirname, {'ignoreDotFiles': true}, restart) } else { restart() }
/* Define configuration from local environment */ const SERVER_IP = process.env.OPENSHIFT_NODEJS_IP || 'localhost' const SERVER_PORT = process.env.OPENSHIFT_NODEJS_PORT || 8080 var app = require('http').Server(require('./main.js')) function restart() { process.stdout.write('\x1Bc') app.close(() => { app.listen(SERVER_PORT, SERVER_IP, e => { if (e != null) { console.log(e) process.exit(1) } console.log(`[${Date.now()}]Connected on ${SERVER_IP}:${SERVER_PORT}`) }) }) } if (["--development", "-D", "--dev"].indexOf(process.argv[2]) !== -1) { /* Watch for changes */ require('watch').watchTree('.', {'ignoreDotFiles': true}, restart) } else { restart() }
Include shebang in "comment" definition.
import fs from "fs"; import InputStream from "./InputStream"; export function isGreyspace(string) { if (string === "" || string === " " || string === "\n" || /^\s*$/.test(string)) { return true; } if (string === undefined || string === null) throw new Error("passed undefined or null to isGreyspace"); let stream = new InputStream(string); // Consume shebang stream.consume(/#!.*\n/); while (!stream.atEnd()) { let consumed = stream.consume(/\s+/) || stream.consume(/\/\/[^\n]*/) || stream.consume(/\/\*[\W\S]*?\*\//); if (!consumed) return false; } return stream.atEnd(); } export function log(...messages) { let data = messages.join(" ") + "\n"; try { fs.writeSync(3, data); } catch (error) { if (error.code === "EBADF") { return; } else { throw error; } } }
import fs from "fs"; import InputStream from "./InputStream"; export function isGreyspace(string) { if (string === "" || string === " " || string === "\n" || /^\s*$/.test(string)) { return true; } if (string === undefined || string === null) throw new Error("passed undefined or null to isGreyspace"); let stream = new InputStream(string); while (!stream.atEnd()) { let consumed = stream.consume(/\s+/) || stream.consume(/\/\/[^\n]*/) || stream.consume(/\/\*[\W\S]*?\*\//); if (!consumed) return false; } return stream.atEnd(); } export function log(...messages) { let data = messages.join(" ") + "\n"; try { fs.writeSync(3, data); } catch (error) { if (error.code === "EBADF") { return; } else { throw error; } } }
Fix Google Analytics tracking code
(function (window) { "use strict"; window.GOVUK = window.GOVUK || {}; const trackingId = 'UA-75215134-1'; // Disable analytics by default window[`ga-disable-${trackingId}`] = true; const initAnalytics = function () { // guard against being called more than once if (!('analytics' in window.GOVUK)) { window[`ga-disable-${trackingId}`] = false; // Load Google Analytics libraries window.GOVUK.Analytics.load(); // Configure profiles and make interface public // for custom dimensions, virtual pageviews and events window.GOVUK.analytics = new GOVUK.Analytics({ trackingId: trackingId, cookieDomain: 'auto', anonymizeIp: true, displayFeaturesTask: null, transport: 'beacon', name: 'GOVUK.analytics', expires: 365 }); // Track initial pageview window.GOVUK.analytics.trackPageview(); } }; window.GOVUK.initAnalytics = initAnalytics; })(window);
(function (window) { "use strict"; window.GOVUK = window.GOVUK || {}; const trackingId = 'UA-26179049-1'; // Disable analytics by default window[`ga-disable-${trackingId}`] = true; const initAnalytics = function () { // guard against being called more than once if (!('analytics' in window.GOVUK)) { window[`ga-disable-${trackingId}`] = false; // Load Google Analytics libraries window.GOVUK.Analytics.load(); // Configure profiles and make interface public // for custom dimensions, virtual pageviews and events window.GOVUK.analytics = new GOVUK.Analytics({ trackingId: trackingId, cookieDomain: 'auto', anonymizeIp: true, displayFeaturesTask: null, transport: 'beacon', name: 'GOVUK.analytics', expires: 365 }); // Track initial pageview window.GOVUK.analytics.trackPageview(); } }; window.GOVUK.initAnalytics = initAnalytics; })(window);
Fix table scope var in tb-table
tbTable.$inject = [ 'tableBuilder' ]; function tbTable(tableBuilder) { var directive = { restrict: 'E', scope: { schema: '=', model: '=', onRowClick: '=?', table: '=?' }, link: scope => { scope.$watch('model', newModel => { if (newModel) scope.table = tableBuilder.newTable(scope.schema, newModel); else scope.table = tableBuilder.emptyTable(); }, true); }, templateUrl: 'templates/shared/TB-Table/tb-table.html' }; return directive; } module.exports = { name: 'tbTable', drtv: tbTable };
tbTable.$inject = [ 'tableBuilder' ]; function tbTable(tableBuilder) { var directive = { restrict: 'E', scope: { schema: '=', model: '=', onRowClick: '=?' }, link: scope => { scope.$watch('model', newModel => { if (newModel) scope.table = tableBuilder.newTable(scope.schema, newModel); else scope.table = tableBuilder.emptyTable(); }, true); }, templateUrl: 'templates/shared/TB-Table/tb-table.html' }; return directive; } module.exports = { name: 'tbTable', drtv: tbTable };
Make mail working on my dev machine.
# -*- coding: utf-8 -*- # Settings for 1flow.net (local development) import os from sparks.django.settings import include_snippets include_snippets( os.path.dirname(__file__), ( '00_development', # Activate this to test 404/500… #'00_production', '1flow_io', 'common', 'db_common', 'db_development', 'cache_common', 'cache_development', 'mail_development', 'raven_development', 'common_development', 'rosetta', 'djdt', ), globals() ) # Override `1flow_net` for local development SITE_DOMAIN = 'localhost:8000' EMAIL_HOST = 'gurney' #EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' #EMAIL_FILE_PATH = '/tmp/1flow.mail'
# -*- coding: utf-8 -*- # Settings for 1flow.net (local development) import os from sparks.django.settings import include_snippets include_snippets( os.path.dirname(__file__), ( '00_development', # Activate this to test 404/500… #'00_production', '1flow_io', 'common', 'db_common', 'db_development', 'cache_common', 'cache_development', 'mail_development', 'raven_development', 'common_development', 'rosetta', 'djdt', ), globals() ) # Override `1flow_net` for local development SITE_DOMAIN = 'localhost'
Increase the version number for new feature
from setuptools import setup long_description = open('README.md').read() setup( name="django-mediumeditor", version='0.2.0', packages=["mediumeditor"], include_package_data=True, description="Medium Editor widget for Django", url="https://github.com/g3rd/django-mediumeditor", author="Chad Shryock", author_email="chad@aceportfol.io", license='MIT', long_description=long_description, platforms=["any"], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=[ 'django-appconf >= 1.0.2', ], )
from setuptools import setup long_description = open('README.md').read() setup( name="django-mediumeditor", version='0.1.3', packages=["mediumeditor"], include_package_data=True, description="Medium Editor widget for Django", url="https://github.com/g3rd/django-mediumeditor", author="Chad Shryock", author_email="chad@aceportfol.io", license='MIT', long_description=long_description, platforms=["any"], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=[ 'django-appconf >= 1.0.2', ], )
Fix not chached user bug
'use strict'; import React from 'react'; import ProfileImage from 'components/atoms/profile_image/ProfileImage'; import Username from 'components/atoms/username/Username'; import Badges from 'components/molecules/badges/Badges'; require('./stylesheets/user_info.scss'); class UserInfo extends React.Component { getUserProfile() { return JSON.parse(localStorage.getItem('userProfile')) || {email:"",nickname:""}; } render() { let userProfile = this.getUserProfile(); return ( <div className='user-info-component'> <ProfileImage email={userProfile.email} /> <div className='column'> <Username username={userProfile.nickname} /> <Badges points='500' /> </div> </div> ); } } UserInfo.displayName = 'MoleculeUserInfo'; // Uncomment properties you need // UserInfo.propTypes = {}; // UserInfo.defaultProps = {}; export default UserInfo;
'use strict'; import React from 'react'; import ProfileImage from 'components/atoms/profile_image/ProfileImage'; import Username from 'components/atoms/username/Username'; import Badges from 'components/molecules/badges/Badges'; require('./stylesheets/user_info.scss'); class UserInfo extends React.Component { getUserProfile() { return JSON.parse(localStorage.getItem('userProfile')); } render() { let userProfile = this.getUserProfile(); return ( <div className='user-info-component'> <ProfileImage email={userProfile.email} /> <div className='column'> <Username username={userProfile.nickname} /> <Badges points='500' /> </div> </div> ); } } UserInfo.displayName = 'MoleculeUserInfo'; // Uncomment properties you need // UserInfo.propTypes = {}; // UserInfo.defaultProps = {}; export default UserInfo;
Change loader back to esnextreact until node-build lands node 6
module.exports = [{ name: 'apiClient', webpack: { entry: { apiClient: './index.es6.js', }, output: { library: '[name].js', libraryTarget: 'umd', }, resolve: { generator: 'npm-and-modules', extensions: ['', '.js', '.jsx', '.es6.js', '.json'], }, loaders: [ 'esnextreact', 'json', ], plugins: [ 'production-loaders', 'set-node-env', 'abort-if-errors', 'minify-and-treeshake', ], externals: { lodash: 'commonjs lodash', 'lodash/object': 'commonjs lodash/object', 'lodash/lang': 'commonjs lodash/lang', 'lodash/array': 'commonjs lodash/array', 'lodash/collection': 'commonjs lodash/collection', superagent: 'commonjs superagent', 'superagent-retry': 'commonjs superagent-retry', }, }, }];
module.exports = [{ name: 'apiClient', webpack: { entry: { apiClient: './index.es6.js', }, output: { library: '[name].js', libraryTarget: 'umd', }, resolve: { generator: 'npm-and-modules', extensions: ['', '.js', '.jsx', '.es6.js', '.json'], }, loaders: [ 'es5react', 'json', ], plugins: [ 'production-loaders', 'set-node-env', 'abort-if-errors', 'minify-and-treeshake', ], externals: { lodash: 'commonjs lodash', 'lodash/object': 'commonjs lodash/object', 'lodash/lang': 'commonjs lodash/lang', 'lodash/array': 'commonjs lodash/array', 'lodash/collection': 'commonjs lodash/collection', superagent: 'commonjs superagent', 'superagent-retry': 'commonjs superagent-retry', }, }, }];
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Add an insert method to the custom data point repository.
/* * Copyright 2014 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.dsu.repository; import org.openmhealth.dsu.domain.DataPoint; import org.openmhealth.dsu.domain.DataPointSearchCriteria; import javax.annotation.Nullable; /** * A set of data point repository methods not automatically implemented by Spring Data repositories. * * @author Emerson Farrugia */ public interface CustomDataPointRepository { Iterable<DataPoint> findBySearchCriteria(DataPointSearchCriteria searchCriteria, @Nullable Integer offset, @Nullable Integer limit); /** * Inserts data points, failing if a data point with the same identifier already exists and compensating in case * previous inserts were successful. * * @param dataPoints the data points to insert */ void insert(Iterable<DataPoint> dataPoints); }
/* * Copyright 2014 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.dsu.repository; import org.openmhealth.dsu.domain.DataPoint; import org.openmhealth.dsu.domain.DataPointSearchCriteria; import javax.annotation.Nullable; /** * A set of data point repository methods not automatically implemented by Spring Data. * * @author Emerson Farrugia */ public interface CustomDataPointRepository { Iterable<DataPoint> findBySearchCriteria(DataPointSearchCriteria searchCriteria, @Nullable Integer offset, @Nullable Integer limit); }
Split out subtitle pattern from compilation phase
#!/usr/bin/env python import re import datetime from collections import namedtuple SUBTITLE_PATTERN = '''\ (\d+) (\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+) (.+?) ''' SUBTITLE_REGEX = re.compile(SUBTITLE_PATTERN, re.MULTILINE | re.DOTALL) Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content']) def parse_time(time): hours, minutes, seconds, milliseconds = map(int, re.split('[,:]', time)) return datetime.timedelta( hours=hours, minutes=minutes, seconds=seconds, milliseconds=milliseconds, ) def parse(srt): for match in SUBTITLE_REGEX.finditer(srt): raw_index, raw_start, raw_end, content = match.groups() yield Subtitle( index=int(raw_index), start=parse_time(raw_start), end=parse_time(raw_end), content=content, )
#!/usr/bin/env python import re import datetime from collections import namedtuple SUBTITLE_REGEX = re.compile(r'''\ (\d+) (\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+) (.+) ''') Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content']) def parse_time(time): hours, minutes, seconds, milliseconds = map(int, re.split('[,:]', time)) return datetime.timedelta( hours=hours, minutes=minutes, seconds=seconds, milliseconds=milliseconds, ) def parse(srt): for match in SUBTITLE_REGEX.finditer(srt): raw_index, raw_start, raw_end, content = match.groups() yield Subtitle( index=int(raw_index), start=parse_time(raw_start), end=parse_time(raw_end), content=content, )
Clean up script to make refunds Tested against httpbin.org
#!/usr/bin/env python -u from __future__ import absolute_import, division, print_function, unicode_literals import csv, os, requests url = 'https://api.balancedpayments.com/debits/{}/refunds' username = os.environ['BALANCED_API_USER'] inp = csv.reader(open('refunds.csv')) inp.next() # headers out = csv.writer(open('refunds.completed.csv', 'w+')) out.writerow(('ts', 'id', 'amount', 'code', 'body')) for ts, id, amount in inp: response = requests.post( url.format(id) , data={'amount': amount} , auth=(username, '') ) out.writerow((ts,id,amount,response.status_code,response.content))
#!/usr/bin/env python -u from __future__ import absolute_import, division, print_function, unicode_literals import csv, os, requests url = 'https://api.balancedpayments.com/debits/{}/refunds' username = os.environ['BALANCED_API_USER'] inp = csv.reader(open('refunds.csv')) inp.next() # headers out = csv.reader(open('refunds.completed.csv', 'w+')) out.writerow('ts', 'id', 'amount', 'code', 'body') for ts, id, amount in inp: response = requests.post( url.format(id) , data={'amount': amount} , auth=(username, '') ) out.writerow((ts,id,amount,response.status_code,response.content))
Fix legacy converter with proper regex to match opacity
/* global legacy, legacyConvert */ module.exports = function(grunt) { grunt.registerTask('convertLegacy', function(task) { var dest = legacyConvert[task], css = grunt.file.read(dest); // Convert rem units to px var rootSize = legacy.rootSize, rootValue = 10; // Determine root value for unit conversion if (rootSize.indexOf('%') !== -1) { rootValue = (rootSize.replace('%', '') / 100) * 16; } else if (rootSize.indexOf('px') !== -1) { rootValue = rootSize.replace('px', ''); } else if (rootSize.indexOf('em') !== -1) { rootValue = rootSize.replace('em', ''); } else if (rootSize.indexOf('pt') !== -1) { rootValue = rootSize.replace('pt', ''); } var output = css.replace(/(-?[.\d]+)rem/gi, function(str, match) { return (match * rootValue) + 'px'; }); // Convert opacity to filter output = output.replace(/opacity:([.\d]+)/gi, function(str, match) { return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');'; }); grunt.file.write(dest, output); }); };
/* global legacy, legacyConvert */ module.exports = function(grunt) { grunt.registerTask('convertLegacy', function(task) { var dest = legacyConvert[task], css = grunt.file.read(dest); // Convert rem units to px var rootSize = legacy.rootSize, rootValue = 10; // Determine root value for unit conversion if (rootSize.indexOf('%') !== -1) { rootValue = (rootSize.replace('%', '') / 100) * 16; } else if (rootSize.indexOf('px') !== -1) { rootValue = rootSize.replace('px', ''); } else if (rootSize.indexOf('em') !== -1) { rootValue = rootSize.replace('em', ''); } else if (rootSize.indexOf('pt') !== -1) { rootValue = rootSize.replace('pt', ''); } var output = css.replace(/(-?[.\d]+)rem/gi, function(str, match) { return (match * rootValue) + 'px'; }); // Convert opacity to filter output = output.replace(/(-?[.\d]+)rem/gi, function(str, match) { return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');'; }); grunt.file.write(dest, output); }); };
Use AbstractBaseJavaLocalInspectionTool instead of deprecated BaseJavaLocalInspectionTool
package com.github.stokito.IdeaSingletonInspection; import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.psi.PsiElementVisitor; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class SingletonPatternInspection extends AbstractBaseJavaLocalInspectionTool { @SuppressWarnings({"PublicField"}) public boolean m_checkFinal = false; @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { return new SingletonPatternInspectionVisitor(holder, m_checkFinal); } @Override public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); optionsPanel.addCheckbox("Check that singletons are final", "m_checkFinal"); return optionsPanel; } }
package com.github.stokito.IdeaSingletonInspection; import com.intellij.codeInspection.BaseJavaLocalInspectionTool; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.psi.PsiElementVisitor; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class SingletonPatternInspection extends BaseJavaLocalInspectionTool { @SuppressWarnings({"PublicField"}) public boolean m_checkFinal = false; @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { return new SingletonPatternInspectionVisitor(holder, m_checkFinal); } @Override public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); optionsPanel.addCheckbox("Check that singletons are final", "m_checkFinal"); return optionsPanel; } }
Fix use of Ember global Fixes #827
(function() { if (typeof FastBoot === 'undefined') { var current = document.getElementById('fastboot-body-start'); var Ember = require('ember').default; if ( current && typeof Ember.ViewUtils.isSerializationFirstNode === 'function' && Ember.ViewUtils.isSerializationFirstNode(current.nextSibling) ) { Ember.ApplicationInstance.reopen({ _bootSync: function(options) { if (options === undefined) { options = { _renderMode: 'rehydrate' }; } return this._super(options); } }); // Prevent clearRender by removing `fastboot-body-start` which is already // guarded for current.parentNode.removeChild(current); var end = document.getElementById('fastboot-body-end'); if (end) { end.parentNode.removeChild(end); } } } })();
(function() { if (typeof FastBoot === 'undefined') { var current = document.getElementById('fastboot-body-start'); if ( current && typeof Ember.ViewUtils.isSerializationFirstNode === 'function' && Ember.ViewUtils.isSerializationFirstNode(current.nextSibling) ) { Ember.ApplicationInstance.reopen({ _bootSync: function(options) { if (options === undefined) { options = { _renderMode: 'rehydrate' }; } return this._super(options); } }); // Prevent clearRender by removing `fastboot-body-start` which is already // guarded for current.parentNode.removeChild(current); var end = document.getElementById('fastboot-body-end'); if (end) { end.parentNode.removeChild(end); } } } })();
Fix wrong type for title in post model.
/*jslint eqeq: true, indent: 2, node: true, plusplus: true, regexp: true, unparam: true, vars: true, nomen: true */ 'use strict'; var Schema = require('mongoose').Schema; /** * The article schema. */ var PostSchema = new Schema({ type: {type: Number, 'default': 0}, authorId: String, catalogId: {type: String, ref: 'Catalog'}, tags: [String], title: String, content: String, date: {type: Date, 'default': Date.now} }); var statics = PostSchema.statics; statics.listLatestPosts = function (param, cb) { var q = this.find(); if (param) { if (param.start) { q.skip(param.start); } if (param.limit) { q.limit(param.limit); } } q.sort({date: 'desc'}); if (cb) { return q.exec(cb); } else { return q; } }; module.exports = PostSchema;
/*jslint eqeq: true, indent: 2, node: true, plusplus: true, regexp: true, unparam: true, vars: true, nomen: true */ 'use strict'; var Schema = require('mongoose').Schema; /** * The article schema. */ var PostSchema = new Schema({ type: {type: Number, 'default': 0}, authorId: String, catalogId: {type: String, ref: 'Catalog'}, tags: [String], title: Number, content: String, date: {type: Date, 'default': Date.now} }); var statics = PostSchema.statics; statics.listLatestPosts = function (param, cb) { var q = this.find(); if (param) { if (param.start) { q.skip(param.start); } if (param.limit) { q.limit(param.limit); } } q.sort({date: 'desc'}); if (cb) { return q.exec(cb); } else { return q; } }; module.exports = PostSchema;
Fix UUID column error in membership seeder
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: new Sequelize.UUIDV1(), memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: new Sequelize.UUIDV1(), memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: Sequelize.UUIDV1, memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: Sequelize.UUIDV1, memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
Change signature to match other resources auth functions
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token): return False def delete(token): return False
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token=None): return False def delete(token=None): return False
Disable end-to-end tests for debugging (will re-enable later!)
#!/usr/bin/env python # ---------------------------------------------------------------------------------------------- # Created by: Lee & Matt # # Description: Contains unit test for BioID Class # ---------------------------------------------------------------------------------------------- # ============================================================================================== import os import yaml from subprocess import call # Nose test generator to iterate format test files defined in CSVs class TestConversion(object): def tests(self): with open("./testing/conversion_tests.yml", "rU") as tests_file: test_cases = tests_file.read() for test_case in yaml.safe_load(test_cases): inputs = test_case["inputs"] outputs = test_case["outputs"] formats = test_case["formats"] alphabet = test_case["alphabet"] if "alphabet" in test_case else None yield self.check_conversion, inputs, outputs, formats, alphabet @staticmethod def check_conversion(input_files, expected_outputs, output_formats, alphabet): # Disable for debugging assert True return # Set up CLI arguments args = "-i %s -f %s -a %s" % (",".join(input_files), ",".join(output_formats), alphabet) # Do conversion(s) ret = call("python BioMagick.py " + args) assert ret == 0 # Check outputs files = os.listdir("./") for output_file in expected_outputs: assert output_file in files # Clean up each output file as it's verified os.remove(output_file)
#!/usr/bin/env python # ---------------------------------------------------------------------------------------------- # Created by: Lee & Matt # # Description: Contains unit test for BioID Class # ---------------------------------------------------------------------------------------------- # ============================================================================================== import os import yaml from subprocess import call # Nose test generator to iterate format test files defined in CSVs class TestConversion(object): def tests(self): with open("./testing/conversion_tests.yml", "rU") as tests_file: test_cases = tests_file.read() for test_case in yaml.safe_load(test_cases): inputs = test_case["inputs"] outputs = test_case["outputs"] formats = test_case["formats"] alphabet = test_case["alphabet"] if "alphabet" in test_case else None yield self.check_conversion, inputs, outputs, formats, alphabet @staticmethod def check_conversion(input_files, expected_outputs, output_formats, alphabet): # Set up CLI arguments args = "-i %s -f %s -a %s" % (",".join(input_files), ",".join(output_formats), alphabet) # Do conversion(s) ret = call("python BioMagick.py " + args) assert ret == 0 # Check outputs files = os.listdir("./") for output_file in expected_outputs: assert output_file in files # Clean up each output file as it's verified os.remove(output_file)
Add file handler for logs
#!/usr/bin/env python3 import logging from aiohttp import web import asyncio import json import aiohttp import litecord import litecord_config as config logging.basicConfig(level=logging.DEBUG, \ format='[%(levelname)7s] [%(name)s] %(message)s') log = logging.getLogger('litecord') handler = logging.FileHandler('litecord.log') handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - [%(levelname)s] [%(name)s] %(message)s') handler.setFormatter(formatter) log.addHandler(handler) app = web.Application() async def give_gateway(request): return web.Response(text=json.dumps({"url": "ws://0.0.0.0:12000"})) async def index(request): return web.Response(text=json.dumps({"goto": "/api/gateway"})) def main(): app.router.add_get('/', index) app.router.add_get('/api/gateway', give_gateway) loop = asyncio.get_event_loop() log.debug("[main] starting ws task") gateway_task = loop.create_task(litecord.gateway_server(app, config.flags)) log.debug("[main] starting http") web.run_app(app, port=8000) log.info("Exiting...") gateway_task.cancel() loop.close() if __name__ == "__main__": main()
#!/usr/bin/env python3 import logging from aiohttp import web import asyncio import json import aiohttp import litecord import litecord_config as config logging.basicConfig(level=logging.DEBUG, \ format='[%(levelname)7s] [%(name)s] %(message)s') log = logging.getLogger('litecord') app = web.Application() async def give_gateway(request): return web.Response(text=json.dumps({"url": "ws://0.0.0.0:12000"})) async def index(request): return web.Response(text=json.dumps({"goto": "/api/gateway"})) def main(): app.router.add_get('/', index) app.router.add_get('/api/gateway', give_gateway) loop = asyncio.get_event_loop() log.debug("[main] starting ws task") gateway_task = loop.create_task(litecord.gateway_server(app, config.flags)) log.debug("[main] starting http") web.run_app(app, port=8000) log.info("Exiting...") gateway_task.cancel() loop.close() if __name__ == "__main__": main()
Improve acceptance test assertion by printing out error type This is useful to distinguish between e.g. a 500 and 404 status code.
package helper import ( "encoding/json" "reflect" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") errorPayload, _ := json.MarshalIndent(err, "", " ") t.Fatalf("Failed to perform request! Error: %s %s. Response: %s", getType(err), errorPayload, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } } // Get type name of some value, according to https://stackoverflow.com/questions/35790935/using-reflection-in-go-to-get-the-name-of-a-struct func getType(myvar interface{}) string { if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr { return "*" + t.Elem().Name() } else { return t.Name() } }
package helper import ( "encoding/json" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") errorPayload, _ := json.MarshalIndent(err, "", " ") t.Fatalf("Failed to perform request, because %s. Response:\n%s", errorPayload, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } }