text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Send HTTP responses for all messages
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); res.send(200); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); res.send(200); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; session.get(phoneNumber, function(err, user) { if (err) messenger.send(phoneNumber, 'There was some kind of error.') if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { res.send(phoneNumber, 'Nice to meet you.') }) } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
Test IE10 instead of IE9
exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, framework: 'jasmine2', sauceSeleniumAddress: 'localhost:4444/wd/hub', baseUrl: 'http://localhost:8000', specs: ['*[sS]pec.js'], multiCapabilities: [{ browserName: 'chrome', platform: 'Windows 7', version: '45.0' }, { browserName: 'firefox', platform: 'Windows 7', version: '41.0' }, { browserName: 'internet explorer', platform: 'Windows 7', version: '10.0' }, { browserName: 'safari', platform: 'OS X 10.10', version: '8.0' }] }
exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, framework: 'jasmine2', sauceSeleniumAddress: 'localhost:4444/wd/hub', baseUrl: 'http://localhost:8000', specs: ['*[sS]pec.js'], multiCapabilities: [{ browserName: 'chrome', platform: 'Windows 7', version: '45.0' }, { browserName: 'firefox', platform: 'Windows 7', version: '41.0' }, { browserName: 'internet explorer', platform: 'Windows 7', version: '9.0' }, { browserName: 'safari', platform: 'OS X 10.10', version: '8.0' }] }
[fix][patch] Delete Bin for non-stock item
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.utilities.repost_stock import update_bin_qty, get_reserved_qty def execute(): repost_for = frappe.db.sql(""" select distinct item_code, warehouse from ( ( select distinct item_code, warehouse from `tabSales Order Item` where docstatus=1 ) UNION ( select distinct item_code, warehouse from `tabPacked Item` where docstatus=1 and parenttype='Sales Order' ) ) so_item where exists(select name from tabItem where name=so_item.item_code and ifnull(is_stock_item, 0)=1) """) for item_code, warehouse in repost_for: update_bin_qty(item_code, warehouse, { "reserved_qty": get_reserved_qty(item_code, warehouse) }) frappe.db.sql("""delete from tabBin where exists( select name from tabItem where name=tabBin.item_code and ifnull(is_stock_item, 0) = 0 ) """)
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.utilities.repost_stock import update_bin_qty, get_reserved_qty def execute(): repost_for = frappe.db.sql(""" select distinct item_code, warehouse from ( ( select distinct item_code, warehouse from `tabSales Order Item` where docstatus=1 ) UNION ( select distinct item_code, warehouse from `tabPacked Item` where docstatus=1 and parenttype='Sales Order' ) ) so_item where exists(select name from tabItem where name=so_item.item_code and ifnull(is_stock_item, 0)=1) """) for item_code, warehouse in repost_for: update_bin_qty(item_code, warehouse, { "reserved_qty": get_reserved_qty(item_code, warehouse) })
Change default db name to g2x.db
import sqlite3 import time class SQLiteLogger: def __init__(self, filename="g2x.db"): self.filename = filename self.connection = None def __enter__(self): try: with open(self.filename): self.connection = sqlite3.connect(self.filename) except IOError: self.connection = sqlite3.connect(self.filename) cursor = self.connection.cursor() cursor.execute('''CREATE TABLE readings (date real, device text, property text, value real)''') self.connection.commit() return self def __exit__(self, type, value, traceback): self.connection.close() self.connection = None def log(self, device, property, value, t=None): if t is None: t = time.time() values = (t, device, property, value) cursor = self.connection.cursor() cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) self.connection.commit()
import sqlite3 import time class SQLiteLogger: def __init__(self, filename="test.db"): self.filename = filename self.connection = None def __enter__(self): try: with open(self.filename): self.connection = sqlite3.connect(self.filename) except IOError: self.connection = sqlite3.connect(self.filename) cursor = self.connection.cursor() cursor.execute('''CREATE TABLE readings (date real, device text, property text, value real)''') self.connection.commit() return self def __exit__(self, type, value, traceback): self.connection.close() self.connection = None def log(self, device, property, value, t=None): if t is None: t = time.time() values = (t, device, property, value) cursor = self.connection.cursor() cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) self.connection.commit()
Clear screen at start of program
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop()
Update for python 3 and new idx design idx no longer writes to files, it only processes bytes
from .. import idx import os def test__count_dimensions(): yield check__count_dimensions, 9, 0 yield check__count_dimensions, [1, 2], 1 yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2 yield check__count_dimensions, [[[1,2], [2]]], 3 def check__count_dimensions(lst, i): assert idx._count_dimensions(lst) == i # these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/ _somelist = [[1, 2], [3, 4]] _somebytes = b'\x00\x00\x0C\x02' + b'\x01\x02\x03\x04' def test_list_to_idx(): data = idx.list_to_idx(_somelist, 'i') assert data == _somebytes def test_idx_to_list(): lst = idx.idx_to_list(_somebytes) assert lst == _somelist
from .. import idx import os def test__find_depth(): yield check__find_depth, 9, 0 yield check__find_depth, [1, 2], 1 yield check__find_depth, [[1, 2], [3, 6, 2]], 2 yield check__find_depth, [[[1,2], [2]]], 3 def check__find_depth(lst, i): assert idx._find_dimensions(lst) == i # these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/ _somelist = [[1, 2], [3, 4]] _somebytes = '\x00\x00\x0C\x02' + '\x01\x02\x03\x04' _testfolder = os.path.dirname(os.path.realpath(__file__)) _somepath = os.path.join(_testfolder, 'test_idx_file') def test_list_to_idx(): idx.list_to_idx(_somelist, _somepath, 'i') with open(_somepath, 'rb') as f: data = f.read() os.remove(_somepath) assert data == _somebytes def test_idx_to_list(): with open(_somepath, 'wb') as f: f.write(_somebytes) lst = idx.idx_to_list(_somepath) os.remove(_somepath) assert lst == _somelist
Fix regression - internal reflect lib changes!
// satisfy ag-grid HTMLElement dependency HTMLElement = typeof HTMLElement === 'undefined' ? function () {} : HTMLElement; HTMLSelectElement = typeof HTMLSelectElement === 'undefined' ? function () {} : HTMLSelectElement; HTMLInputElement = typeof HTMLInputElement === 'undefined' ? function () {} : HTMLInputElement; HTMLButtonElement = typeof HTMLButtonElement === 'undefined' ? function () {} : HTMLButtonElement; var {AgGridNg2} = require('./dist/agGridNg2'); var {ComponentUtil} = require("ag-grid/main"); var missingProperties = []; ComponentUtil.ALL_PROPERTIES.forEach((property) => { if (!AgGridNg2.propDecorators.hasOwnProperty(property)) { missingProperties.push(`Grid property ${property} does not exist on AgGridNg2`) } }); var missingEvents = []; ComponentUtil.EVENTS.forEach((event) => { if (!AgGridNg2.propDecorators.hasOwnProperty(event)) { missingEvents.push(`Grid event ${event} does not exist on AgGridNg2`) } }); if(missingProperties.length || missingEvents.length) { console.error("*************************** BUILD FAILED ***************************"); missingProperties.concat(missingEvents).forEach((message) => console.error(message)); console.error("*************************** BUILD FAILED ***************************"); throw("Build Properties Check Failed"); } else { console.info("*************************** BUILD OK ***************************"); }
// satisfy ag-grid HTMLElement dependency HTMLElement = typeof HTMLElement === 'undefined' ? function () {} : HTMLElement; HTMLSelectElement = typeof HTMLSelectElement === 'undefined' ? function () {} : HTMLSelectElement; HTMLInputElement = typeof HTMLInputElement === 'undefined' ? function () {} : HTMLInputElement; HTMLButtonElement = typeof HTMLButtonElement === 'undefined' ? function () {} : HTMLButtonElement; require('./node_modules/reflect-metadata'); var {AgGridNg2} = require('./dist/agGridNg2'); var {ComponentUtil} = require("ag-grid/main"); var missingProperties = []; ComponentUtil.ALL_PROPERTIES.forEach((property) => { if (!Reflect.getOwnMetadata('propMetadata', AgGridNg2).hasOwnProperty(property)) { missingProperties.push(`Grid property ${property} does not exist on AgGridNg2`) } }); var missingEvents = []; ComponentUtil.EVENTS.forEach((event) => { if (!Reflect.getOwnMetadata('propMetadata', AgGridNg2).hasOwnProperty(event)) { missingEvents.push(`Grid event ${event} does not exist on AgGridNg2`) } }); if(missingProperties.length || missingEvents.length) { console.error("*************************** BUILD FAILED ***************************"); missingProperties.concat(missingEvents).forEach((message) => console.error(message)); console.error("*************************** BUILD FAILED ***************************"); throw("Build Properties Check Failed"); } else { console.info("*************************** BUILD OK ***************************"); }
Fix string index out of bounds
package io.digdag.cli; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; import java.util.HashMap; import java.util.List; import java.util.Map; public class ParameterValidator implements IParameterValidator { public void validate(String name, String value) throws ParameterException { if (!value.contains("=")) { throw new ParameterException("Parameter " + name + " expected a value of the form a=b but got:" + value); } } public static Map<String, String> toMap(List<String> list) { Map<String, String> map = new HashMap<>(); String key = null; for (String value : list) { if (value.contains("=")) { key = value.substring(0, value.indexOf("=")); String val = value.substring(value.indexOf("=") + 1); map.put(key, val); } else { String val = new StringBuilder(map.get(key)).append(",").append(value).toString(); map.put(key, val); } } return map; } }
package io.digdag.cli; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; import java.util.HashMap; import java.util.List; import java.util.Map; public class ParameterValidator implements IParameterValidator { public void validate(String name, String value) throws ParameterException { if (!value.contains("=")) { throw new ParameterException("Parameter " + name + " expected a value of the form a=b but got:" + value); } } public static Map<String, String> toMap(List<String> list) { Map<String, String> map = new HashMap<>(); list.forEach(value -> map.put(value.substring(0, value.indexOf("=")), value.substring(value.indexOf("=")+1))); return map; } }
Use set() method instead of __call magic method
<?php namespace BryanCrowe\Growl; use BryanCrowe\Growl\Builder\BuilderAbstract; class Growl { /** * The Builder to use for building the command. * * @var BuilderAbstract */ protected $builder; /** * An array of options to use for building commands. * * @var array */ protected $options = array(); /** * Constructor. * * Accepts a Builder object to be used in building the command. * * @param BuilderAbstract $builder * * @return void */ public function __construct(BuilderAbstract $builder) { $this->builder = $builder; } /** * Executes the built command. * * @return string */ public function execute() { $command = $this->builder->build($this->options); return exec($command); } /** * Set options for Builders with a key/value. * * @param string $key The key. * @param array $value The value of the key. * * @return $this */ public function set($key, $value) { $this->options[$key] = $value; return $this; } }
<?php namespace BryanCrowe\Growl; use BryanCrowe\Growl\Builder\BuilderAbstract; class Growl { /** * The Builder to use for building the command. * * @var BuilderAbstract */ protected $builder; /** * An array of options to use for building commands. * * @var array */ protected $options = array(); /** * Constructor. * * Accepts a Builder object to be used in building the command. * * @param BuilderAbstract $builder * * @return void */ public function __construct(BuilderAbstract $builder) { $this->builder = $builder; } /** * Executes the built command. * * @return string */ public function execute() { $command = $this->builder->build($this->options); return exec($command); } /** * Implement the __call magic method to provide an expressive way of setting * options for commands. * * @param string $name The name of the method called. * @param array $args An array of the supplied arguments. * * @return $this */ public function __call($name, $args) { $this->options[$name] = $args[0]; return $this; } }
Refactor code so we can use command in tests
from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): self._setup() two_years = self.now - relativedelta(years=2) return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years) class Command(BaseCommand): help = ( "Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed" ) def handle(self, *args, **kwargs): instance = FindAndDeleteCasesUsingCreationTime() cases = instance.get_eligible_cases() if len(args) == 0: print(cases.count()) elif args[0] == "test_find": return cases elif args[0] == "delete": instance.run()
from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): self._setup() two_years = self.now - relativedelta(years=2) return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years) class Command(BaseCommand): help = ( "Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed" ) def handle(self, *args, **kwargs): instance = FindAndDeleteCasesUsingCreationTime() if len(args) == 0: cases = instance.get_eligible_cases() print(cases.count()) elif args[0] == "delete": instance.run()
Add __contains__ for proper lookup in cache Engines class.
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------- # Name: cache_engine.py # Python Library # Author: Raymond Wagner # Purpose: Base cache engine class for collecting registered engines #----------------------- class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] def __contains__(self, key): return self._engines.__contains__(key) Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------- # Name: cache_engine.py # Python Library # Author: Raymond Wagner # Purpose: Base cache engine class for collecting registered engines #----------------------- class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
Check currentUser before calling id method
function PostController(post, Auth, PostsService, $stateParams, categories, Flash) { var ctrl = this; if (post) { ctrl.data = post.data; } if (categories) { ctrl.categories = categories.data; } var currentUser; Auth.currentUser().then(function (user) { ctrl.currentUser = user }) ctrl.editPost = function () { if (ctrl.currentUser) { return ctrl.currentUser.id === ctrl.data.author.id } } ctrl.save = function () { if ($stateParams.id && ctrl.editPost()) { PostsService.updatePost($stateParams.id, ctrl.data); } else if (!$stateParams.id) { PostsService.addPost(ctrl.data) } else { var message = "Oops, you can't do that!"; var id = Flash.create('danger', message, 5000); } } ctrl.removePost = function () { if ($stateParams.id && ctrl.editPost()) { PostsService.deletePost($stateParams.id); } else { var message = "Oops, you can't do that!"; var id = Flash.create('danger', message, 5000); } } } PostController.$inject = ['post', 'Auth', 'PostsService', '$stateParams', 'categories', 'Flash']; angular .module('app') .controller('PostController', PostController)
function PostController(post, Auth, PostsService, $stateParams, categories, Flash) { var ctrl = this; if (post) { ctrl.data = post.data; } if (categories) { ctrl.categories = categories.data; } var currentUser; Auth.currentUser().then(function (user) { ctrl.currentUser = user }) ctrl.editPost = function () { return ctrl.currentUser.id === ctrl.data.author.id } ctrl.save = function () { if ($stateParams.id && ctrl.editPost()) { PostsService.updatePost($stateParams.id, ctrl.data); } else if (!$stateParams.id) { PostsService.addPost(ctrl.data) } else { var message = "Oops, you can't do that!"; var id = Flash.create('danger', message, 5000); } } ctrl.removePost = function () { if ($stateParams.id && ctrl.editPost()) { PostsService.deletePost($stateParams.id); } else { var message = "Oops, you can't do that!"; var id = Flash.create('danger', message, 5000); } } } PostController.$inject = ['post', 'Auth', 'PostsService', '$stateParams', 'categories', 'Flash']; angular .module('app') .controller('PostController', PostController)
Fix bug with buildpacks field not being set Co-authored-by: An Yu <446e9838deaeb979640d56c46523b7c882d598cd@pivotal.io>
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("pushing an app a second time", func() { const ( DownloadRegexp = `Download \[.*/dotnet-sdk\..*\.tar\.xz\]` CopyRegexp = `Copy \[.*/dotnet-sdk\..*\.tar\.xz\]` ) var app *cutlass.App BeforeEach(func() { SkipUnlessUncached() app = cutlass.New(filepath.Join(bpDir, "fixtures", "simple_source_web_2.0")) app.SetEnv("BP_DEBUG", "true") app.Buildpacks = []string{"dotnet_core_buildpack"} }) AfterEach(func() { PrintFailureLogs(app.Name) app = DestroyApp(app) }) It("uses the cache for manifest dependencies", func() { PushAppAndConfirm(app) Expect(app.Stdout.String()).To(MatchRegexp(DownloadRegexp)) Expect(app.Stdout.String()).ToNot(MatchRegexp(CopyRegexp)) app.Stdout.Reset() PushAppAndConfirm(app) Expect(app.Stdout.String()).To(MatchRegexp(CopyRegexp)) Expect(app.Stdout.String()).ToNot(MatchRegexp(DownloadRegexp)) }) })
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("pushing an app a second time", func() { const ( DownloadRegexp = `Download \[.*/dotnet-sdk\..*\.tar\.xz\]` CopyRegexp = `Copy \[.*/dotnet-sdk\..*\.tar\.xz\]` ) var app *cutlass.App BeforeEach(func() { SkipUnlessUncached() app = cutlass.New(filepath.Join(bpDir, "fixtures", "simple_source_web_2.0")) app.SetEnv("BP_DEBUG", "true") }) AfterEach(func() { PrintFailureLogs(app.Name) app = DestroyApp(app) }) It("uses the cache for manifest dependencies", func() { PushAppAndConfirm(app) Expect(app.Stdout.String()).To(MatchRegexp(DownloadRegexp)) Expect(app.Stdout.String()).ToNot(MatchRegexp(CopyRegexp)) app.Stdout.Reset() PushAppAndConfirm(app) Expect(app.Stdout.String()).To(MatchRegexp(CopyRegexp)) Expect(app.Stdout.String()).ToNot(MatchRegexp(DownloadRegexp)) }) })
Update expected output to match what is actually generated by coffeescript
var cubes, list, math, num, number, opposite, race, square, __slice = [].slice; number = 42; opposite = true; if (opposite) { number = -42; } square = function(x) { return x * x; }; list = [1, 2, 3, 4, 5]; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners); }; if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results; })();
var cubes, list, math, num, number, opposite, race, square, __slice = [].slice; number = 42; opposite = true; if (opposite) { number = -42; } square = function(x) { return x * x; }; list = [1, 2, 3, 4, 5]; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners); }; if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results; })();
Add third annotation style. Refactor the style handling to be a bit more DRY. git-svn-id: a0d2519504059b70a86a1ce51b726c2279190bad@24871 6e01202a-0783-4428-890a-84243c50cc2b
package org.concord.datagraph.analysis; import java.awt.Component; import java.util.ArrayList; import org.concord.data.state.OTDataStore; import org.concord.datagraph.analysis.rubric.GraphRubric; import org.concord.datagraph.analysis.rubric.ResultSet; import org.concord.datagraph.state.OTDataCollector; import org.concord.datagraph.state.OTDataGraphable; import org.concord.framework.otrunk.OTObjectList; import org.concord.graph.util.state.OTHideableAnnotation; public interface GraphAnalyzer { public enum AnnotationStyle { ONE, TWO, THREE } public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException; public GraphRubric buildRubric(OTObjectList rubric); public ResultSet compareGraphs(GraphRubric expected, Graph received); public String getHtmlReasons(ResultSet results); public void displayHtmlReasonsPopup(Component parent, ResultSet results); public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector dataCollector, ResultSet scoreResults, AnnotationStyle style); public ArrayList<OTDataGraphable> drawSegmentResults(OTDataCollector dataCollector, Graph graph); }
package org.concord.datagraph.analysis; import java.awt.Component; import java.util.ArrayList; import org.concord.data.state.OTDataStore; import org.concord.datagraph.analysis.rubric.GraphRubric; import org.concord.datagraph.analysis.rubric.ResultSet; import org.concord.datagraph.state.OTDataCollector; import org.concord.datagraph.state.OTDataGraphable; import org.concord.framework.otrunk.OTObjectList; import org.concord.graph.util.state.OTHideableAnnotation; public interface GraphAnalyzer { public enum AnnotationStyle { ONE, TWO } public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException; public GraphRubric buildRubric(OTObjectList rubric); public ResultSet compareGraphs(GraphRubric expected, Graph received); public String getHtmlReasons(ResultSet results); public void displayHtmlReasonsPopup(Component parent, ResultSet results); public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector dataCollector, ResultSet scoreResults, AnnotationStyle style); public ArrayList<OTDataGraphable> drawSegmentResults(OTDataCollector dataCollector, Graph graph); }
Change about section ID from header to about
const About = () => { return ( <header id="about" className="component"> <a href="/" id="about-mainPageButton">Gå til hovedsiden</a> <img className="header-logo" src="assets/images/online_logo.svg" alt="" /> <h1>Velkommen til Online, linjeforeningen for informatikkstudenter ved <a href="http://ntnu.no/">NTNU</a>.</h1> <p className="about-description">Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.</p> <a href="#calendar"><button className="skipToCalendar">Hopp til program</button></a> </header> ); }; export default About;
const About = () => { return ( <header id="header" className="component"> <a href="/" id="about-mainPageButton">Gå til hovedsiden</a> <img className="header-logo" src="assets/images/online_logo.svg" alt="" /> <h1>Velkommen til Online, linjeforeningen for informatikkstudenter ved <a href="http://ntnu.no/">NTNU</a>.</h1> <p className="about-description">Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.</p> <a href="#calendar"><button className="skipToCalendar">Hopp til program</button></a> </header> ); }; export default About;
Add custom psiTurk as dependency link
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='wallace-platform', packages=['wallace'], version="0.11.2", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], }, dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk'] ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='wallace-platform', packages=['wallace'], version="0.11.2", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], } ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
Remove redundant type in declaration
package org.folio.okapi.util; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Handler; import java.util.LinkedList; import java.util.List; import org.folio.okapi.common.ErrorType; import org.folio.okapi.common.ExtendedAsyncResult; import org.folio.okapi.common.Failure; import org.folio.okapi.common.Success; public class CompList<T> { List<Future> futures = new LinkedList<>(); ErrorType errorType; public CompList(ErrorType type) { errorType = type; } public void add(Future f) { futures.add(f); } public void all(T l, Handler<ExtendedAsyncResult<T>> fut) { CompositeFuture.all(futures).setHandler(res2 -> { if (res2.failed()) { fut.handle(new Failure<>(errorType, res2.cause())); } else { fut.handle(new Success<>(l)); } }); } public void all(Handler<ExtendedAsyncResult<Void>> fut) { CompositeFuture.all(futures).setHandler(res2 -> { if (res2.failed()) { fut.handle(new Failure<>(errorType, res2.cause())); } else { fut.handle(new Success<>()); } }); } }
package org.folio.okapi.util; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Handler; import java.util.LinkedList; import java.util.List; import org.folio.okapi.common.ErrorType; import org.folio.okapi.common.ExtendedAsyncResult; import org.folio.okapi.common.Failure; import org.folio.okapi.common.Success; public class CompList<T> { List<Future> futures = new LinkedList<>(); ErrorType errorType; public CompList(ErrorType type) { errorType = type; } public void add(Future f) { futures.add(f); } public <T> void all(T l, Handler<ExtendedAsyncResult<T>> fut) { CompositeFuture.all(futures).setHandler(res2 -> { if (res2.failed()) { fut.handle(new Failure<>(errorType, res2.cause())); } else { fut.handle(new Success<>(l)); } }); } public <T> void all(Handler<ExtendedAsyncResult<Void>> fut) { CompositeFuture.all(futures).setHandler(res2 -> { if (res2.failed()) { fut.handle(new Failure<>(errorType, res2.cause())); } else { fut.handle(new Success<>()); } }); } }
Remove unnecessary check for loading file
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Button = app.Button || require('./button.js'); var LoadButton = Button.inherits(function(props) { this.loader = props.loader; this.registerChangeListener(); }); LoadButton.prototype.inputElement = function() { return dom.child(this.element(), 2); }; LoadButton.prototype.registerChangeListener = function() { dom.on(this.inputElement(), 'change', LoadButton.prototype.onchange.bind(this)); }; LoadButton.prototype.ontap = function() { dom.click(this.inputElement()); }; LoadButton.prototype.onchange = function(event) { this.loader(dom.file(dom.target(event))); }; if (typeof module !== 'undefined' && module.exports) { module.exports = LoadButton; } else { app.LoadButton = LoadButton; } })(this.app || (this.app = {}));
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Button = app.Button || require('./button.js'); var LoadButton = Button.inherits(function(props) { this.loader = props.loader; this.registerChangeListener(); }); LoadButton.prototype.inputElement = function() { return dom.child(this.element(), 2); }; LoadButton.prototype.registerChangeListener = function() { dom.on(this.inputElement(), 'change', LoadButton.prototype.onchange.bind(this)); }; LoadButton.prototype.ontap = function() { dom.click(this.inputElement()); }; LoadButton.prototype.onchange = function(event) { var file = dom.file(dom.target(event)); if (file) { this.loader(file); } }; if (typeof module !== 'undefined' && module.exports) { module.exports = LoadButton; } else { app.LoadButton = LoadButton; } })(this.app || (this.app = {}));
Fix db ref for SO
export let baseUrl = 'http://rosettastack.com'; export let sites = [{ name: 'Programmers', slug: 'programmers', seUrl: 'http://programmers.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/programmers', }, { name: 'Coffee', slug: 'coffee', seUrl: 'http://coffee.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/coffee', }, { name: 'Server Fault', slug: 'serverfault', seUrl: 'http://serverfault.com/', langs: ['en', 'fr'], db: 'localhost/serverfault', }, { name: 'Super User', slug: 'superuser', seUrl: 'http://superuser.com/', langs: ['en', 'fr'], db: 'localhost/superuser', }, { name: 'Stack Overflow', slug: 'stackoverflow', seUrl: 'http://stackoverflow.com/', langs: ['en', 'fr'], db: 'localhost/stackoverflow', }, { name: 'Android', slug: 'android', seUrl: 'http://android.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/android', }, { name: 'Tor', slug: 'tor', seUrl: 'http://tor.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/tor', }];
export let baseUrl = 'http://rosettastack.com'; export let sites = [{ name: 'Programmers', slug: 'programmers', seUrl: 'http://programmers.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/programmers', }, { name: 'Coffee', slug: 'coffee', seUrl: 'http://coffee.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/coffee', }, { name: 'Server Fault', slug: 'serverfault', seUrl: 'http://serverfault.com/', langs: ['en', 'fr'], db: 'localhost/serverfault', }, { name: 'Super User', slug: 'superuser', seUrl: 'http://superuser.com/', langs: ['en', 'fr'], db: 'localhost/superuser', }, { name: 'Stack Overflow', slug: 'stackoverflow', seUrl: 'http://stackoverflow.com/', langs: ['en', 'fr'], db: 'localhost/programmers', }, { name: 'Android', slug: 'android', seUrl: 'http://android.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/android', }, { name: 'Tor', slug: 'tor', seUrl: 'http://tor.stackexchange.com/', langs: ['en', 'fr'], db: 'localhost/tor', }];
Include config in exception message Added the configuration needed to disable view annocations.
<?php /* * This file is part of the FOSRestBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FOS\RestBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Checks if the SensioFrameworkExtraBundle views annotations are disabled when using the View Response listener. * * @author Eriksen Costa <eriksencosta@gmail.com> */ class ConfigurationCheckPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if ($container->has('sensio_framework_extra.view.listener') && $container->has('fos_rest.view_response_listener')) { throw new \RuntimeException('You need to disable the view annotations in SensioFrameworkExtraBundle when using the FOSRestBundle View Response listener. Add "view: { annotations: false }" to the sensio_framework_extra: section of your config.yml'); } if ($container->has('fos_rest.converter.request_body') && !$container->has('sensio_framework_extra.converter.listener')) { throw new \RuntimeException('You need to enable the parameter converter listeners in SensioFrameworkExtraBundle when using the FOSRestBundle RequestBodyParamConverter'); } } }
<?php /* * This file is part of the FOSRestBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FOS\RestBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Checks if the SensioFrameworkExtraBundle views annotations are disabled when using the View Response listener. * * @author Eriksen Costa <eriksencosta@gmail.com> */ class ConfigurationCheckPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if ($container->has('sensio_framework_extra.view.listener') && $container->has('fos_rest.view_response_listener')) { throw new \RuntimeException('You need to disable the view annotations in SensioFrameworkExtraBundle when using the FOSRestBundle View Response listener.'); } if ($container->has('fos_rest.converter.request_body') && !$container->has('sensio_framework_extra.converter.listener')) { throw new \RuntimeException('You need to enable the parameter converter listeners in SensioFrameworkExtraBundle when using the FOSRestBundle RequestBodyParamConverter'); } } }
Split `alert` method into two different methods
<?php namespace TomIrons\Tuxedo\Mailables; use TomIrons\Tuxedo\Message; use TomIrons\Tuxedo\TuxedoMailable; class AlertMailable extends TuxedoMailable { use Message; /** * The view to use for the message. * * @var string */ public $view = 'tuxedo::templates.alert'; /** * The type of alert. * * @var string|null */ public $type = null; /** * The text of the alert. * * @var string|null */ public $message = null; /** * Set the type of alert for the message. * * @param string $type * @return $this */ public function type($type) { $this->type = $type; return $this; } /** * Set the alert "message" for the message. * * @param string $message * @return $this */ public function message($message) { $this->message = $message; return $this; } }
<?php namespace TomIrons\Tuxedo\Mailables; use TomIrons\Tuxedo\Message; use TomIrons\Tuxedo\TuxedoMailable; class AlertMailable extends TuxedoMailable { use Message; /** * The view to use for the message. * * @var string */ public $view = 'tuxedo::templates.alert'; /** * The type of alert. * * @var string|null */ public $alertType = null; /** * The text of the alert. * * @var string|null */ public $alertText = null; /** * Set the alert type and text for the message. * * @param string $type * @param string $text * @return $this */ public function alert($type, $text) { $this->alertType = $type; $this->alertText = $text; return $this; } }
Make sure to run realpath on $file Do that only when it's local stream.
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); stream_is_local($file) && ($file = realpath($file)); if (0 !== strpos($file, $prefix)) { continue; } $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force); } return $paths; } }
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); if (0 !== strpos($file, $prefix)) { continue; } $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force); } return $paths; } }
Include links to source code with viewcode extension
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
Rename variables from Gittip to Gratipay
<?php require '../src/Curl/Curl.php'; use \Curl\Curl; define('GRATIPAY_USERNAME', 'XXXXXXXXXX'); define('GRATIPAY_API_KEY', 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'); $data = array( array( 'username' => 'user' . mt_rand(), 'platform' => 'gittip', 'amount' => '0.02', ), array( 'username' => 'user' . mt_rand(), 'platform' => 'gittip', 'amount' => '0.02', ), ); $curl = new Curl(); $curl->setHeader('Content-Type', 'application/json'); $curl->setBasicAuthentication(GRATIPAY_API_KEY); $curl->post('https://www.gittip.com/' . GRATIPAY_USERNAME . '/tips.json', json_encode($data)); foreach ($curl->response as $tip) { echo $tip->amount . ' given to ' . $tip->username . '.' . "\n"; }
<?php require '../src/Curl/Curl.php'; use \Curl\Curl; define('GITTIP_USERNAME', 'XXXXXXXXXX'); define('GITTIP_API_KEY', 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'); $data = array( array( 'username' => 'user' . mt_rand(), 'platform' => 'gittip', 'amount' => '0.02', ), array( 'username' => 'user' . mt_rand(), 'platform' => 'gittip', 'amount' => '0.02', ), ); $curl = new Curl(); $curl->setHeader('Content-Type', 'application/json'); $curl->setBasicAuthentication(GITTIP_API_KEY); $curl->post('https://www.gittip.com/' . GITTIP_USERNAME . '/tips.json', json_encode($data)); foreach ($curl->response as $tip) { echo $tip->amount . ' given to ' . $tip->username . '.' . "\n"; }
Remove ssid/key from example script.
# MQTT Example. # This example shows how to use the MQTT library. # # 1) Copy the mqtt.py library to OpenMV storage. # 2) Install the mosquitto client on PC and run the following command: # mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v # import time, network from mqtt import MQTTClient SSID='' # Network SSID KEY='' # Network key # Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) client = MQTTClient("openmv", "test.mosquitto.org", port=1883) client.connect() while (True): client.publish("openmv/test", "Hello World!") time.sleep(1000)
# MQTT Example. # This example shows how to use the MQTT library. # # 1) Copy the mqtt.py library to OpenMV storage. # 2) Install the mosquitto client on PC and run the following command: # mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v # import time, network from mqtt import MQTTClient SSID='mux' # Network SSID KEY='j806fVnT7tObdCYE' # Network key # Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) client = MQTTClient("openmv", "test.mosquitto.org", port=1883) client.connect() while (True): client.publish("openmv/test", "Hello World!") time.sleep(1000)
Use the REST client get_or_create helper function.
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from qiprofile_rest_client.model.imaging import Session from . import (clinical, imaging) def sync_session(project, collection, subject, session, filename): """ Updates the qiprofile database from the XNAT database content for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session number :param filename: the XLS input file location """ # Get or create the subject database subject. key = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, key) # Update the clinical information from the XLS input. clinical.sync(sbj, filename) # Update the imaging information from XNAT. imaging.sync(sbj, session)
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from . import (clinical, imaging) def sync_session(project, collection, subject, session, filename): """ Updates the qiprofile database from the XNAT database content for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session name, without subject prefix :param filename: the XLS input file location """ # Get or create the database subject. sbj_pk = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, sbj_pk) # Update the clinical information from the XLS input. clinical.sync(sbj, filename) # Update the imaging information from XNAT. imaging.sync(sbj, session)
Add sessions inline to classes
from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') class SessionInline(admin.TabularInline): model = Session extra = 1 fields = ('start_date_time', 'stop_date_time', 'teacher') class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): inlines = [ SessionInline, ] admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') # fieldsets = ( # ("Attendee", {'fields': ('name'),}), # ("Start Date Time", {"fields": ('start_date_time'),}), # ("Stop Date Time", {"fields": ('stop_date_time'),}), # ('Notes', {'fields': ('notes'),}), # ) class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): pass admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
Make the compression optional, as it slows down.
import theano as _th import numpy as _np def create_param(shape, init, fan=None, name=None, type=_th.config.floatX): return _th.shared(init(shape, fan).astype(type), name=name) def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX): val = init(shape, fan).astype(type) param = _th.shared(val, name=name) grad_name = 'grad_' + name if name is not None else None grad_param = _th.shared(_np.zeros_like(val), name=grad_name) return param, grad_param def create_param_state_as(other, initial_value=0, prefix='state_for_'): return _th.shared(other.get_value()*0 + initial_value, broadcastable=other.broadcastable, name=prefix + str(other.name) ) def count_params(module): params, _ = module.parameters() return sum(p.get_value().size for p in params) def save_params(module, where, compress=False): params, _ = module.parameters() savefn = _np.savez_compressed if compress else _np.savez savefn(where, params=[p.get_value() for p in params]) def load_params(module, fromwhere): params, _ = module.parameters() with _np.load(fromwhere) as f: for p, v in zip(params, f['params']): p.set_value(v)
import theano as _th import numpy as _np def create_param(shape, init, fan=None, name=None, type=_th.config.floatX): return _th.shared(init(shape, fan).astype(type), name=name) def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX): val = init(shape, fan).astype(type) param = _th.shared(val, name=name) grad_name = 'grad_' + name if name is not None else None grad_param = _th.shared(_np.zeros_like(val), name=grad_name) return param, grad_param def create_param_state_as(other, initial_value=0, prefix='state_for_'): return _th.shared(other.get_value()*0 + initial_value, broadcastable=other.broadcastable, name=prefix + str(other.name) ) def count_params(module): params, _ = module.parameters() return sum(p.get_value().size for p in params) def save_params(module, where): params, _ = module.parameters() _np.savez_compressed(where, params=[p.get_value() for p in params]) def load_params(module, fromwhere): params, _ = module.parameters() with _np.load(fromwhere) as f: for p, v in zip(params, f['params']): p.set_value(v)
Fix package path issue caused by previous refactoring commit.
from django.contrib.auth.models import User, Group from ztreeauth.models import LocalUser from ztreecrud.component.factories import create_node_factory import logging logger = logging.getLogger('ztreeauth') def local_user_factory(request, local_user_content_type, **kwargs): logger.info('creating local user "%s" at %s with groups %s' % (kwargs['username'], (request.tree_context.node and request.tree_context.node.absolute_path), kwargs['groups'])) user = User(username=kwargs['username']) user.set_password(kwargs['password1']) user.save() # create LocalUser local_user = LocalUser(user=user) local_user.save() # set auth groups for local_user for group_name in kwargs['groups']: grp = Group.objects.get(name=group_name) local_user.groups.add(grp) if hasattr(request, 'user'): username = request.user.username else: # if serving backend tree web service, no auth and no request.user username = kwargs.get('authenticated_username') new_node = create_node_factory(local_user, parent_node=request.tree_context.node, username=username, slug=user.username) return new_node
from django.contrib.auth.models import User, Group from ztreeauth.models import LocalUser from ztree.component.factories import create_node_factory import logging logger = logging.getLogger('ztreeauth') def local_user_factory(request, local_user_content_type, **kwargs): logger.info('creating local user "%s" at %s with groups %s' % (kwargs['username'], (request.tree_context.node and request.tree_context.node.absolute_path), kwargs['groups'])) user = User(username=kwargs['username']) user.set_password(kwargs['password1']) user.save() # create LocalUser local_user = LocalUser(user=user) local_user.save() # set auth groups for local_user for group_name in kwargs['groups']: grp = Group.objects.get(name=group_name) local_user.groups.add(grp) if hasattr(request, 'user'): username = request.user.username else: # if serving backend tree web service, no auth and no request.user username = kwargs.get('authenticated_username') new_node = create_node_factory(local_user, parent_node=request.tree_context.node, username=username, slug=user.username) return new_node
Test WSGI start_response is called
import mock import unittest from resto.wsgi import Middleware class AppTestCase(unittest.TestCase): def setUp(self): self.environ = { 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': True, } self.mock_start = mock.Mock() def test_application_init(self): result = Middleware(self.environ, self.mock_start) content = '' for data in result: content += data self.assertGreater(content, '') self.assertTrue(self.mock_start.called) if __name__ == '__main__': unittest.main()
import mock import unittest from resto.wsgi import Middleware class AppTestCase(unittest.TestCase): def setUp(self): self.environ = { 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': True, } self.mock_start = mock.Mock() def test_application_init(self): result = Middleware(self.environ, self.mock_start) content = '' for data in result: content += data self.assertGreater(content, '') if __name__ == '__main__': unittest.main()
Use actual path to template
from django.contrib.syndication.views import Feed from .models import Post from .settings import ( SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK, SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE ) class LatestPostFeed(Feed): title = SYNDICATION_FEED_TITLE link = SYNDICATION_FEED_LINK description = SYNDICATION_FEED_DESCRIPTION feed_type = SYNDICATION_FEED_TYPE description_template = 'hermes/feed_post_description.html def items(self): return Post.objects.recent() def item_title(self, item): return item.subject def item_description(self, item): return item.body def item_pubdate(self, item): return item.created_on def item_updateddate(self, item): return item.modified_on def item_categories(self, item): return [category.title for category in item.category.hierarchy()] def item_author_name(self, item): return "{first_name} {last_name}".format( first_name=item.author.first_name, last_name=item.author.last_name, ) def item_author_email(self, item): return item.author.email
from django.contrib.syndication.views import Feed from .models import Post from .settings import ( SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK, SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE ) class LatestPostFeed(Feed): title = SYNDICATION_FEED_TITLE link = SYNDICATION_FEED_LINK description = SYNDICATION_FEED_DESCRIPTION feed_type = SYNDICATION_FEED_TYPE description_template = 'feed_post_description.html def items(self): return Post.objects.recent() def item_title(self, item): return item.subject def item_description(self, item): return item.body def item_pubdate(self, item): return item.created_on def item_updateddate(self, item): return item.modified_on def item_categories(self, item): return [category.title for category in item.category.hierarchy()] def item_author_name(self, item): return "{first_name} {last_name}".format( first_name=item.author.first_name, last_name=item.author.last_name, ) def item_author_email(self, item): return item.author.email
Watch dragulaModel in case the model is an array setup after app initialization.
'use strict'; var dragula = require('dragula'); /*jshint unused: false*/ function register (angular) { return ['dragulaService', function angularDragula (dragulaService) { return { restrict: 'A', scope: { dragulaScope: '=', dragulaModel: '=' }, link: link }; function link (scope, elem, attrs) { var dragulaScope = scope.dragulaScope || scope.$parent; var container = elem[0]; var name = scope.$eval(attrs.dragula); var bag = dragulaService.find(dragulaScope, name); if (bag) { var drake = bag.drake; drake.containers.push(container); } else { var drake = dragula({ containers: [container] }); dragulaService.add(dragulaScope, name, drake); } scope.$watch('dragulaModel', function(model) { if(model){ if(drake.models){ drake.models.push(model); }else{ drake.models = [model]; } } } ); } }]; } module.exports = register;
'use strict'; var dragula = require('dragula'); /*jshint unused: false*/ function register (angular) { return ['dragulaService', function angularDragula (dragulaService) { return { restrict: 'A', scope: { dragulaScope: '=', dragulaModel: '=', }, link: link }; function link (scope, elem, attrs) { var dragulaScope = scope.dragulaScope || scope.$parent; var container = elem[0]; var name = scope.$eval(attrs.dragula); var model = scope.dragulaModel; var bag = dragulaService.find(dragulaScope, name); if (bag) { bag.drake.containers.push(container); if(model){ if(bag.drake.models){ bag.drake.models.push(model); }else{ bag.drake.models = [model]; } } return; } var drake = dragula({ containers: [container] }); if(model){ drake.models = [model]; } dragulaService.add(dragulaScope, name, drake); } }]; } module.exports = register;
Remove fixing result of games.
<?php /** * Created by PhpStorm. * User: stas * Date: 28.05.16 * Time: 17:39 */ namespace CoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class RunEventsCommand * @package CoreBundle\Command */ class CronCommand extends ContainerAwareCommand { protected function configure() { $this->setName('core:cron:run') ->setDescription('Run all current events from `events` table'); } /** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->getContainer()->get("core.handler.event")->runAllCurrentEvents(); } }
<?php /** * Created by PhpStorm. * User: stas * Date: 28.05.16 * Time: 17:39 */ namespace CoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class RunEventsCommand * @package CoreBundle\Command */ class CronCommand extends ContainerAwareCommand { protected function configure() { $this->setName('core:cron:run') ->setDescription('Run all current events from `events` table'); } /** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->getContainer()->get("core.handler.event")->runAllCurrentEvents(); $this->getContainer()->get("core.handler.game")->fixResultGames(); } }
[COM_COURSES] Fix migration syntax. Forgot it changed recently...
<?php use Hubzero\Content\Migration\Base; // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); /** * Migration script for adding is_default column **/ class Migration20140217151012ComCourses extends Base { /** * Up **/ public function up() { if ($this->db->tableExists('#__courses_offering_sections')) { if (!$this->db->tableHasField('#__courses_offering_sections', 'is_default')) { $query = "ALTER TABLE `#__courses_offering_sections` ADD `is_default` TINYINT(2) NOT NULL DEFAULT '0' AFTER `offering_id`"; $this->db->setQuery($query); $this->db->query(); } } } /** * Down **/ public function down() { if ($this->db->tableExists('#__courses_offering_sections')) { if ($this->db->tableHasField('#__courses_offering_sections', 'is_default')) { $query = "ALTER TABLE `#__courses_offering_sections` DROP `is_default`;"; $this->db->setQuery($query); $this->db->query(); } } } }
<?php use Hubzero\Content\Migration\Base; // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); /** * Migration script for adding is_default column **/ class Migration20140217151012ComCourses extends Base { /** * Up **/ public function up() { if ($this->db->tableExists('#__courses_offering_sections')) { if (!$db->tableHasField('#__courses_offering_sections', 'is_default')) { $query = "ALTER TABLE `#__courses_offering_sections` ADD `is_default` TINYINT(2) NOT NULL DEFAULT '0' AFTER `offering_id`"; $db->setQuery($query); $db->query(); } } } /** * Down **/ public function down() { if ($this->db->tableExists('#__courses_offering_sections')) { if ($db->tableHasField('#__courses_offering_sections', 'is_default')) { $query = "ALTER TABLE `#__courses_offering_sections` DROP `is_default`;"; $db->setQuery($query); $db->query(); } } } }
Use correct check for not undefined
const path = require('path'); const port = process.env.PORT || 3000; const screenshotPath = path.resolve(__dirname, '..', 'test', 'acceptance', 'report', 'screenshots'); const reportPath = path.resolve(__dirname, '..', 'test', 'acceptance', 'report'); module.exports = { root: path.normalize(`${__dirname}/..`), env: process.env.NODE_ENV || 'development', ci: process.env.CI, port, googleAnalyticsId: process.env.GOOGLE_ANALYTICS_TRACKING_ID, staticCdn: process.env.STATIC_CDN || '/', trustProtoHeader: typeof process.env.DYNO !== 'undefined', trustAzureHeader: typeof process.env.WEBSITE_SITE_NAME !== 'undefined', logLevel: process.env.LOG_LEVEL || 'warn', webdriver: { baseUrl: process.env.WDIO_BASEURL || `http://localhost:${port}`, screenshotPath: process.env.WDIO_SCREENSHOTPATH || screenshotPath, reportOutput: process.env.WDIO_REPORTPATH || reportPath, }, browserstack: { user: process.env.BROWSERSTACK_USERNAME, key: process.env.BROWSERSTACK_ACCESS_KEY, }, travis: { buildNum: process.env.TRAVIS_BUILD_NUMBER, jobNum: process.env.TRAVIS_JOB_NUMBER, }, feedbackApi: { baseUrl: process.env.FEEDBACK_API_BASEURL, apiKey: process.env.FEEDBACK_API_KEY, }, };
const path = require('path'); const port = process.env.PORT || 3000; const screenshotPath = path.resolve(__dirname, '..', 'test', 'acceptance', 'report', 'screenshots'); const reportPath = path.resolve(__dirname, '..', 'test', 'acceptance', 'report'); module.exports = { root: path.normalize(`${__dirname}/..`), env: process.env.NODE_ENV || 'development', ci: process.env.CI, port, googleAnalyticsId: process.env.GOOGLE_ANALYTICS_TRACKING_ID, staticCdn: process.env.STATIC_CDN || '/', trustProtoHeader: typeof process.env.DYNO !== undefined, trustAzureHeader: typeof process.env.WEBSITE_SITE_NAME !== undefined, logLevel: process.env.LOG_LEVEL || 'warn', webdriver: { baseUrl: process.env.WDIO_BASEURL || `http://localhost:${port}`, screenshotPath: process.env.WDIO_SCREENSHOTPATH || screenshotPath, reportOutput: process.env.WDIO_REPORTPATH || reportPath, }, browserstack: { user: process.env.BROWSERSTACK_USERNAME, key: process.env.BROWSERSTACK_ACCESS_KEY, }, travis: { buildNum: process.env.TRAVIS_BUILD_NUMBER, jobNum: process.env.TRAVIS_JOB_NUMBER, }, feedbackApi: { baseUrl: process.env.FEEDBACK_API_BASEURL, apiKey: process.env.FEEDBACK_API_KEY, }, };
Add docstring to explain the code
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),) def validate_unique(self): """If the form had an error and a station was chosen, we need to setup the widget choices to the previously selected value for the autocomplete to display it properly""" super(BikeModelForm, self).validate_unique() if self.errors and 'id_station' in self.data: self.fields['id_station'].widget.choices = ((self.cleaned_data['id_station'], self.data['station']),) class Meta: widgets = { 'id_station': autocomplete.ListSelect2(url='station-autocomplete', forward=('provider',), attrs={'data-allow-clear': 'false'}) } class Media: js = ('js/admin_form.js',)
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),) def validate_unique(self): super(BikeModelForm, self).validate_unique() if self.errors and 'id_station' in self.data: # A station was chosen, reinit choices with it self.fields['id_station'].widget.choices = ((self.cleaned_data['id_station'], self.data['station']),) class Meta: widgets = { 'id_station': autocomplete.ListSelect2(url='station-autocomplete', forward=('provider',), attrs={'data-allow-clear': 'false'}) } class Media: js = ('js/admin_form.js',)
Use RSVP instead of ember-cli/ext/promise
/* jshint node: true */ var RSVP = require('rsvp'); var spawn = require('child_process').spawn; function run(command, args, opts) { return new RSVP.Promise(function(resolve, reject) { var p = spawn(command, args, opts || {}); var stderr = ''; var stdout = ''; p.stdout.on('data', function(output) { stdout += output; }); p.stderr.on('data', function(output) { stderr += output; }); p.on('close', function(code){ if (code !== 0) { var err = new Error(command + " " + args.join(" ") + " exited with nonzero status"); err.stderr = stderr; err.stdout = stdout; reject(err); } else { resolve({ stdout: stdout, stderr: stderr }); } }); }); } module.exports = run;
/* jshint node: true */ var Promise = require('ember-cli/lib/ext/promise'); var spawn = require('child_process').spawn; function run(command, args, opts) { return new Promise(function(resolve, reject) { var p = spawn(command, args, opts || {}); var stderr = ''; var stdout = ''; p.stdout.on('data', function(output) { stdout += output; }); p.stderr.on('data', function(output) { stderr += output; }); p.on('close', function(code){ if (code !== 0) { var err = new Error(command + " " + args.join(" ") + " exited with nonzero status"); err.stderr = stderr; err.stdout = stdout; reject(err); } else { resolve({ stdout: stdout, stderr: stderr }); } }); }); } module.exports = run;
Allow empty model value for color inputs
angular.module('anol.featurestyleeditor') .directive('color', function() { var COLOR_REGEX = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/; return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { ctrl.$validators.color = function(modelValue, viewValue) { if(ctrl.$isEmpty(modelValue)) { return true; } if(ctrl.$isEmpty(viewValue)) { return false; } var result = COLOR_REGEX.test(viewValue); return result; }; } }; });
angular.module('anol.featurestyleeditor') .directive('color', function() { var COLOR_REGEX = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/; return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { ctrl.$validators.color = function(modelValue, viewValue) { if(ctrl.$isEmpty(modelValue)) { return false; } if(ctrl.$isEmpty(viewValue)) { return false; } var result = COLOR_REGEX.test(viewValue); return result; }; } }; });
Use module constant for function timeout, increase to 900 sec (15 min)
const utils = require('./utils'); // https://docs.aws.amazon.com/lambda/latest/dg/limits.html // default function timeout in seconds const DEFAULT_TIMEOUT = 900; // 15 min /* Mimicks the lambda context object http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html */ module.exports = function createLambdaContext(fun, provider, cb) { const functionName = fun.name; const timeout = (fun.timeout || provider.timeout || DEFAULT_TIMEOUT) * 1000; const endTime = new Date().getTime() + timeout; return { /* Methods */ done: cb, succeed: res => cb(null, res, true), fail: err => cb(err, null, true), getRemainingTimeInMillis: () => endTime - new Date().getTime(), /* Properties */ functionName, memoryLimitInMB: fun.memorySize || provider.memorySize, functionVersion: `offline_functionVersion_for_${functionName}`, invokedFunctionArn: `offline_invokedFunctionArn_for_${functionName}`, awsRequestId: `offline_awsRequestId_${utils.randomId()}`, logGroupName: `offline_logGroupName_for_${functionName}`, logStreamName: `offline_logStreamName_for_${functionName}`, identity: {}, clientContext: {}, }; };
const utils = require('./utils'); /* Mimicks the lambda context object http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html */ module.exports = function createLambdaContext(fun, provider, cb) { const functionName = fun.name; const timeout = (fun.timeout || provider.timeout || 6) * 1000; // default 6 second timeout const endTime = new Date().getTime() + timeout; return { /* Methods */ done: cb, succeed: res => cb(null, res, true), fail: err => cb(err, null, true), getRemainingTimeInMillis: () => endTime - new Date().getTime(), /* Properties */ functionName, memoryLimitInMB: fun.memorySize || provider.memorySize, functionVersion: `offline_functionVersion_for_${functionName}`, invokedFunctionArn: `offline_invokedFunctionArn_for_${functionName}`, awsRequestId: `offline_awsRequestId_${utils.randomId()}`, logGroupName: `offline_logGroupName_for_${functionName}`, logStreamName: `offline_logStreamName_for_${functionName}`, identity: {}, clientContext: {}, }; };
Update test to add HTML content first
<?php namespace SendGrid\Tests; use PHPUnit\Framework\TestCase; use SendGrid\Mail\Mail; use SendGrid\Mail\Content; use SendGrid\Mail\EmailAddress; use SendGrid\Mail\From; /** * This class tests the getContents() function in SendGrid\Mail\Mail * * @package SendGrid\Tests */ class MailGetContentsTest extends TestCase { /** * This method tests that array from Mail getContents() returns with * text/plain Content object first when Mail instantiated with text/html * content before text/plain * * @return null */ public function testWillReturnPlainContentFirst() { $email = new \SendGrid\Mail\Mail(); $email->setFrom(null, "test@example.com"); $email->setSubject("Hello World from the SendGrid PHP Library"); $email->addTo("Test Person", "test@example.com"); $email->addContent("text/html", "<p>some text here</p>"); $email->addContent("text/plain", "some text here"); $this->assertEquals('text/plain', $email->getContents()[0]->getType()); } }
<?php namespace SendGrid\Tests; use PHPUnit\Framework\TestCase; use SendGrid\Mail\Mail; use SendGrid\Mail\Content; use SendGrid\Mail\EmailAddress; use SendGrid\Mail\From; /** * This class tests the getContents() function in SendGrid\Mail\Mail * * @package SendGrid\Tests */ class MailGetContentsTest extends TestCase { /** * This method tests that array from Mail getContents() returns with * text/plain Content object first when Mail instantiated with text/html * content before text/plain * * @return null */ public function testWillReturnPlainContentFirst() { $from = new From(null, "test@example.com"); $subject = "Hello World from the SendGrid PHP Library"; $to = new EmailAddress("Test Person", "test@example.com"); $plain_content = new Content("text/plain", "some text here"); $html_content = new Content("text/html", "<p>some text here</p>"); $mail = new Mail($from, [$to], $subject, $html_content, $plain_content); $this->assertEquals('text/plain', $mail->getContents()[0]->getType()); } }
Fix _get_version for tagged releases
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags") output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] return version __version__ = _get_version()
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags") output = subprocess.check_output(git_args) output = output.decode("utf-8").strip() version = output[:output.rfind("-")] return version __version__ = _get_version()
Allow static proxy URL to be configured.
from django.conf.urls.defaults import patterns, url from mezzanine.conf import settings urlpatterns = [] if "django.contrib.admin" in settings.INSTALLED_APPS: urlpatterns += patterns("django.contrib.auth.views", url("^password_reset/$", "password_reset", name="password_reset"), ("^password_reset/done/$", "password_reset_done"), ("^reset/(?P<uidb36>[-\w]+)/(?P<token>[-\w]+)/$", "password_reset_confirm"), ("^reset/done/$", "password_reset_complete"), ) _proxy_url = getattr(settings, "STATIC_PROXY_URL", "static_proxy").strip("/") urlpatterns += patterns("mezzanine.core.views", url("^edit/$", "edit", name="edit"), url("^search/$", "search", name="search"), url("^set_site/$", "set_site", name="set_site"), url("^set_device/(?P<device>.*)/$", "set_device", name="set_device"), url("^%s/$" % _proxy_url, "static_proxy", name="static_proxy"), )
from django.conf.urls.defaults import patterns, url from mezzanine.conf import settings urlpatterns = [] if "django.contrib.admin" in settings.INSTALLED_APPS: urlpatterns += patterns("django.contrib.auth.views", url("^password_reset/$", "password_reset", name="password_reset"), ("^password_reset/done/$", "password_reset_done"), ("^reset/(?P<uidb36>[-\w]+)/(?P<token>[-\w]+)/$", "password_reset_confirm"), ("^reset/done/$", "password_reset_complete"), ) urlpatterns += patterns("mezzanine.core.views", url("^edit/$", "edit", name="edit"), url("^search/$", "search", name="search"), url("^set_site/$", "set_site", name="set_site"), url("^set_device/(?P<device>.*)/$", "set_device", name="set_device"), url("^static_proxy/$", "static_proxy", name="static_proxy"), )
Remove a tmp directory unless told not to
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var path = require('path'); var fse = require('fs-extra'); var uuid = require('uuid').v1; module.exports = function(path_) { var tmpDir = path_ || path.join(__dirname, '..', 'tmp', uuid()); fse.mkdirpSync(tmpDir); if (!process.env.NO_REMOVE_TMP) { process.once('exit', function() { fse.removeSync(tmpDir); }); } return tmpDir; };
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var path = require('path'); var fse = require('fs-extra'); var uuid = require('uuid').v1; module.exports = function(path_) { var tmpDir = path_ || path.join(__dirname, '..', 'tmp', uuid()); fse.mkdirpSync(tmpDir); return tmpDir; };
config: Fix typo, cofig => config Signed-off-by: Vivek Anand <6cbec6cb1b0c30c91d3fca6c61ddeb9b64cef11c@gmail.com>
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper config file under /etc/autocloud/') config = ConfigParser.RawConfigParser() config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper cofig file under /etc/autocloud/') config = ConfigParser.RawConfigParser() config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
Change 'other' type in 'manual' type
<?php namespace APIBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use FOS\RestBundle\Controller\Annotations as Rest; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use APIBundle\Entity\Exercise; use APIBundle\Form\Type\EventType; use APIBundle\Entity\Event; class InjectTypeController extends Controller { /** * @ApiDoc( * description="List inject types" * ) * @Rest\Get("/inject_types") */ public function getInjectTypesAction(Request $request) { $url = $this->getParameter('worker_url') . '/cxf/contracts'; $contracts = json_decode(file_get_contents($url), true); $other = array(); $other['type'] = 'manual'; $other['fields'] = array(); $other['fields'][] = array( 'name' => 'content', 'type' => 'textarea', 'cardinality' => '1', 'mandatory' => true, ); $contracts[] = $other; $output = json_encode($contracts); return new Response($output); } }
<?php namespace APIBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use FOS\RestBundle\Controller\Annotations as Rest; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use APIBundle\Entity\Exercise; use APIBundle\Form\Type\EventType; use APIBundle\Entity\Event; class InjectTypeController extends Controller { /** * @ApiDoc( * description="List inject types" * ) * @Rest\Get("/inject_types") */ public function getInjectTypesAction(Request $request) { $url = $this->getParameter('worker_url') . '/cxf/contracts'; $contracts = json_decode(file_get_contents($url), true); $other = array(); $other['type'] = 'other'; $other['fields'] = array(); $other['fields'][] = array( 'name' => 'content', 'type' => 'textarea', 'cardinality' => '1', 'mandatory' => true, ); $contracts[] = $other; $output = json_encode($contracts); return new Response($output); } }
Fix bug that send 'unknown' as command name every time
import Mixpanel from 'mixpanel'; import path from 'path'; import fs from 'fs'; const mixpanel = Mixpanel.init(process.env.MIXPANEL_TOKEN); const commands = []; { const prefix = path.join(__dirname, 'commands'); fs.readdir(prefix, (err, files) => { files.forEach((file) => { const entry = require(path.join(prefix, file)); commands.push(entry); }); }); } const help = "Hi, I'm the Lexicon, here's [what I can do](http://wiki.esoui.com/Lexicon)."; export function parse(message, reply) { if (!message || !message.text) return; if (message.text.match(/^((lex(icon)?)( h[ea]lp)?|h[ea]lp)\s?$/)) return reply(help); let [ ,,text ] = message.text.match(/^lex(icon)?\s(.+)/) || []; if (!text) return; let matchCommandName = 'unknown'; commands.forEach(function(command) { if (!command.pattern) return true; const match = text.match(new RegExp('^' + command.pattern, 'i')); if (match) { matchCommandName = command.name; command.reply(message, match, reply); } }); mixpanel.track('interaction', { message: text, command: matchCommandName, author: message.fromUser.username }); }
import Mixpanel from 'mixpanel'; import path from 'path'; import fs from 'fs'; const mixpanel = Mixpanel.init(process.env.MIXPANEL_TOKEN); const commands = []; { const prefix = path.join(__dirname, 'commands'); fs.readdir(prefix, (err, files) => { files.forEach((file) => { const entry = require(path.join(prefix, file)); commands.push(entry); }); }); } const help = "Hi, I'm the Lexicon, here's [what I can do](http://wiki.esoui.com/Lexicon)."; export function parse(message, reply) { if (!message || !message.text) return; if (message.text.match(/^((lex(icon)?)( h[ea]lp)?|h[ea]lp)\s?$/)) return reply(help); let [ ,,text ] = message.text.match(/^lex(icon)?\s(.+)/) || []; if (!text) return; let matchCommandName; commands.forEach(function(command) { if (!command.pattern) return true; const match = text.match(new RegExp('^' + command.pattern, 'i')); if (match) { matchCommandName = command.name; command.reply(message, match, reply); return false; } else { matchCommandName = 'unknown'; } }); mixpanel.track('interaction', { message: text, command: matchCommandName, author: message.fromUser.username }); }
Fix broken twitter avatars (for real this time) - didn't notice avatarOptions object last time
privacyOptions = { // true means exposed _id: true, commentCount: true, createdAt: true, email_hash: true, isInvited: true, karma: true, postCount: true, slug: true, username: true, 'profile.name': true, 'profile.notifications': true, 'profile.bio': true, 'profile.github': true, 'profile.site': true, 'profile.twitter': true, 'services.twitter.profile_image_url': true, 'services.twitter.profile_image_url_https': true, 'services.facebook.id': true, 'services.twitter.screenName': true, 'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code 'votes.downvotedComments': true, 'votes.downvotedPosts': true, 'votes.upvotedComments': true, 'votes.upvotedPosts': true }; // minimum required properties to display avatars avatarOptions = { _id: true, email_hash: true, slug: true, username: true, 'profile.name': true, 'profile.github': true, 'profile.twitter': true, 'services.twitter.profile_image_url': true, 'services.twitter.profile_image_url_https': true, 'services.facebook.id': true, 'services.twitter.screenName': true, 'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code }
privacyOptions = { // true means exposed _id: true, commentCount: true, createdAt: true, email_hash: true, isInvited: true, karma: true, postCount: true, slug: true, username: true, 'profile.name': true, 'profile.notifications': true, 'profile.bio': true, 'profile.github': true, 'profile.site': true, 'profile.twitter': true, 'services.twitter.profile_image_url': true, 'services.twitter.profile_image_url_https': true, 'services.facebook.id': true, 'services.twitter.screenName': true, 'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code 'votes.downvotedComments': true, 'votes.downvotedPosts': true, 'votes.upvotedComments': true, 'votes.upvotedPosts': true }; // minimum required properties to display avatars avatarOptions = { _id: true, email_hash: true, slug: true, username: true, 'profile.name': true, 'profile.github': true, 'profile.twitter': true, 'services.twitter.profile_image_url': true, 'services.facebook.id': true, 'services.twitter.screenName': true, 'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code }
Print out the stack when an error occurs.
#!/usr/bin/env node // // Takes a text file and calls the AWS Polly API // to convert it to an audio file. // 'use strict'; const fs = require('fs-extra'); const textchunk = require('textchunk'); const { checkUsage, compressSpace, generateSpeech, getSpinner, trim } = require('./lib'); const args = require('minimist')(process.argv.slice(2)); const inputFilename = args._[0]; const outputFilename = args._[1]; const maxCharacterCount = 1500; let spinner = getSpinner(); // Check the usage. checkUsage(args); // Read in the file. spinner.begin('Reading text'); let text = fs.readFileSync(inputFilename, 'utf8'); spinner.end(); // Split the text into chunks. spinner.begin('Splitting text'); let parts = textchunk.chunk(text, maxCharacterCount); parts = parts.map(compressSpace).map(trim); // compress the white space spinner.end(); // Generate the audio file. generateSpeech(parts, args).then(tempFile => { fs.move(tempFile, outputFilename, { overwrite: true }, () => { spinner.succeed(`Done. Saved to ${outputFilename}`); }); }).catch(err => { process.stderr.write(err.stack); });
#!/usr/bin/env node // // Takes a text file and calls the AWS Polly API // to convert it to an audio file. // 'use strict'; const fs = require('fs-extra'); const textchunk = require('textchunk'); const { checkUsage, compressSpace, generateSpeech, getSpinner, trim } = require('./lib'); const args = require('minimist')(process.argv.slice(2)); const inputFilename = args._[0]; const outputFilename = args._[1]; const maxCharacterCount = 1500; let spinner = getSpinner(); // Check the usage. checkUsage(args); // Read in the file. spinner.begin('Reading text'); let text = fs.readFileSync(inputFilename, 'utf8'); spinner.end(); // Split the text into chunks. spinner.begin('Splitting text'); let parts = textchunk.chunk(text, maxCharacterCount); parts = parts.map(compressSpace).map(trim); // compress the white space spinner.end(); // Generate the audio file. generateSpeech(parts, args).then(tempFile => { fs.move(tempFile, outputFilename, { overwrite: true }, () => { spinner.succeed(`Done. Saved to ${outputFilename}`); }); });
Test child process command logging
var fs = require('fs'); var exec = require('child_process').exec; function Err(msg, err){ var err_str = 'build error\n' + (msg ? msg + '\n' : '') + (err ? err.message + '\n' : ''); throw new Error(err_str); } function build(dir){ var commands = 'cd ' + dir + ' && npm install && node-gyp configure && node-gyp build'; console.log(commands); exec(commands, function (err, stdout, stderr) { if(err) console.log('--- exec error ---\n' + err + '--- end exec error ---'); console.log('--- stdout ---\n' + stdout + '--- end stdout ---'); console.log('--- stderr ---\n' + stderr + '--- end stderr ---'); }); } var lib_dir = __dirname + '/lib'; fs.readdir(lib_dir, function (err, dirs){ if(err) return Err('Could not read ' + lib_dir, err); dirs.forEach(function (dir){ var module_dir = lib_dir + '/' + dir fs.readdir(module_dir, function (err, dirs){ if(err) return Err('Could not read ', err); dirs.forEach(function (dir){ if(dir == 'cpp') build(module_dir + '/' + dir); }); }); }); });
var fs = require('fs'); var exec = require('child_process').exec; function Err(msg, err){ var err_str = 'build error\n' + (msg ? msg + '\n' : '') + (err ? err.message + '\n' : ''); throw new Error(err_str); } function build(dir){ var commands = 'cd ' + dir + ' && npm install && node-gyp configure && node-gyp build'; exec(commands, function (err, stdout, stderr) { if(err) console.log('--- exec error ---\n' + err + '--- end exec error ---'); console.log('--- stdout ---\n' + stdout + '--- end stdout ---'); console.log('--- stderr ---\n' + stderr + '--- end stderr ---'); }); } var lib_dir = __dirname + '/lib'; fs.readdir(lib_dir, function (err, dirs){ if(err) return Err('Could not read ' + lib_dir, err); dirs.forEach(function (dir){ var module_dir = lib_dir + '/' + dir fs.readdir(module_dir, function (err, dirs){ if(err) return Err('Could not read ', err); dirs.forEach(function (dir){ if(dir == 'cpp') build(module_dir + '/' + dir); }); }); }); });
Use path module for getting static file serve path
var express = require('express'); var app = express(); var server = require('http').createServer(app); var sockets = require('socket.io')(server); var hash = require('crypto').createHash; var path = require('path'); var buildGroups = require('./groups'); var dataProvider; var subdomain; app.use(express.static(path.join(__dirname, '..', 'public_html'))); module.exports = function(provider, domain, port) { dataProvider = provider; //could be the API or the mock data subdomain = domain; server.listen(port, function() { console.log('Server listening at port %d', port); }); return { updateStatus: updateStatus }; }; function updateStatus() { get('services', function(services) { sendUpdate(buildGroups(services)); }); } function get(resource, callback, params) { dataProvider.getAll(resource, function(error, data) { if (error) { return sendError(error); } callback(data); }, params); } function sendUpdate(data) { console.log(new Date() + ': Sending update.'); sockets.emit('update', { groups: data, subdomain: subdomain, hash: hash('sha256').update(JSON.stringify(data)).digest('hex') }); } function sendError(error) { console.log(new Date() + ': ' + error.message); sockets.emit('error', error.message); }
var express = require('express'); var app = express(); var server = require('http').createServer(app); var sockets = require('socket.io')(server); var hash = require('crypto').createHash; var buildGroups = require('./groups'); var dataProvider; var subdomain; app.use(express.static(__dirname + '/../public_html')); module.exports = function(provider, domain, port) { dataProvider = provider; //could be the API or the mock data subdomain = domain; server.listen(port, function() { console.log('Server listening at port %d', port); }); return { updateStatus: updateStatus }; }; function updateStatus() { get('services', function(services) { sendUpdate(buildGroups(services)); }); } function get(resource, callback, params) { dataProvider.getAll(resource, function(error, data) { if (error) { return sendError(error); } callback(data); }, params); } function sendUpdate(data) { console.log(new Date() + ': Sending update.'); sockets.emit('update', { groups: data, subdomain: subdomain, hash: hash('sha256').update(JSON.stringify(data)).digest('hex') }); } function sendError(error) { console.log(new Date() + ': ' + error.message); sockets.emit('error', error.message); }
Fix problem of note replacement
import { asImmutable } from '../../../helper/immutableHelper'; import * as actions from './actions'; const initialState = asImmutable({}); export const reducer = (state = initialState, { type, payload }) => { switch (type) { case actions.FETCH_USER.SUCCEEDED: return state.merge(payload.data || {}); case actions.FETCH_USER_NOTES.SUCCEEDED: return state.merge({ notes: payload.data || [] }); case actions.STORE_USER_NOTE.SUCCEEDED: return state.set('notes', state.get('notes').push(asImmutable(payload.data))); case actions.FETCH_REPOSITORIES.SUCCEEDED: return state.merge({ repositories: payload.data || [] }); default: return state; } }; export default reducer;
import { asImmutable } from '../../../helper/immutableHelper'; import * as actions from './actions'; const initialState = asImmutable({}); export const reducer = (state = initialState, { type, payload }) => { switch (type) { case actions.FETCH_USER.SUCCEEDED: return state.merge(payload.data || {}); case actions.FETCH_USER_NOTES.SUCCEEDED: return state.merge({ notes: payload.data || [] }); case actions.STORE_USER_NOTE.SUCCEEDED: return state.mergeIn(['notes'], [payload.data]); case actions.FETCH_REPOSITORIES.SUCCEEDED: return state.merge({ repositories: payload.data || [] }); default: return state; } }; export default reducer;
Update expected number of nodes
var acorn = require("acorn"), assert = require("assert"), idast = require("./idast"), walk = require("acorn/util/walk"); var mkAST = function() { return acorn.parse("(function(a) { var q = (a ? 3 : 'h').length*7; var o = {a: 9}; o.q = o['w'] = 2; return o; })(true);"); }; describe("assignIds", function() { it("assigns IDs to AST nodes", function() { var ast = mkAST(); idast.assignIds(ast, "test"); var ids = []; walk.simple(ast, { Node: function(node, st, c) { ids.push(node._id); }, }, idast.base); assert(ids.indexOf("test/Program/body/0/ExpressionStatement/expression/CallExpression/arguments/0") !== -1); assert.equal("test/Program", ids[0]); assert.equal(33, ids.length); }); }); describe("visitor", function() { it("passes AST node IDs to visitor", function() { var ids = []; walk.simple(mkAST(), { Node: function(node, st, c) { ids.push(st); }, }, idast.base, ""); assert(ids.indexOf("/Program/body/0/ExpressionStatement/expression/CallExpression/arguments/0") !== -1); assert.equal("/Program", ids[0]); assert.equal(33, ids.length); }); });
var acorn = require("acorn"), assert = require("assert"), idast = require("./idast"), walk = require("acorn/util/walk"); var mkAST = function() { return acorn.parse("(function(a) { var q = (a ? 3 : 'h').length*7; var o = {a: 9}; o.q = o['w'] = 2; return o; })(true);"); }; describe("assignIds", function() { it("assigns IDs to AST nodes", function() { var ast = mkAST(); idast.assignIds(ast, "test"); var ids = []; walk.simple(ast, { Node: function(node, st, c) { ids.push(node._id); }, }, idast.base); assert(ids.indexOf("test/Program/body/0/ExpressionStatement/expression/CallExpression/arguments/0") !== -1); assert.equal("test/Program", ids[0]); assert.equal(31, ids.length); }); }); describe("visitor", function() { it("passes AST node IDs to visitor", function() { var ids = []; walk.simple(mkAST(), { Node: function(node, st, c) { ids.push(st); }, }, idast.base, ""); assert(ids.indexOf("/Program/body/0/ExpressionStatement/expression/CallExpression/arguments/0") !== -1); assert.equal("/Program", ids[0]); assert.equal(31, ids.length); }); });
Make all data records store record id keys as strings
class DataRecord: @classmethod def get_store( cls ): if hasattr( cls, 'store' ): return cls.store cls.store = {} return cls.store @classmethod def find( cls, record_id ): return cls.get_store().get( str(record_id), None ) @classmethod def save( cls, record_id, record ): cls.get_store()[ str(record_id) ] = record @classmethod def create_or_update( cls, record_id, **kwargs ): found_record = cls.find( str(record_id) ) if found_record is not None: for name, value in kwargs.items(): setattr( found_record, name, value ) return found_record return cls( str(record_id), **kwargs ) def __init__( self, record_id ): self.record_id = str(record_id) self.__class__.save( str(record_id), self )
class DataRecord: @classmethod def get_store( cls ): if hasattr( cls, 'store' ): return cls.store cls.store = {} return cls.store @classmethod def find( cls, record_id ): return cls.get_store().get( record_id, None ) @classmethod def save( cls, record_id, record ): cls.get_store()[ record_id ] = record @classmethod def create_or_update( cls, record_id, **kwargs ): found_record = cls.find( record_id ) if found_record is not None: for name, value in kwargs.items(): setattr( found_record, name, value ) return found_record return cls( record_id, **kwargs ) def __init__( self, record_id ): self.record_id = record_id self.__class__.save( record_id, self )
Update dependencies to actual version numbers
from distutils.core import setup setup( name='HotCIDR', version='0.1.0', author='ViaSat', author_email='stephan.kemper@viasat.com', packages=['hotcidr', 'hotcidr.test'], scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'], #url='http://pypi.python.org/pypi/HotCIDR', license='LICENSE.txt', description="Firewall rule management and automation tools", #long_description=open('README.txt').read(), install_requires=[ "GitPython >= 0.3.2.RC1", "MySQL-python >= 1.2.5", "PyYAML >= 3.10", "boto >= 2.28.0", "inflect >= 0.2.4", "netaddr >= 0.7.11", "requests >= 0.14.0", "toposort >= 1.0", ], )
from distutils.core import setup setup( name='HotCIDR', version='0.1.0', author='ViaSat', author_email='stephan.kemper@viasat.com', packages=['hotcidr', 'hotcidr.test'], scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'], #url='http://pypi.python.org/pypi/HotCIDR', license='LICENSE.txt', description="Firewall rule management and automation tools", #long_description=open('README.txt').read(), install_requires=[ "GitPython >= 0.3.2", "MySQL-python >= 1.2.5", "PyYAML >= 3.10", "boto >= 2.31.1", "inflect >= 0.2.4", "netaddr >= 0.7.12", "requests >= 0.14.0", "toposort >= 1.1", ], )
Handle unknown events in LoggerListner.
<?php /* * This file is part of the Pomm's Foundation package. * * (c) 2014 Grégoire HUBERT <hubert.greg@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PommProject\Foundation; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; class LoggerListener implements LoggerAwareInterface, ListenerInterface { use LoggerAwareTrait; public function notify($event, array $data) { if ($event === 'pre') { $message = $data['sql']; $context = $data['parameters']; } else if ($event === 'post') { $message = "Query ok."; $context = $data; } else { throw new FoundationException( sprintf( "Do not know what to log for event '%s' (data {%s}).", $event, join(', ', array_map(function($val) { return sprintf("'%s'", $val); })) ) ); } $this->logger->info($message, $context); } }
<?php /* * This file is part of the Pomm's Foundation package. * * (c) 2014 Grégoire HUBERT <hubert.greg@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PommProject\Foundation; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; class LoggerListener implements LoggerAwareInterface, ListenerInterface { use LoggerAwareTrait; public function notify($event, $data) { if ($event === 'pre') { $message = $data['sql']; $context = $data['parameters']; } else if ($event === 'post') { $message = "Query ok."; $context = $data; } $this->logger->info($message, $context); } }
Fix Java chart app detection logic
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, shouldBeInstalled = !isJavaInstalled && !isMobile; $('#install-java').toggle(shouldBeInstalled); $('#download-app').toggle(isJavaInstalled); $('#install-java').on('click', function () { deployJava.installLatestJava(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, canBeInstalled = isJavaInstalled && !isMobile; $('#install-java').toggle(!isJavaInstalled); $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { deployJava.installLatestJava(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
Remove stray comma from brunch config
// Brunch configuration // See http://brunch.io for documentation. 'use strict'; module.exports = { files: { javascripts: { joinTo: { 'scripts/main.js': ['app/scripts/**/*.js', /^node_modules/] } }, stylesheets: { joinTo: { 'styles/main.css': ['app/styles/main.scss'] } } }, modules: { autoRequire: { 'scripts/main.js': ['scripts/main'] } }, paths: { // Exclude test files from compilation watched: ['app'] }, plugins: { postcss: { processors: [ require('autoprefixer')({ browsers: ['> 0.1%'] }) ] } } };
// Brunch configuration // See http://brunch.io for documentation. 'use strict'; module.exports = { files: { javascripts: { joinTo: { 'scripts/main.js': ['app/scripts/**/*.js', /^node_modules/] } }, stylesheets: { joinTo: { 'styles/main.css': ['app/styles/main.scss'] } } }, modules: { autoRequire: { 'scripts/main.js': ['scripts/main'] } }, paths: { // Exclude test files from compilation watched: ['app'] }, plugins: { postcss: { processors: [ require('autoprefixer')({ browsers: ['> 0.1%'] }) ] } }, };
Fix tests to work when GOOGLE_ANALYTICS_KEY is not set.
import unittest import mock import django.conf class TestRecaptchaTags(unittest.TestCase): def test_recaptcha_html(self): from fixcity.bmabr.templatetags import recaptcha_tags from django.conf import settings html = recaptcha_tags.recaptcha_html() self.failUnless(settings.RECAPTCHA_PUBLIC_KEY in html) self.failUnless(html.startswith('<script')) class TestGoogleTags(unittest.TestCase): @mock.patch_object(django.conf, 'settings') def test_google_analytics(self, mock_settings): from fixcity.bmabr.templatetags import google_analytics mock_settings.GOOGLE_ANALYTICS_KEY = 'xyzpdq' html = google_analytics.google_analytics() self.failUnless('xyzpdq' in html) self.failUnless(html.startswith('<script')) # For some reason this doesn't work if I put it in a separate # test case... the google_analytics() function keeps a # reference to the OLD mock_settings instance with the # 'xyzpdq' value! mock_settings.GOOGLE_ANALYTICS_KEY = '' html = google_analytics.google_analytics() self.assertEqual(html, '')
import unittest class TestRecaptchaTags(unittest.TestCase): def test_recaptcha_html(self): from fixcity.bmabr.templatetags import recaptcha_tags from django.conf import settings html = recaptcha_tags.recaptcha_html() self.failUnless(settings.RECAPTCHA_PUBLIC_KEY in html) self.failUnless(html.startswith('<script')) class TestGoogleTags(unittest.TestCase): def test_google_analytics(self): from fixcity.bmabr.templatetags import google_analytics from django.conf import settings html = google_analytics.google_analytics() self.failUnless(settings.GOOGLE_ANALYTICS_KEY in html) self.failUnless(html.startswith('<script'))
Remove whitespace around brackets in example code
#!/usr/bin/env python """Generate fixtures.""" import os import json import numpy as np from scipy import special # Get the file path: FILE = os.path.realpath(__file__) # Extract the directory in which this file resides: DIR = os.path.dirname(FILE) def gen(x, name): """Generates fixture data and writes them to file. # Arguments * `x`: domain * `name::str`: output filename # Examples ``` python python> x = linspace(-1000, 1000, 2001); python> gen(x, \"./data.json\"); ``` """ y = special.logit(x) # Store data to be written to file as a dictionary: data = { "x": x.tolist(), "expected": y.tolist() } # Based on the script directory, create an output filepath: filepath = os.path.join(DIR, name) with open(filepath, 'w') as outfile: json.dump(data, outfile) def main(): """Generate fixture data.""" x = np.linspace(0.0001, 0.25, 500) gen(x, "small.json") x = np.linspace(0.25, 0.75, 500) gen(x, "medium.json") x = np.linspace(0.75, 0.9999, 500) gen(x, "large.json") if __name__ == "__main__": main()
#!/usr/bin/env python """Generate fixtures.""" import os import json import numpy as np from scipy import special # Get the file path: FILE = os.path.realpath(__file__) # Extract the directory in which this file resides: DIR = os.path.dirname(FILE) def gen(x, name): """Generates fixture data and writes them to file. # Arguments * `x`: domain * `name::str`: output filename # Examples ``` python python> x = linspace( -1000, 1000, 2001 ); python> gen( x, \"./data.json\" ); ``` """ y = special.logit(x) # Store data to be written to file as a dictionary: data = { "x": x.tolist(), "expected": y.tolist() } # Based on the script directory, create an output filepath: filepath = os.path.join(DIR, name) with open(filepath, 'w') as outfile: json.dump(data, outfile) def main(): """Generate fixture data.""" x = np.linspace(0.0001, 0.25, 500) gen(x, "small.json") x = np.linspace(0.25, 0.75, 500) gen(x, "medium.json") x = np.linspace(0.75, 0.9999, 500) gen(x, "large.json") if __name__ == "__main__": main()
Make the format match the current locale
function initDatePicker(container, elem, pickerOptions) { $(container + ' ' + elem).fdatepicker(pickerOptions); $(container + ' ' + elem + ' i').on('click', function() { $(this).closest(elem + 'wrapper') .find(elem) .fdatepicker('show'); }); } function initDatepickersIn(container) { initDatePicker(container, '.datepicker', {format: "dd-mm-yyyy"}); } function initDateTimepickersIn(container) { initDatePicker(container, '.datetimepicker', {format: "dd-mm-yyyy hh:ii", pickTime: true}); } $(function() { if ($('small.error').length > 0) { $('html, body').animate({ scrollTop: ($('small.error').first().offset().top-100) },500); } initDatepickersIn("body"); initDateTimepickersIn("body"); });
function initDatePicker(container, elem, pickerOptions) { $(container + ' ' + elem).fdatepicker(pickerOptions); $(container + ' ' + elem + ' i').on('click', function() { $(this).closest(elem + 'wrapper') .find(elem) .fdatepicker('show'); }); } function initDatepickersIn(container) { initDatePicker(container, '.datepicker', {format: "dd-mm-yy"}); } function initDateTimepickersIn(container) { initDatePicker(container, '.datetimepicker', {format: "dd-mm-yy hh:ii", pickTime: true}); } $(function() { if ($('small.error').length > 0) { $('html, body').animate({ scrollTop: ($('small.error').first().offset().top-100) },500); } initDatepickersIn("body"); initDateTimepickersIn("body"); });
Update GitHub repos from blancltd to developersociety
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='django-latest-tweets', version='0.4.5', description='Latest Tweets for Django', long_description=readme, url='https://github.com/developersociety/django-latest-tweets', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'twitter>=1.9.1', 'requests>=2.0', ], packages=find_packages(), include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='django-latest-tweets', version='0.4.5', description='Latest Tweets for Django', long_description=readme, url='https://github.com/blancltd/django-latest-tweets', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'twitter>=1.9.1', 'requests>=2.0', ], packages=find_packages(), include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
Update the sample proxy list
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Use Blacklight.onLoad to support turbolinks.
Blacklight.onLoad(function(){ Blacklight.do_hierarchical_facet_expand_contract_behavior(); }); (function($) { Blacklight.do_hierarchical_facet_expand_contract_behavior = function() { $( Blacklight.do_hierarchical_facet_expand_contract_behavior.selector ).each ( Blacklight.hierarchical_facet_expand_contract ); } Blacklight.do_hierarchical_facet_expand_contract_behavior.selector = 'li.h-node'; Blacklight.hierarchical_facet_expand_contract = function() { var li = $(this); $('ul', this).each(function() { li.addClass('twiddle'); if($('span.selected', this).length == 0){ $(this).hide(); } else { li.addClass('twiddle-open'); } }); // attach the toggle behavior to the li tag li.click(function(e){ if (e.target == this) { // toggle the content $(this).toggleClass('twiddle-open'); $(this).children('ul').slideToggle(); } }); }; })(jQuery);
$(document).ready(function() { Blacklight.do_hierarchical_facet_expand_contract_behavior(); }); (function($) { Blacklight.do_hierarchical_facet_expand_contract_behavior = function() { $( Blacklight.do_hierarchical_facet_expand_contract_behavior.selector ).each ( Blacklight.hierarchical_facet_expand_contract ); } Blacklight.do_hierarchical_facet_expand_contract_behavior.selector = 'li.h-node'; Blacklight.hierarchical_facet_expand_contract = function() { var li = $(this); $('ul', this).each(function() { li.addClass('twiddle'); if($('span.selected', this).length == 0){ $(this).hide(); } else { li.addClass('twiddle-open'); } }); // attach the toggle behavior to the li tag li.click(function(e){ if (e.target == this) { // toggle the content $(this).toggleClass('twiddle-open'); $(this).children('ul').slideToggle(); } }); }; })(jQuery);
Rename the name of topo.
''' SDN project testing topo s1 / \ s2--s3 | | host.. host... ''' from mininet.topo import Topo class LoopTopo( Topo ): def __init__( self , n=2 ): # Initialize topology Topo.__init__( self) # Add Host h1 = self.addHost( 'h1' ) h2 = self.addHost( 'h2' ) h3 = self.addHost( 'h3' ) h4 = self.addHost( 'h4' ) h5 = self.addHost( 'h5' ) h6 = self.addHost( 'h6' ) # Add Switch s1 = self.addSwitch( 's1' ) s2 = self.addSwitch( 's2' ) s3 = self.addSwitch( 's3' ) # Add Link self.addLink( s1, s2 ) self.addLink( s1, s3 ) self.addLink( s2, s3 ) self.addLink( s2, h1 ) self.addLink( s2, h2 ) self.addLink( s2, h3 ) self.addLink( s3, h4 ) self.addLink( s3, h5 ) self.addLink( s3, h6 ) topos = { 'Loop': ( lambda: LoopTopo() ) }
''' SDN project testing topo s1 / \ s2--s3 | | host.. host... ''' from mininet.topo import Topo class LoopTopo( Topo ): def __init__( self , n=2 ): # Initialize topology Topo.__init__( self) # Add Host h1 = self.addHost( 'h1' ) h2 = self.addHost( 'h2' ) h3 = self.addHost( 'h3' ) h4 = self.addHost( 'h4' ) h5 = self.addHost( 'h5' ) h6 = self.addHost( 'h6' ) # Add Switch s1 = self.addSwitch( 's1' ) s2 = self.addSwitch( 's2' ) s3 = self.addSwitch( 's3' ) # Add Link self.addLink( s1, s2 ) self.addLink( s1, s3 ) self.addLink( s2, s3 ) self.addLink( s2, h1 ) self.addLink( s2, h2 ) self.addLink( s2, h3 ) self.addLink( s3, h4 ) self.addLink( s3, h5 ) self.addLink( s3, h6 ) topos = { 'LoopTopo': ( lambda: LoopTopo() ) }
Update light component to use changing opacity instead of changing color
import React from 'react'; import Radium from 'radium'; import { lightActive, lightInactive } from 'theme/variables'; const size = 18; const innerPadding = 4; @Radium class Light extends React.Component { render() { const { active } = this.props; const baseInnerStyle = { position: 'absolute', left: innerPadding, right: innerPadding, top: innerPadding, bottom: innerPadding, borderRadius: '50%', }; const styles = { outer: { position: 'relative', backgroundColor: 'rgba(0,0,0,0.4)', width: size, height: size, borderRadius: '50%' }, innerInactive: { ...baseInnerStyle, backgroundColor: lightInactive }, innerActive: { ...baseInnerStyle, backgroundColor: lightActive, opacity: active ? 1 : 0 } }; return ( <div style={styles.outer}> <div style={styles.innerInactive}></div> <div style={styles.innerActive}></div> </div> ); } } Light.propTypes = { active: React.PropTypes.bool.isRequired }; export default Light;
import React from 'react'; import Radium from 'radium'; import { lightActive, lightInactive } from 'theme/variables'; const size = 18; const innerPadding = 4; @Radium class Light extends React.Component { render() { const { active } = this.props; const styles = { outer: { position: 'relative', backgroundColor: 'rgba(0,0,0,0.4)', width: size, height: size, borderRadius: '50%' }, inner: { position: 'absolute', left: innerPadding, right: innerPadding, top: innerPadding, bottom: innerPadding, borderRadius: '50%', backgroundColor: active ? lightActive : lightInactive } }; return ( <div style={styles.outer}> <div style={styles.inner}></div> </div> ); } } Light.propTypes = { active: React.PropTypes.bool.isRequired }; export default Light;
Fix a crash with statements without speakers
import { List } from 'immutable' import createCachedSelector from 're-reselect' const EMPTY_COMMENTS_LIST = new List() export const getAllComments = (state) => state.VideoDebate.comments.comments export const getStatementAllComments = (state, props) => getAllComments(state).get(props.statement.id, EMPTY_COMMENTS_LIST) export const classifyComments = createCachedSelector( getStatementAllComments, (state, props) => props.statement.speaker_id, (comments, speakerId) => { const selfComments = [] const approvingFacts = [] const refutingFacts = [] const regularComments = [] for (const comment of comments) { if (comment.user.speaker_id && comment.user.speaker_id === speakerId) selfComments.push(comment) else if (!comment.source || comment.approve === null) regularComments.push(comment) else if (comment.approve) approvingFacts.push(comment) else refutingFacts.push(comment) } return { regularComments: new List(regularComments), selfComments: new List(selfComments), approvingFacts: new List(approvingFacts), refutingFacts: new List(refutingFacts), } } )((state, props) => props.statement.id)
import { List } from 'immutable' import createCachedSelector from 're-reselect' const EMPTY_COMMENTS_LIST = new List() export const getAllComments = (state) => state.VideoDebate.comments.comments export const getStatementAllComments = (state, props) => getAllComments(state).get(props.statement.id, EMPTY_COMMENTS_LIST) export const classifyComments = createCachedSelector( getStatementAllComments, (state, props) => props.statement.speaker_id, (comments, speakerId) => { const selfComments = [] const approvingFacts = [] const refutingFacts = [] const regularComments = [] for (const comment of comments) { if (comment.user.speaker_id === speakerId) selfComments.push(comment) else if (!comment.source || comment.approve === null) regularComments.push(comment) else if (comment.approve) approvingFacts.push(comment) else refutingFacts.push(comment) } return { regularComments: new List(regularComments), selfComments: new List(selfComments), approvingFacts: new List(approvingFacts), refutingFacts: new List(refutingFacts), } } )((state, props) => props.statement.id)
Add comment about binary res.json()
const jsonMask = require('json-mask') module.exports = function (opt) { opt = opt || {} function partialResponse(obj, fields) { if (!fields) return obj return jsonMask(obj, fields) } function wrap(orig) { return function (obj) { const param = this.req.query[opt.query || 'fields'] if (1 === arguments.length) { orig(partialResponse(obj, param)) } else if (2 === arguments.length) { if ('number' === typeof arguments[1]) { // res.json(body, status) backwards compat orig(arguments[1], partialResponse(obj, param)) } else { // res.json(status, body) backwards compat orig(obj, partialResponse(arguments[1], param)) } } } } return function (req, res, next) { if (!res.__isJSONMaskWrapped) { res.json = wrap(res.json.bind(res)) if (req.jsonp) res.jsonp = wrap(res.jsonp.bind(res)) res.__isJSONMaskWrapped = true } next() } }
const jsonMask = require('json-mask') module.exports = function (opt) { opt = opt || {} function partialResponse(obj, fields) { if (!fields) return obj return jsonMask(obj, fields) } function wrap(orig) { return function (obj) { const param = this.req.query[opt.query || 'fields'] if (1 === arguments.length) { orig(partialResponse(obj, param)) } else if (2 === arguments.length) { if ('number' === typeof arguments[1]) { orig(arguments[1], partialResponse(obj, param)) } else { orig(obj, partialResponse(arguments[1], param)) } } } } return function (req, res, next) { if (!res.__isJSONMaskWrapped) { res.json = wrap(res.json.bind(res)) if (req.jsonp) res.jsonp = wrap(res.jsonp.bind(res)) res.__isJSONMaskWrapped = true } next() } }
Use string substitution in console.log().
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), year = new Date().getFullYear(), preamble = '/*!\n' + ' * ' + pkg.name + ' ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-' + (year === 2015 ? 'present' : year) + ' ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * ' + pkg.name + ' may be freely distributed under the MIT license.\n' + ' */\n'; exec('uglifyjs src/aria-collapsible.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/aria-collapsible.js'); exec('uglifyjs src/aria-collapsible.js --compress --mangle --preamble "' + preamble + '" --output dist/aria-collapsible.min.js'); console.log(colors.green('aria-collapsible %s built successfully!'), pkg.version);
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), year = new Date().getFullYear(), preamble = '/*!\n' + ' * ' + pkg.name + ' ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-' + (year === 2015 ? 'present' : year) + ' ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * ' + pkg.name + ' may be freely distributed under the MIT license.\n' + ' */\n'; exec('uglifyjs src/aria-collapsible.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/aria-collapsible.js'); exec('uglifyjs src/aria-collapsible.js --compress --mangle --preamble "' + preamble + '" --output dist/aria-collapsible.min.js'); console.log(('aria-collapsible ' + pkg.version + ' built successfully!').green);
Remove not needed request argument in view decorator. Patch by: Pawel Solyga Review by: to-be-reviewed --HG-- extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # 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. """Views decorators. """ __authors__ = [ '"Pawel Solyga" <pawel.solyga@gmail.com>', ] import logging from functools import wraps from google.appengine.runtime import DeadlineExceededError from django import http def view(func): """Decorator that insists that exceptions are handled by view.""" @wraps(func) def view_wrapper(*args, **kwds): try: return func(*args, **kwds) except DeadlineExceededError: logging.exception('DeadlineExceededError') return http.HttpResponse('DeadlineExceededError') except MemoryError: logging.exception('MemoryError') return http.HttpResponse('MemoryError') except AssertionError: logging.exception('AssertionError') return http.HttpResponse('AssertionError') return view_wrapper
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # 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. """Views decorators. """ __authors__ = [ '"Pawel Solyga" <pawel.solyga@gmail.com>', ] import logging from functools import wraps from google.appengine.runtime import DeadlineExceededError from django import http def view(func): """Decorator that insists that exceptions are handled by view.""" @wraps(func) def view_wrapper(request, *args, **kwds): try: return func(request, *args, **kwds) except DeadlineExceededError: logging.exception('DeadlineExceededError') return http.HttpResponse('DeadlineExceededError') except MemoryError: logging.exception('MemoryError') return http.HttpResponse('MemoryError') except AssertionError: logging.exception('AssertionError') return http.HttpResponse('AssertionError') return view_wrapper
Add port on flask app
from flask import Flask, render_template, request from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from scipy import misc import numpy as np from VGG16_gs_model import * # sett opp nevralt nettverk: model = VGG_16() fpath = '../models/vgg16_sg.h5'; model.load_weights(fpath) # Sett opp webapp app = Flask(__name__) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'img' configure_uploads(app, photos) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) # Hent ut prediksjon img = misc.imread('./img/' + filename) img = misc.imresize(img, (224, 224)) img = img.transpose() img = np.expand_dims(img, axis=0).astype(np.uint8) preds, idxs, classes = predict(model, img) return 'You are a ' + str(classes[0]) + ' with a confidence of ' + str(preds[0]) return render_template('upload.html') @app.route("/") def hello(): return "Hello Nabla and Timini!" if __name__ == "__main__": app.run(host = '0.0.0.0', port=5000)
from flask import Flask, render_template, request from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from scipy import misc import numpy as np from VGG16_gs_model import * # sett opp nevralt nettverk: model = VGG_16() fpath = '../models/vgg16_sg.h5'; model.load_weights(fpath) # Sett opp webapp app = Flask(__name__) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'img' configure_uploads(app, photos) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) # Hent ut prediksjon img = misc.imread('./img/' + filename) img = misc.imresize(img, (224, 224)) img = img.transpose() img = np.expand_dims(img, axis=0).astype(np.uint8) preds, idxs, classes = predict(model, img) return 'You are a ' + str(classes[0]) + ' with a confidence of ' + str(preds[0]) return render_template('upload.html') @app.route("/") def hello(): return "Hello Nabla and Timini!" if __name__ == "__main__": app.run(host = '0.0.0.0' )
Set Serpent connector to force_harvest when connector is done. git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1727 baf6b65b-9124-4dc3-b1c0-01155b4af546
<?php /* connector for SERPENT estimated execution time: 23 mins. Connector screen scrapes the partner website. */ include_once(dirname(__FILE__) . "/../../config/environment.php"); $timestart = time_elapsed(); require_library('connectors/SerpentAPI'); $GLOBALS['ENV_DEBUG'] = false; $taxa = SerpentAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_id = 170; $resource_path = CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml"; $OUT = fopen($resource_path, "w+"); fwrite($OUT, $xml); fclose($OUT); // set SERPENT to force harvest if(filesize(CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml")) { $GLOBALS['db_connection']->update("UPDATE resources SET resource_status_id=" . ResourceStatus::insert('Force Harvest') . " WHERE id=" . $resource_id); } $elapsed_time_sec = time_elapsed() - $timestart; echo "\n"; echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hours \n"; exit("\n\n Done processing."); ?>
<?php /* connector for Serpent estimated execution time: 23 mins. Connector screen scrapes the partner website. */ $timestart = microtime(1); include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/SerpentAPI'); $GLOBALS['ENV_DEBUG'] = false; $taxa = SerpentAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . "170.xml"; $OUT = fopen($resource_path, "w+"); fwrite($OUT, $xml); fclose($OUT); $elapsed_time_sec = microtime(1)-$timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec sec \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " min \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n"; exit("\n\n Done processing."); ?>
Allow for user-specified newline breaks in values
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
Move build-constraints near the top.
// Copyright 2014 The Prometheus Authors // 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. // Build only when actually fuzzing // +build gofuzz package text import "bytes" // Fuzz text metric parser with with github.com/dvyukov/go-fuzz: // // go-fuzz-build github.com/prometheus/client_golang/text // go-fuzz -bin text-fuzz.zip -workdir fuzz // // Further input samples should go in the folder fuzz/corpus. func Fuzz(in []byte) int { parser := Parser{} _, err := parser.TextToMetricFamilies(bytes.NewReader(in)) if err != nil { return 0 } return 1 }
// Copyright 2014 The Prometheus Authors // 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 text import "bytes" // Build only when actually fuzzing // +build gofuzz // Fuzz text metric parser with with github.com/dvyukov/go-fuzz: // // go-fuzz-build github.com/prometheus/client_golang/text // go-fuzz -bin text-fuzz.zip -workdir fuzz // // Further input samples should go in the folder fuzz/corpus. func Fuzz(in []byte) int { parser := Parser{} _, err := parser.TextToMetricFamilies(bytes.NewReader(in)) if err != nil { return 0 } return 1 }
Fix return value for bundle method
var styledeps = require('style-deps') var resolve = require('style-resolve') var xtend = require('xtend') module.exports = Sheetify // for now, stylify has no "core" // modules. var core = {} function Sheetify(entry) { if (!(this instanceof Sheetify)) return new Sheetify(entry) if (Array.isArray(entry) && entry.length > 1) throw new Error( 'Support for more than one entry css file ' + 'is not currently available.' ) this.transforms = [] this.entry = Array.isArray(entry) ? entry[0] : entry } Sheetify.prototype.transform = function(transform) { this.transforms.push(transform) return this } Sheetify.prototype.bundle = function(opts, done) { if (typeof opts === 'function') { done = opts opts = {} } return styledeps(this.entry, xtend(opts || {}, { transforms: this.transforms , modifiers: this.modifiers }), done) }
var styledeps = require('style-deps') var resolve = require('style-resolve') var xtend = require('xtend') module.exports = Sheetify // for now, stylify has no "core" // modules. var core = {} function Sheetify(entry) { if (!(this instanceof Sheetify)) return new Sheetify(entry) if (Array.isArray(entry) && entry.length > 1) throw new Error( 'Support for more than one entry css file ' + 'is not currently available.' ) this.transforms = [] this.entry = Array.isArray(entry) ? entry[0] : entry } Sheetify.prototype.transform = function(transform) { this.transforms.push(transform) return this } Sheetify.prototype.bundle = function(opts, done) { if (typeof opts === 'function') { done = opts opts = {} } styledeps(this.entry, xtend(opts || {}, { transforms: this.transforms , modifiers: this.modifiers }), done) }
Update endpoint that is targeted
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function () { request //.get('/glimpse/api/messages') //.query({ latest: true }) .get('/Glimpse/Data/History') //TODO: this will probably change in time to the above .set('Accept', 'application/json') .end(function(err, res){ if (err.status == 200) { glimpse.emit('data.message.summary.found.remote', []); } }); }, triggerGetDetailsFor: function (requestId) { request .get('/glimpse/api/messages') .query({ context: requestId }) .set('Accept', 'application/json') .end(function(err, res){ if (err.status == 200) { glimpse.emit('data.message.summary.found.remote', []); } }); } };
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function () { request .get('/glimpse/api/messages') .query({ latest: true }) .set('Accept', 'application/json') .end(function(err, res){ if (err.status == 200) { glimpse.emit('data.message.summary.found.remote', []); } }); }, triggerGetDetailsFor: function (requestId) { request .get('/glimpse/api/messages') .query({ context: requestId }) .set('Accept', 'application/json') .end(function(err, res){ if (err.status == 200) { glimpse.emit('data.message.summary.found.remote', []); } }); } };
Make CsvReaderFactory a POJO with static methods
package uk.ac.ebi.atlas.experimentimport.coexpression; import uk.ac.ebi.atlas.utils.CsvReaderFactory; import au.com.bytecode.opencsv.CSVReader; import org.springframework.beans.factory.annotation.Value; import javax.inject.Inject; import javax.inject.Named; import java.nio.file.NoSuchFileException; import java.text.MessageFormat; @Named public class BaselineCoexpressionProfileInputStreamFactory { private final String fileTemplate; @Inject public BaselineCoexpressionProfileInputStreamFactory(@Value("#{configuration['experiment.coexpression_matrix.template']}") String fileTemplate) { this.fileTemplate = fileTemplate; } public BaselineCoexpressionProfileInputStream create(String experimentAccession) throws NoSuchFileException { String tsvGzFilePath = MessageFormat.format(fileTemplate, experimentAccession); CSVReader csvReader = CsvReaderFactory.createForTsvGz(tsvGzFilePath); return new BaselineCoexpressionProfileInputStream(csvReader, tsvGzFilePath); } }
package uk.ac.ebi.atlas.experimentimport.coexpression; import uk.ac.ebi.atlas.utils.CsvReaderFactory; import au.com.bytecode.opencsv.CSVReader; import org.springframework.beans.factory.annotation.Value; import javax.inject.Inject; import javax.inject.Named; import java.nio.file.NoSuchFileException; import java.text.MessageFormat; @Named public class BaselineCoexpressionProfileInputStreamFactory { private final CsvReaderFactory csvReaderFactory; private final String fileTemplate; @Inject public BaselineCoexpressionProfileInputStreamFactory(@Value("#{configuration['experiment.coexpression_matrix.template']}") String fileTemplate, CsvReaderFactory csvReaderFactory) { this.fileTemplate = fileTemplate; this.csvReaderFactory = csvReaderFactory; } public BaselineCoexpressionProfileInputStream create(String experimentAccession) throws NoSuchFileException { String tsvGzFilePath = MessageFormat.format(fileTemplate, experimentAccession); CSVReader csvReader = csvReaderFactory.createTsvGzReader(tsvGzFilePath); return new BaselineCoexpressionProfileInputStream(csvReader, tsvGzFilePath); } }
Use directory path in order to maintain relative path to addon templates
/* jshint node: true */ 'use strict'; const TransformFilter = require('./lib/transform-filter'); const fs = require('fs'); module.exports = { name: 'ember-form-for', included(app) { this._super.included.apply(this, arguments); var controlsDirectory = `${__dirname}/addon/templates/components/controls`; var controlFileList = fs.readdirSync(controlsDirectory); this.options = { targets: [ { pattern: 'components/example-component.hbs', transform: (content, originalPath) => { return buildTemplate(controlFileList); } } ], extensions: ['hbs'] }; }, treeForAddonTemplates: function (tree) { return new TransformFilter(tree, this.options); } }; function buildTemplate(controlFileList) { var hash = controlFileList.reduce((content, controlFileName) => { var controlName = controlFileName.slice(0, -4); var keyName = controlName.replace('-control', ''); return `${content} ${keyName}=(component "controls/${controlName}")`; }, ''); return `{{yield (hash ${hash})}}`; }
/* jshint node: true */ 'use strict'; const TransformFilter = require('./lib/transform-filter'); const fs = require('fs'); module.exports = { name: 'ember-form-for', included(app) { this._super.included.apply(this, arguments); var controlsDirectory = `${app.project.root}/addon/templates/components/controls`; var controlFileList = fs.readdirSync(controlsDirectory); this.options = { targets: [ { pattern: 'components/example-component.hbs', transform: (content, originalPath) => { return buildTemplate(controlFileList); } } ], extensions: ['hbs'] }; }, treeForAddonTemplates: function (tree) { return new TransformFilter(tree, this.options); } }; function buildTemplate(controlFileList) { var hash = controlFileList.reduce((content, controlFileName) => { var controlName = controlFileName.slice(0, -4); var keyName = controlName.replace('-control', ''); return `${content} ${keyName}=(component "controls/${controlName}")`; }, ''); return `{{yield (hash ${hash})}}`; }
Remove header from gold script file
""" python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv') x = data('time') y = data('air_temp_set_1') axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1') # Axes Settings axes1.legend(loc='lower right') axes0.set_title('Snow Data') # y1-axis Settings axes1.set_ylabel('Air Temperature [C]') axes1.set_ylim([0.0, 35.94]) # Show figure and write pdf plt.show() figure.savefig("output.pdf")
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html """ python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_jan_2016.csv') x = data('time') y = data('air_temp_set_1') axes1.plot(x, y, marker='', linewidth=5.0, color=[0.2, 0.627, 0.173, 1.0], markersize=1, linestyle=u'--', label='air_temp_set_1') # Axes Settings axes1.legend(loc='lower right') axes0.set_title('Snow Data') # y1-axis Settings axes1.set_ylabel('Air Temperature [C]') axes1.set_ylim([0.0, 35.94]) # Show figure and write pdf plt.show() figure.savefig("output.pdf")
Remove synonyms of primitive statuses Refers #1
/* Copyright 2015 Anton Vorobyev 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 co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; }
/* Copyright 2015 Anton Vorobyev 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 co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes successfully, synonym of SUCCESS */ public static final int OK = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; /** * Exit code returned when execution finishes failingly, synonym of FAILURE */ public static final int BAD = 1; }
Test the value passed to the growl manager component
import Ember from 'ember'; import { test, moduleForComponent } from 'ember-qunit'; var testNotification = {options: {type: 'error', twitch: true}}; moduleForComponent('growl-instance', 'Growl Instance'); test('assert that the element class exists', function() { expect(1); ok(this.subject().classNames.indexOf('growl-instance') > -1, 'CSS class exists'); }); test('assert that the notification type is reflected as a classname', function() { expect(1); var subject = this.subject(); subject.set('notification', testNotification); equal(subject._classStringForProperty('type'), 'error', 'The instance has a class of error'); }); test('assert that the instance will close when clicked', function() { expect(3); var subject = this.subject(); subject.set('notification', testNotification); subject.sendAction = function(name, value) { equal(name, 'action', 'The parent action was called'); equal(value, testNotification, 'The notification is passed to the parent action'); }; subject.click(); // now override destroyAlert to make sure it is what called the action subject.destroyAlert = function() { ok(true, 'The instance was closed'); }; subject.click(); });
import Ember from 'ember'; import { test, moduleForComponent } from 'ember-qunit'; var testNotification = {options: {type: 'error', twitch: true}}; moduleForComponent('growl-instance', 'Growl Instance'); test('assert that the element class exists', function() { expect(1); ok(this.subject().classNames.indexOf('growl-instance') > -1, 'CSS class exists'); }); test('assert that the notification type is reflected as a classname', function() { expect(1); var subject = this.subject(); subject.set('notification', testNotification); equal(subject._classStringForProperty('type'), 'error', 'The instance has a class of error'); }); test('assert that the instance will close when clicked', function() { expect(2); var subject = this.subject(); subject.sendAction = function(name, value) { equal(name, 'action', 'The parent action was called'); }; subject.click(); // now override destroyAlert to make sure it is what called the action subject.destroyAlert = function() { ok(true, 'The instance was closed'); }; subject.click(); });
Move className onto a div wrapping ion-icon This is to avoid overwriting ion-icons own classnames that it sets on itself. Overwriting these causes the icon to become invisible.
// @flow import styles from './Icon.css'; type Props = { /** Name of the icon can be found on the webpage*/ name: string, scaleOnHover?: boolean, className?: string, size?: number, style?: Object, }; /** * Render an Icon like this with the name of your icon: * * <Icon name="add" /> * * Names can be found here: * https://ionic.io/ionicons * */ const Icon = ({ name = 'star', scaleOnHover = false, className, style = {}, size = 24, ...props }: Props) => { return ( <div className={className} style={{ fontSize: `${size.toString()}px`, ...style, }} {...(props: Object)} > <ion-icon name={name}></ion-icon> </div> ); }; Icon.Badge = ({ badgeCount, ...props }: Props & { badgeCount: number }) => { const icon = <Icon {...props} />; if (!badgeCount) { return icon; } return ( <div style={{ position: 'relative' }}> <span className={styles.badge}>{badgeCount}</span> {icon} </div> ); }; Icon.Badge.displayName = 'IconBadge'; export default Icon;
// @flow import styles from './Icon.css'; type Props = { /** Name of the icon can be found on the webpage*/ name: string, scaleOnHover?: boolean, className?: string, size?: number, style?: Object, }; /** * Render an Icon like this with the name of your icon: * * <Icon name="add" /> * * Names can be found here: * https://ionic.io/ionicons * */ const Icon = ({ name = 'star', scaleOnHover = false, className, style = {}, size = 24, ...props }: Props) => { return ( <ion-icon name={name} class={className} style={{ fontSize: `${size.toString()}px`, lineHeight: 2, ...style, }} {...(props: Object)} ></ion-icon> ); }; Icon.Badge = ({ badgeCount, ...props }: Props & { badgeCount: number }) => { const icon = <Icon {...props} />; if (!badgeCount) { return icon; } return ( <div style={{ position: 'relative' }}> <span className={styles.badge}>{badgeCount}</span> {icon} </div> ); }; Icon.Badge.displayName = 'IconBadge'; export default Icon;
Reduce the URL timestamp length and avoid using emulated longs git-svn-id: 558837a20bd4f75dae4ad66848e1ea511a65cec4@35 0d5c52f8-90a3-11de-8ad7-8b2c2f1e2016
/* * Copyright 2009 Richard Zschech. * * 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 net.zschech.gwt.comet.client.impl; import net.zschech.gwt.comet.client.CometClient; import net.zschech.gwt.comet.client.CometListener; import com.google.gwt.core.client.Duration; /** * This is the base class for the comet implementations * * @author Richard Zschech */ public abstract class CometTransport { protected CometClient client; protected CometListener listener; public void initiate(CometClient client, CometListener listener) { this.client = client; this.listener = listener; } public abstract void connect(); public abstract void disconnect(); public String getUrl() { String url = client.getUrl(); return url + (url.contains("?") ? "&" : "?") + Integer.toString((int) Duration.currentTimeMillis(), Character.MAX_RADIX); } }
/* * Copyright 2009 Richard Zschech. * * 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 net.zschech.gwt.comet.client.impl; import net.zschech.gwt.comet.client.CometClient; import net.zschech.gwt.comet.client.CometListener; /** * This is the base class for the comet implementations * * @author Richard Zschech */ public abstract class CometTransport { protected CometClient client; protected CometListener listener; public void initiate(CometClient client, CometListener listener) { this.client = client; this.listener = listener; } public abstract void connect(); public abstract void disconnect(); public String getUrl() { String url = client.getUrl(); return url + (url.contains("?") ? "&" : "?") + Long.toString(System.currentTimeMillis(), Character.MAX_RADIX); } }
Fix warning in test suite when running under Django 1.11
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ['id'] @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
Set text to same text like in translation So that current translations are working
<?php class Kwc_Statistics_Opt_Form extends Kwc_Abstract_Composite_Form { protected function _initFields() { $this->add(new Kwf_Form_Field_TextArea('text_opt_in', trlKwf('Text for opt-in'))) ->setDefaultValue(trlKwf('Cookies are set when visiting this webpage. Click to deactivate cookies.')) ->setWidth(500) ->setHeight(100); $this->add(new Kwf_Form_Field_TextArea('text_opt_out', trlKwf('Text for opt-out'))) ->setDefaultValue(trlKwf('No cookies are set when visiting this webpage. Click to activate cookies.')) ->setWidth(500) ->setHeight(100); } }
<?php class Kwc_Statistics_Opt_Form extends Kwc_Abstract_Composite_Form { protected function _initFields() { $this->add(new Kwf_Form_Field_TextArea('text_opt_in', trlKwf('Text for opt-in'))) ->setDefaultValue(trlKwf('Tracking cookies are set when visiting this webpage. Click to deactivate tracking cookies.')) ->setWidth(500) ->setHeight(100); $this->add(new Kwf_Form_Field_TextArea('text_opt_out', trlKwf('Text for opt-out'))) ->setDefaultValue(trlKwf('No tracking cookies are set when visiting this webpage. Click to activate tracking cookies.')) ->setWidth(500) ->setHeight(100); } }
Update error function to arrow function
'use strict'; /** * Module dependencies. */ const express = require('express'); const compression = require('compression'); const bodyParser = require('body-parser'); const router = require('./routes/routes'); /** * Express configuration. */ const app = express(); app.use(compression()); // parse application/json app.use(bodyParser.json()); // support encoded bodies app.use(bodyParser.urlencoded({ extended: true })); app.use(router); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); /** * Catch all error requests */ app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env')); }); module.exports = app;
'use strict'; /** * Module dependencies. */ const express = require('express'); const compression = require('compression'); const bodyParser = require('body-parser'); const router = require('./routes/routes'); /** * Express configuration. */ const app = express(); app.use(compression()); // parse application/json app.use(bodyParser.json()); // support encoded bodies app.use(bodyParser.urlencoded({ extended: true })); app.use(router); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); /** * Catch all error requests */ app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); }); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env')); }); module.exports = app;
Package name of configuration changed
/* * Copyright 2014 The original authors * * 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.vaadin.spring; import org.springframework.context.annotation.Import; import org.vaadin.spring.config.VaadinConfiguration; import java.lang.annotation.*; /** * Brings in the machinery to setup Spring + Vaadin applications. * * @author Josh Long (josh@joshlong.com) * @author Petter Holmström (petter@vaadin.com) */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(VaadinConfiguration.class) public @interface EnableVaadin { }
/* * Copyright 2014 The original authors * * 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.vaadin.spring; import org.springframework.context.annotation.Import; import org.vaadin.spring.internal.VaadinConfiguration; import java.lang.annotation.*; /** * Brings in the machinery to setup Spring + Vaadin applications. * * @author Josh Long (josh@joshlong.com) * @author Petter Holmström (petter@vaadin.com) */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(VaadinConfiguration.class) public @interface EnableVaadin { }
Check that command is not null before saving.
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.storage.filesystem; import org.spine3.server.storage.CommandStorage; import org.spine3.server.storage.CommandStoreRecord; import static com.google.common.base.Preconditions.checkNotNull; public class FileSystemCommandStorage extends CommandStorage { @Override protected void write(CommandStoreRecord record) { checkNotNull(record, "CommandRecord shouldn't be null."); Helper.write(record); } }
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.storage.filesystem; import org.spine3.server.storage.CommandStorage; import org.spine3.server.storage.CommandStoreRecord; public class FileSystemCommandStorage extends CommandStorage { @Override protected void write(CommandStoreRecord record) { Helper.write(record); } }
Return DCM probabilities as MultiIndexed Series Instead of separately returning probabilities and alternatives information this groups them all together. The probabilities have a MultiIndex with chooser IDs on the outside and alternative IDs on the inside.
import numpy.testing as npt import pandas as pd import pandas.util.testing as pdt import pytest from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( {'var2': range(10, 20), 'var3': range(20, 30)}, index=pd.Index([x for x in 'abcdefghij'], name='thing_id')) def test_interaction_dataset_sim(choosers, alternatives): sample, merged, chosen = inter.mnl_interaction_dataset( choosers, alternatives, len(alternatives)) # chosen should be len(choosers) rows * len(alternatives) cols assert chosen.shape == (len(choosers), len(alternatives)) assert chosen[:, 0].sum() == len(choosers) assert chosen[:, 1:].sum() == 0 npt.assert_array_equal( sample, list(alternatives.index.values) * len(choosers)) assert len(merged) == len(choosers) * len(alternatives) npt.assert_array_equal(merged.index.values, sample) assert list(merged.columns) == [ 'var2', 'var3', 'join_index', 'thing_id', 'var1'] assert merged['join_index'].isin(choosers.index).all()
import numpy.testing as npt import pandas as pd import pandas.util.testing as pdt import pytest from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( {'var2': range(10, 20), 'var3': range(20, 30)}, index=pd.Index([x for x in 'abcdefghij'], name='thing_id')) def test_interaction_dataset_sim(choosers, alternatives): sample, merged, chosen = inter.mnl_interaction_dataset( choosers, alternatives, len(alternatives)) # chosen should be len(choosers) rows * len(alternatives) cols assert chosen.shape == (len(choosers), len(alternatives)) assert chosen[:, 0].sum() == len(choosers) assert chosen[:, 1:].sum() == 0 npt.assert_array_equal( sample, list(alternatives.index.values) * len(choosers)) assert len(merged) == len(choosers) * len(alternatives) npt.assert_array_equal(merged.index.values, sample) assert list(merged.columns) == [ 'var2', 'var3', 'join_index', 'thing_id', 'var1']
Allow single service object for workers
module.exports = function(services) { var self = this; if(!Array.isArray(services)) { services = [services]; } services.forEach(function(s) { if(typeof s != 'object') { throw new Error('Service is not an object'); } if(typeof s.serviceType != 'string') { throw new Error('Service type not string'); } if(!Array.isArray(s.serviceInstances)) { throw new Error('Service Instances not array'); } s.serviceInstances.forEach(function(serviceInstance) { var serviceName = s.serviceType+'.'+serviceInstance; if(self.services.indexOf(serviceName) > -1) { throw new Error('Service '+serviceName+' already registered'); } self.services.push(serviceName); }); }); return this.services; };
module.exports = function(services) { var self = this; if(!Array.isArray(services)) { throw new Error('Services is not array'); } services.forEach(function(s) { if(typeof s.serviceType != 'string') { throw new Error('Service type not string'); } if(!Array.isArray(s.serviceInstances)) { throw new Error('Service Instances not array'); } s.serviceInstances.forEach(function(serviceInstance) { var serviceName = s.serviceType+'.'+serviceInstance; if(self.services.indexOf(serviceName) > -1) { throw new Error('Service '+serviceName+' already registered'); } self.services.push(serviceName); }); }); return this.services; };
Use binary zip adapter prior to ZIpExtension
<?php /* * This file is part of Zippy. * * (c) Alchemy <info@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alchemy\Zippy\FileStrategy; use Alchemy\Zippy\Adapter\AdapterContainer; class ZipFileStrategy implements FileStrategyInterface { private $container; public function __construct(AdapterContainer $container) { $this->container = $container; } /** * {@inheritdoc} */ public function getAdapters() { return array( $this->container['Alchemy\\Zippy\\Adapter\\ZipAdapter'], $this->container['Alchemy\\Zippy\\Adapter\\ZipExtensionAdapter'], ); } /** * {@inheritdoc} */ public function getFileExtension() { return 'zip'; } }
<?php /* * This file is part of Zippy. * * (c) Alchemy <info@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alchemy\Zippy\FileStrategy; use Alchemy\Zippy\Adapter\AdapterContainer; class ZipFileStrategy implements FileStrategyInterface { private $container; public function __construct(AdapterContainer $container) { $this->container = $container; } /** * {@inheritdoc} */ public function getAdapters() { return array( $this->container['Alchemy\\Zippy\\Adapter\\ZipExtensionAdapter'], $this->container['Alchemy\\Zippy\\Adapter\\ZipAdapter'], ); } /** * {@inheritdoc} */ public function getFileExtension() { return 'zip'; } }
Remove table row links init method
/* ========================================================================== Table Row Links Mixin for adding row link click functionality to table organism. ========================================================================== */ 'use strict'; var closest = require( 'atomic-component/src/utilities/dom-closest' ).closest; var TableRowLinks = { events: { 'click tbody tr': 'onRowLinkClick' }, ui: { base: '.o-table__row-links' }, /** * Handle a click of the table. * * @param {Object} event Mouse event for click on the table. */ onRowLinkClick: function( event ) { var target = event.target; if( target && target.tagName === 'A' ) { return } target = closest( event.target, 'tr' ); var link = target.querySelector( 'a' ); if( link ) window.location = link.getAttribute( 'href' ); } }; module.exports = TableRowLinks;
/* ========================================================================== Table Row Links Mixin for adding row link click functionality to table organism. ========================================================================== */ 'use strict'; var closest = require( 'atomic-component/src/utilities/dom-closest' ).closest; var TableRowLinks = { events: { 'click tbody tr': 'onRowLinkClick' }, ui: { base: '.o-table__row-links' }, /** * Handle a click of the table. * * @param {Object} event Mouse event for click on the table. */ onRowLinkClick: function( event ) { var target = event.target; if( target && target.tagName === 'A' ) { return } target = closest( event.target, 'tr' ); var link = target.querySelector( 'a' ); if( link ) window.location = link.getAttribute( 'href' ); }, /** * Handle initilization of Table Row Links. Added for standalone * use cases. * */ init: function() { var elements = document.querySelector( TableRowLinks.ui.base ); for ( var i = 0; i < elements.length; ++i ) { if( elements[i].hasAttribute( 'data-bound' ) === false ) { elements[i].addEventListener( 'click', table, TableRowLinks.onRowLinkClick ); } } } }; module.exports = TableRowLinks;
Fix variable names in __all__
from luigi_td.bulk_import import BulkImport from luigi_td.client import ResultProxy from luigi_td.config import Config, get_config from luigi_td.task import DatabaseTask, TableTask, Query from luigi_td.targets.result import ResultTarget from luigi_td.targets.s3 import S3ResultTarget from luigi_td.targets.tableau import TableauServerResultTarget, TableauOnlineResultTarget from luigi_td.targets.td import DatabaseTarget, TableTarget, SchemaError __all__ = [ # bulk_import 'BulkImport', # client 'ResultProxy', # config 'Config', 'get_config', # task 'DatabaseTask', 'TableTask', 'Query', # targets.result 'ResultTarget', # targets.s3 'S3ResultTarget', # targets.tableau 'TableauServerResultTarget', 'TableauOnlineResultTarget', # targets.td 'DatabaseTarget', 'TableTarget', 'SchemaError', ]
from luigi_td.bulk_import import BulkImport from luigi_td.client import ResultProxy from luigi_td.config import Config, get_config from luigi_td.task import DatabaseTask, TableTask, Query from luigi_td.targets.result import ResultTarget from luigi_td.targets.s3 import S3ResultTarget from luigi_td.targets.tableau import TableauServerResultTarget, TableauOnlineResultTarget from luigi_td.targets.td import DatabaseTarget, TableTarget, SchemaError __all__ = [ # bulk_import 'BulkImport', # client 'ResultProxy', # config 'Config', 'get_config' # task 'DatabaseTask', 'TableTask', 'Query', # targets.result 'ResultTarget' # targets.s3 'S3ResultTarget', # targets.tableau 'TableauServerResultTarget', 'TableauOnlineResultTarget', # targets.td 'DatabaseTarget', 'TableTarget', 'SchemaError', ]
Add webapp dependency to test-in-browser This ensures the app created for test-packages will have the default Cordova plugins installed.
Package.describe({ summary: "Run tests interactively in the browser", version: '1.0.8-plugins.1', documentation: null }); Package.onUse(function (api) { // XXX this should go away, and there should be a clean interface // that tinytest and the driver both implement? api.use('tinytest'); api.use('bootstrap@1.0.1'); api.use('underscore'); api.use('session'); api.use('reload'); api.use(['webapp', 'blaze', 'templating', 'spacebars', 'ddp', 'tracker'], 'client'); api.addFiles('diff_match_patch_uncompressed.js', 'client'); api.addFiles([ 'driver.css', 'driver.html', 'driver.js' ], "client"); api.use('autoupdate', 'server', {weak: true}); api.use('random', 'server'); api.addFiles('autoupdate.js', 'server'); });
Package.describe({ summary: "Run tests interactively in the browser", version: '1.0.8-plugins.0', documentation: null }); Package.onUse(function (api) { // XXX this should go away, and there should be a clean interface // that tinytest and the driver both implement? api.use('tinytest'); api.use('bootstrap@1.0.1'); api.use('underscore'); api.use('session'); api.use('reload'); api.use(['blaze', 'templating', 'spacebars', 'ddp', 'tracker'], 'client'); api.addFiles('diff_match_patch_uncompressed.js', 'client'); api.addFiles([ 'driver.css', 'driver.html', 'driver.js' ], "client"); api.use('autoupdate', 'server', {weak: true}); api.use('random', 'server'); api.addFiles('autoupdate.js', 'server'); });
Add Event Listener to window.resize
//Get the begin and end coordinates of selction function getSelectionEnds() { var success = false, x1 = 0, y1 = 0, x2 = 0, y2 = 0; var sel = window.getSelection() if (sel.rangeCount > 0){ var range_rects = sel.getRangeAt(0).getClientRects(); if (range_rects.length > 0){ //fail if zero success = true; var rect_first = range_rects[0]; x1 = rect_first.left; y1 = rect_first.top; var rect_last = range_rects[range_rects.length - 1]; x2 = rect_last.right; y2 = rect_last.bottom; } } return {success: success, x1: x1, y1: y1, x2: x2, y2: y2}; } // A side note: use event listener, not inline event handlers (e.g., "onclick") // new inline events could overwrite any existing inline event handlers document.addEventListener("mouseup", function(event) { chrome.runtime.sendMessage(getSelectionEnds(), function(response) {}); }); window.addEventListener("resize", function(event) { chrome.runtime.sendMessage(getSelectionEnds(), function(response) {}); });
//Get the begin and end coordinates of selction function getSelectionEnds() { var success = false, x1 = 0, y1 = 0, x2 = 0, y2 = 0; var sel = window.getSelection() if (sel.rangeCount > 0){ var range_rects = sel.getRangeAt(0).getClientRects(); if (range_rects.length > 0){ //fail if zero success = true; var rect_first = range_rects[0]; x1 = rect_first.left; y1 = rect_first.top; var rect_last = range_rects[range_rects.length - 1]; x2 = rect_last.right; y2 = rect_last.bottom; } } return {success: success, x1: x1, y1: y1, x2: x2, y2: y2}; } document.addEventListener("mouseup", function(event) { chrome.runtime.sendMessage(getSelectionEnds(), function(response) {}); });
Connect on existing tabs when activating the plugin.
# coding: utf8 # Copyright © 2011 Kozea # Licensed under a 3-clause BSD license. """ Strip trailing whitespace before saving. """ from gi.repository import GObject, Gedit class WhiteSpaceTerminator(GObject.Object, Gedit.WindowActivatable): """Strip trailing whitespace before saving.""" window = GObject.property(type=Gedit.Window) def do_activate(self): self.window.connect("tab-added", self.on_tab_added) for document in self.window.get_documents(): document.connect("save", self.on_document_save) def on_tab_added(self, window, tab, data=None): tab.get_document().connect("save", self.on_document_save) def on_document_save(self, document, location, encoding, compression, flags, data=None): for i, text in enumerate(document.props.text.rstrip().split("\n")): strip_stop = document.get_iter_at_line(i) strip_stop.forward_to_line_end() strip_start = strip_stop.copy() strip_start.backward_chars(len(text) - len(text.rstrip())) document.delete(strip_start, strip_stop) document.delete(strip_start, document.get_end_iter())
# coding: utf8 # Copyright © 2011 Kozea # Licensed under a 3-clause BSD license. """ Strip trailing whitespace before saving. """ from gi.repository import GObject, Gedit class WhiteSpaceTerminator(GObject.Object, Gedit.WindowActivatable): """Strip trailing whitespace before saving.""" window = GObject.property(type=Gedit.Window) def do_activate(self): self.window.connect("tab-added", self.on_tab_added) def on_tab_added(self, window, tab, data=None): tab.get_document().connect("save", self.on_document_save) def on_document_save(self, document, location, encoding, compression, flags, data=None): for i, text in enumerate(document.props.text.rstrip().split("\n")): strip_stop = document.get_iter_at_line(i) strip_stop.forward_to_line_end() strip_start = strip_stop.copy() strip_start.backward_chars(len(text) - len(text.rstrip())) document.delete(strip_start, strip_stop) document.delete(strip_start, document.get_end_iter())
Remove useless comment about returning a null mouse. Access mouse through ForPlay.mouse().
/** * Copyright 2010 The ForPlay Authors * * 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 forplay.core; /** * Generic platform interface. New platforms are defined as implementations of this interface. */ public interface Platform { Audio audio(); Graphics graphics(); AssetManager assetManager(); Json json(); Keyboard keyboard(); Log log(); Net net(); Pointer pointer(); Mouse mouse(); Storage storage(); Analytics analytics(); float random(); void run(Game game); double time(); RegularExpression regularExpression(); void openURL(String url); }
/** * Copyright 2010 The ForPlay Authors * * 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 forplay.core; /** * Generic platform interface. New platforms are defined as implementations of this interface. */ public interface Platform { Audio audio(); Graphics graphics(); AssetManager assetManager(); Json json(); Keyboard keyboard(); Log log(); Net net(); Pointer pointer(); /** * Return the mouse if it is supported, or null otherwise. * * @return the mouse if it is supported, or null otherwise. */ Mouse mouse(); Storage storage(); Analytics analytics(); float random(); void run(Game game); double time(); RegularExpression regularExpression(); void openURL(String url); }
chore(sms): Store allowed phone numbers in a Set
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' module.exports = (config, Settings, log) => { class AllowedPhoneNumbers extends Settings { constructor(phoneNumbers) { super('allowedPhoneNumbers') this.setAll(phoneNumbers) } isAllowed(phoneNumber) { return this.phoneNumbers.has(phoneNumber) } setAll(phoneNumbers) { this.phoneNumbers = new Set(phoneNumbers) } validate(phoneNumbers) { if (!Array.isArray(phoneNumbers)) { log.error({ op: 'allowedPhoneNumbers.validate.invalid', data: phoneNumbers }) throw new Settings.Missing('invalid allowedPhoneNumbers from memcache') } return phoneNumbers } toJSON() { return Array.from(this.phoneNumbers) } } return new AllowedPhoneNumbers(config.allowedPhoneNumbers || []) }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' module.exports = (config, Settings, log) => { class AllowedPhoneNumbers extends Settings { constructor(phoneNumbers) { super('allowedPhoneNumbers') this.setAll(phoneNumbers) } isAllowed(phoneNumber) { return phoneNumber in this.phoneNumbers } setAll(phoneNumbers) { this.phoneNumbers = {} phoneNumbers.forEach((phoneNumber) => { this.phoneNumbers[phoneNumber] = true }) return Object.keys(this.phoneNumbers) } validate(phoneNumbers) { if (!Array.isArray(phoneNumbers)) { log.error({ op: 'allowedPhoneNumbers.validate.invalid', data: phoneNumbers }) throw new Settings.Missing('invalid allowedPhoneNumbers from memcache') } return phoneNumbers } toJSON() { return Object.keys(this.phoneNumbers) } } return new AllowedPhoneNumbers(config.allowedPhoneNumbers || []) }
Add model for borrow requests
import * as Sequelize from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; const borrowRequestSchema = (sequelize) => { const BorrowRequests = sequelize.define('BorrowRequests', { id: { type: Sequelize.UUID, allowNull: false, primaryKey: true, defaultValue: uuidv4(), }, reason: { type: Sequelize.ENUM, values: ['Research', 'Assignment', 'Leisure reading'], allowNull: false, }, comments: { type: Sequelize.TEXT, allowNull: false, }, returnDate: { type: Sequelize.DATE, allowNull: false, }, status: { type: Sequelize.STRING, defaultValue: 'Pending', allowNull: false, }, }); BorrowRequests.associate = (models) => { BorrowRequests.belongsTo(models.User, { foreignKey: 'userId', as: 'userBorrowRequests', onDelete: 'CASCADE', }); BorrowRequests.belongsTo(models.Book, { foreignKey: 'bookId', as: 'borrowRequests', }); }; return BorrowRequests; }; export default borrowRequestSchema;
import * as Sequelize from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; const borrowRequestSchema = (sequelize) => { const BorrowRequests = sequelize.define('BorrowRequests', { id: { type: Sequelize.UUID, allowNull: false, primaryKey: true, defaultValue: uuidv4(), }, reason: { type: Sequelize.ENUM, values: ['Research', 'Assignment', 'Leisure reading'], allowNull: false, }, comments: { type: Sequelize.TEXT, allowNull: false, }, returnDate: { type: Sequelize.DATE, allowNull: false, }, }); BorrowRequests.associate = (models) => { BorrowRequests.belongsTo(models.User, { foreignKey: 'userId', as: 'userBorrowRequests', onDelete: 'CASCADE', }); BorrowRequests.belongsTo(models.Book, { foreignKey: 'bookId', as: 'borrowRequests', }); }; return BorrowRequests; }; export default borrowRequestSchema;
Fix new post textare margin
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) 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/>. */ import React, { Component } from 'react'; import _ from 'lodash'; export default class EditPostShort extends Component { updateNewPostTags = (tags) => { console.info(tags); } render () { let value = ''; if (!_.isUndefined(this.props.post)) { value = this.props.post.text; } return ( <div className="layout__row"> <textarea className="input input-textarea input-block" defaultValue={value} name="text" placeholder="Share education related resources, your perspective" /> </div> ) } }
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) 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/>. */ import React, { Component } from 'react'; import _ from 'lodash'; export default class EditPostShort extends Component { updateNewPostTags = (tags) => { console.info(tags); } render () { let value = ''; if (!_.isUndefined(this.props.post)) { value = this.props.post.text; } return ( <div> <div className="layout__row"> <textarea className="input input-textarea input-block" defaultValue={value} name="text" placeholder="Share education related resources, your perspective" /> </div> </div> ) } }